text:
require "ipaddr"
require "digest"

require "rack/bug/options"
require "rack/bug/render"

Dir[File.dirname(__FILE__) + "/panels/*.rb"].each do |panel_name|
  require "rack/bug/panels/" + File.basename(panel_name)
end

module Rack
  module Bug

    class RackStaticBugAvoider
      def initialize(app, static_app)
        @app = app
        @static_app = static_app
      end

      def call(env)
        if env["PATH_INFO"] =~ /^\/__rack_bug__/
          @static_app.call(env)
        else
          @app.call(env)
        end
      end
    end

    class Toolbar
      include Options
      include Render

      MIME_TYPES = ["text/html", "application/xhtml+xml"]

      def initialize(app, options = {})
        @app = asset_server(app)
        initialize_options options
        instance_eval(&block) if block_given?
      end

      def asset_server(app)
        RackStaticBugAvoider.new(app, Rack::Static.new(app, :urls => ["/__rack_bug__"], :root => public_path))
      end

      def public_path
        ::File.expand_path(::File.dirname(__FILE__) + "/../bug/public")
      end

      def call(env)
        env.replace @default_options.merge(env)
        @env = env
        @original_request = Request.new(@env)

        if toolbar_requested? && ip_authorized? && ssl_authorized? && password_authorized?
          dispatch
        else
          pass
        end
      end

      def pass
        @app.call(@env)
      end

      def dispatch
        @env["rack-bug.panels"] = []

        Rack::Bug.enable
        status, headers, body = builder.call(@env)
        Rack::Bug.disable

        @response = Rack::Response.new(body, status, headers)

        if @response.redirect? && options["rack-bug.intercept_redirects"]
          intercept_redirect
        elsif modify?
          inject_toolbar
        end

        return @response.to_a
      end

      def intercept_redirect
        redirect_to = @response.location
        new_body = render_template("redirect", :redirect_to => @response.location)
        new_response = Rack::Response.new(new_body, 200, { "Content-Type" => "text/html" })
        new_response["Content-Length"] = new_body.size.to_s
        @response = new_response
      end

      def xhr?
        @original_request.env['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' || @original_request.env["X-Requested-With"] == "XMLHttpRequest"
      end

      def ssl_authorized?
        !options['rack-bug.ssl_required'] || (@original_request.env['HTTPS'] == 'on' || @original_request.env['HTTP_X_FORWARDED_PROTO'] == 'https')
      end

      def toolbar_requested?
        @original_request.cookies["rack_bug_enabled"]
      end

      def ip_authorized?
        return true unless options["rack-bug.ip_masks"]

        options["rack-bug.ip_masks"].any? do |ip_mask|
          ip_mask.include?(IPAddr.new(@original_request.ip))
        end
      end

      def password_authorized?
        return true unless options["rack-bug.password"]

        expected_sha = Digest::SHA1.hexdigest ["rack_bug", options["rack-bug.password"]].join(":")
        actual_sha = @original_request.cookies["rack_bug_password"]

        actual_sha == expected_sha
      end

      def modify?
        @response.ok? && !xhr? && MIME_TYPES.include?(@response.content_type.split(";").first)
      end

      def builder
        builder = Rack::Builder.new

        options["rack-bug.panel_classes"].each do |panel_class|
          builder.use panel_class
        end

        builder.run @app

        return builder
      end

      def inject_toolbar
        full_body = @response.body.join
        if full_body =~ /<\/body>/
          full_body.sub! /<\/body>/, render + "</body>"
        else
          full_body << render
        end

        @response["Content-Length"] = full_body.size.to_s
        @response.body = [full_body]
      end

      def render
        render_template("toolbar", :panels => @env["rack-bug.panels"].reverse)
      end

    end

  end
end


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_Experimental_Director_DirectorPlayer : LuaObject {
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int constructor(IntPtr l) {
		try {
			UnityEngine.Experimental.Director.DirectorPlayer o;
			o=new UnityEngine.Experimental.Director.DirectorPlayer();
			pushValue(l,true);
			pushValue(l,o);
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int Play(IntPtr l) {
		try {
			int argc = LuaDLL.lua_gettop(l);
			if(argc==2){
				UnityEngine.Experimental.Director.DirectorPlayer self=(UnityEngine.Experimental.Director.DirectorPlayer)checkSelf(l);
				UnityEngine.Experimental.Director.Playable a1;
				checkType(l,2,out a1);
				self.Play(a1);
				pushValue(l,true);
				return 1;
			}
			else if(argc==3){
				UnityEngine.Experimental.Director.DirectorPlayer self=(UnityEngine.Experimental.Director.DirectorPlayer)checkSelf(l);
				UnityEngine.Experimental.Director.Playable a1;
				checkType(l,2,out a1);
				System.Object a2;
				checkType(l,3,out a2);
				self.Play(a1,a2);
				pushValue(l,true);
				return 1;
			}
			pushValue(l,false);
			LuaDLL.lua_pushstring(l,"No matched override function to call");
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int Stop(IntPtr l) {
		try {
			UnityEngine.Experimental.Director.DirectorPlayer self=(UnityEngine.Experimental.Director.DirectorPlayer)checkSelf(l);
			self.Stop();
			pushValue(l,true);
			return 1;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int SetTime(IntPtr l) {
		try {
			UnityEngine.Experimental.Director.DirectorPlayer self=(UnityEngine.Experimental.Director.DirectorPlayer)checkSelf(l);
			System.Double a1;
			checkType(l,2,out a1);
			self.SetTime(a1);
			pushValue(l,true);
			return 1;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int GetTime(IntPtr l) {
		try {
			UnityEngine.Experimental.Director.DirectorPlayer self=(UnityEngine.Experimental.Director.DirectorPlayer)checkSelf(l);
			var ret=self.GetTime();
			pushValue(l,true);
			pushValue(l,ret);
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int SetTimeUpdateMode(IntPtr l) {
		try {
			UnityEngine.Experimental.Director.DirectorPlayer self=(UnityEngine.Experimental.Director.DirectorPlayer)checkSelf(l);
			UnityEngine.Experimental.Director.DirectorUpdateMode a1;
			checkEnum(l,2,out a1);
			self.SetTimeUpdateMode(a1);
			pushValue(l,true);
			return 1;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int GetTimeUpdateMode(IntPtr l) {
		try {
			UnityEngine.Experimental.Director.DirectorPlayer self=(UnityEngine.Experimental.Director.DirectorPlayer)checkSelf(l);
			var ret=self.GetTimeUpdateMode();
			pushValue(l,true);
			pushEnum(l,(int)ret);
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	static public void reg(IntPtr l) {
		getTypeTable(l,"UnityEngine.Experimental.Director.DirectorPlayer");
		addMember(l,Play);
		addMember(l,Stop);
		addMember(l,SetTime);
		addMember(l,GetTime);
		addMember(l,SetTimeUpdateMode);
		addMember(l,GetTimeUpdateMode);
		createTypeMetatable(l,constructor, typeof(UnityEngine.Experimental.Director.DirectorPlayer),typeof(UnityEngine.Behaviour));
	}
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="HandheldFriendly" content="true" />
  <title>Brandon Phillips | Web App Engineer</title>

  <!-- Third party CSS stylesheets (that aren't imported through @import and grunt-concat-css) go here -->
  <!-- build:css app.css -->
  <link type="text/css" rel="stylesheet" href="vendor.css">
  <link type="text/css" rel="stylesheet" href="app.css">
  <!-- endbuild -->

  <!-- Dynamically generated by socket.io while server is running -->
  <script src="/socket.io/socket.io.js"></script>

  <!-- JS dependencies (that aren't required through browserify) go here -->
  <!-- build:js app.js -->
  <script src="vendor.js"></script>
  <script src="templates.js"></script>
  <script src="app.js"></script>
  <!-- endbuild -->
</head>
<body ng-app="brph">

<div ui-view></div>

</body>
</html>


text:
<b>Гринберг Вадим Маркович. Группа БПМИ151.</b>

##Актуальность решаемой задачи##

Машинное обучение является одним из самых бурно развивающихся разделов анализа данных и находит применение во множестве различных сфер программирования. Одной из самых горячих тем в настоящее время является обучение с подкреплением (reinforcement learning) и глубокое обучение (deep learning). Эти подходы позволяют решать такие сложные задачи, как классификация или нахождение выигрышных стратегий. К примеру, на основе данных методов была создана программа **AlphaGo**, впервые победившая профессионала игры Го. **AlphaGo** является ярким примером того, что в машинном обучении, применённом к разработке победных стратегий для игр заложен огромный  потенциал. В нашем проекте мы постараемся реализовать алгоритм, использующийся в **AlphaGo** для более простой, но очень похожей игры -- Рэндзю. В планах также изучение различных алгоритмов машинного обучения и нескольких видов как простых, так и очень сложных нейронных сетей.

##Цели

* На основе статьи **Playing Atari with Deep Reinforcement Learning** предложить модель, способную конкурентно играть с человеком.
* Создать собственную программу для игры в Рендзю.
* Разработать и обучить эффективный алгоритм для игры в Рендзю.

##Задачи
Для достижения поставленной цели необходимо выполнить следующие задачи:

1. Изучить основные алгоритмы и методы машинного обучения, в частности: обучение с подкреплением, глубокое обучение.

2. Изучить структуры нейронных сетей.

3. Ознакомиться с игрой Рендзю, понять правила.

4. Сбор данных по играм для обучения.

5. Разработать программу для игры в Рендзю, запрограммировать правила игры.

6. Обучить модель с помощью игры с самой собой, протестировать на пользователях.

7. Улучшить эффективность алгоритма до оптимального (относительно человека) уровня.

8. Создать удобный графический интерфейс для игры в Рендзю.

##Технологические решения##
* Язык программирования Python3 -- используем в силу простоты и удобства. Кроме того, в данном языке реализовано большое количество научных библиотек для машинного обучения, позволяющих охватить больший спектр задач и существенно выиграть в скорости.
* В частности, мы будем использовать библиотеки Numpy -- работа с линейной алгеброй, Theano и Tensorflow -- обучение нейронных сетей, Keras -- удобный и эффективный интерпретатор архитектуры нейронных сетей.
* Кроме того, будет использоваться Jupyter Notebook -- одна из лучших сред программирования для оформления исследовательских отчётов параллельно с решением задачи.
* В планах имеется вычислять на видеокарте для повышения прозводительности -- для этого будем использовать CUDA.
* В случае, если программа работает медленно, можно воспользоваться облачными вычислениями при помощи aws, google, icloud.

##План##

1. Выполнение нескольких лабораторных работ для изучения и закрепления различных методов машинного обучения, в частности -- градиентный спуск и полносвязные нейросети. В ходе работы идёт ознакомление с используемыми библиотеками. Сроки: конец октября -- начало января.
2. Построение начальной архитектуры сети, представление игры в программе, поиск по дереву и работа с данными -- генерация выборки и обучение. Кроме того, планируется обсуждение разных статей на соответствующие темы с ментором. Сроки: начало января -- начало февраля.
3. Создание первоначальной работающей версии нейронной сети, её обучение на играх Рэндзю. Сроки: начало февраля -- конец марта.
4. Доработка нейронной сети, повышение качества обучения, реализация алгоритма обучения с подкреплением и глубокого обучения в рамках задачи Рэндзю. Конкурс по качеству програмы. Сроки: конец марта -- середина мая.
5. Редактирование и оформление программы, возможное создание интерфейса. Сроки: середина мая -- начало июня.


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

namespace StarWRPG.Models
{
    public class ZabrakPreset : SpeciesPreset
    {
        public override string SpeciesName
        {
            get { return "Zabrak"; }
        }
        public override string SpecialAbilities
        {
            get { return "Zabrak begin the game with one rank in Survival." + AUTOMATIC; }
        }
        public override uint MaxWounds
        {
            get { return 10; }
        }
        public override uint MaxStrain
        {
            get { return 10; }
        }
        public override uint StartingXP
        {
            get { return 100; }
        }

        public override Characteristics InitializeCharacteristics()
        {
            return new Characteristics(2, 2, 2, 2, 3, 1);
        }

        public override List<Skill> InitializeSkills()
        {
            return new List<Skill>
            {
                new SurvivalSkill(Characteristics.Cunning) { Rank = 1 },
            };
        }

        public override List<Talent> InitializeTalents()
        {
            return new List<Talent>
            {
                new Talent
                {
                    Description = "Zabrak add automatic advantage to all Coercion checks they make.",
                    Name = "Fearsome Countenance",
                    PageNumber = 63
                },
            };
        }
    }
}


text:
package com.inter6.mail.gui.data;

import com.google.gson.Gson;
import com.inter6.mail.gui.ConfigObserver;
import com.inter6.mail.gui.tab.TabComponentPanel;
import com.inter6.mail.model.data.EnvelopeData;
import com.inter6.mail.module.AppConfig;
import com.inter6.mail.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.swing.*;
import java.awt.*;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class EnvelopePanel extends TabComponentPanel implements ConfigObserver {
    private static final long serialVersionUID = 72285172570878291L;

    @Autowired
    private AppConfig appConfig;

    private final JTextField fromField = new JTextField(40);
    private final JTextArea toArea = new JTextArea(3, 40);

    public EnvelopePanel(String tabName) {
        super(tabName);
    }

    @PostConstruct
    private void init() {
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        JPanel fromPanel = new JPanel(new FlowLayout());
        {
            fromPanel.add(new JLabel("Mail From"));
            fromPanel.add(this.fromField);
        }
        this.add(fromPanel);
        JPanel toPanel = new JPanel(new FlowLayout());
        {
            toPanel.add(new JLabel("Rcpt To"));
            toPanel.add(toArea);
        }
        this.add(toPanel);
    }

    public EnvelopeData getEnvelopeData() {
        EnvelopeData envelopeData = new EnvelopeData();
        envelopeData.setMailFrom(this.fromField.getText());
        envelopeData.setRcptTos(StringUtil.splitToSet(this.toArea.getText(), "\n"));
        return envelopeData;
    }

    @Override
    public void loadConfig() {
        EnvelopeData envelopeData = new Gson().fromJson(this.appConfig.getString(tabName + ".envelope.data"), EnvelopeData.class);
        if (envelopeData == null) {
            return;
        }
        this.fromField.setText(envelopeData.getMailFrom());
        this.toArea.setText(StringUtils.join(envelopeData.getRcptTos(), "\n"));
    }

    @Override
    public void updateConfig() {
        this.appConfig.setProperty(tabName + ".envelope.data", new Gson().toJson(this.getEnvelopeData()));
    }
}


text:
/*----------------------------------------------------------------------------*/
/* Source File:   PARKINGLOTCELLINFOENTITYDATABUILDER.JAVA                    */
/* Description:   Test Data Builder Pattern for ParkinglotCellInfoEntity      */
/*                entity object.                                              */
/* Author:        Carlos Adolfo Ortiz Quirós (COQ)                            */
/* Date:          Oct.04/2017                                                 */
/* Last Modified: Oct.10/2017                                                 */
/* Version:       1.1                                                         */
/* Copyright (c), 2017 CSoftZ, Ceiba.                                         */
/*----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
 History
 Oct.04/2017 COQ  File created.
 -----------------------------------------------------------------------------*/

package com.csoftz.ceiba.java.learn.parking.service.test.entities.data.builder;

import com.csoftz.ceiba.java.learn.parking.service.entities.ParkinglotCellInfoEntity;

/**
 * Test Data Builder Pattern for ParkinglotCellInfoEntity entity object.
 *
 * @author Carlos Adolfo Ortiz Quirós (COQ)
 * @version 1.1, Oct.04/2017
 * @since 1.8 (JDK), Oct.10/2017
 */
public class ParkinglotCellInfoEntityDataBuilder {
	private String plate;
	private int vehicleType;

	/**
	 * Default constructor.
	 */
	public ParkinglotCellInfoEntityDataBuilder() {
		this.plate = "";
		this.vehicleType = 0;
	}

	/**
	 * Assign plate field to ParkinglotCellInfoEntity
	 *
	 * @param plate
	 *            Description of the Vehicle.
	 * @return A reference to itself.
	 */
	public ParkinglotCellInfoEntityDataBuilder withPlate(String plate) {
		this.plate = plate;
		return this;
	}

	/**
	 * Assign vehicleType field to ParkinglotCellInfoEntity
	 *
	 * @param vehicleType
	 *            Holds 1:Car, 2:Motorcycle.
	 * @return A reference to itself.
	 */
	public ParkinglotCellInfoEntityDataBuilder withVehicleType(int vehicleType) {
		this.vehicleType = vehicleType;
		return this;
	}

	/**
	 * Makes a representation of ParkinglotCellInfoEntity to test.
	 *
	 * @return ParkinglotCellInfo domain object.
	 */
	public ParkinglotCellInfoEntity build() {
		return new ParkinglotCellInfoEntity(this.plate, this.vehicleType);
	}

}


text:
//---------------------------------------------------------------------------//
//!
//! \file   MonteCarlo_WHAdjointIncoherentPhotonScatteringDistribution.hpp
//! \author Alex Robinson
//! \brief  The Waller-Hartree adjoint incoherent photon scattering dist. decl.
//!
//---------------------------------------------------------------------------//

#ifndef MONTE_CARLO_WH_INCOHERENT_ADJOINT_PHOTON_SCATTERING_DISTRIBUTION_HPP
#define MONTE_CARLO_WH_INCOHERENT_ADJOINT_PHOTON_SCATTERING_DISTRIBUTION_HPP

// Trilinos Includes
#include <Teuchos_RCP.hpp>

// FRENSIE Includes
#include "MonteCarlo_IncoherentAdjointPhotonScatteringDistribution.hpp"
#include "MonteCarlo_AdjointPhotonKinematicsHelpers.hpp"
#include "Utility_TabularOneDDistribution.hpp"

namespace MonteCarlo{

//! The Waller-Hartree incoherent adjoint photon scattering distribution class
template<typename ScatteringFunctionArgUnitConversionPolicy>
class WHIncoherentAdjointPhotonScatteringDistribution : public IncoherentAdjointPhotonScatteringDistribution
{

public:

  //! Constructor
  WHIncoherentAdjointPhotonScatteringDistribution(
    const double max_energy,
    const Teuchos::RCP<const Utility::OneDDistribution>& scattering_function );

  //! Destructor
  virtual ~WHIncoherentAdjointPhotonScatteringDistribution()
  { /* ... */ }

  //! Evaluate the distribution
  double evaluate( const double incoming_energy,
		   const double max_energy,
		   const double scattering_angle_cosine ) const;

  //! Evaluate the integrated cross section (b)
  virtual double evaluateIntegratedCrossSection(const double incoming_energy,
						const double max_energy,
						const double precision ) const;

  //! Sample an outgoing energy and direction from the distribution
  void sample( const double incoming_energy,
	       double& outgoing_energy,
	       double& scattering_angle_cosine ) const;

  //! Sample an outgoing energy and direction and record the number of trials
  void sampleAndRecordTrials( const double incoming_energy,
			      double& outgoing_energy,
			      double& scattering_angle_cosine,
			      unsigned& trials ) const;

  //! Randomly scatter the photon and return the shell that was interacted with
  void scatterAdjointPhoton( AdjointPhotonState& adjoint_photon,
			     ParticleBank& bank,
			     SubshellType& shell_of_interaction ) const;

protected:

  //! Check if an energy is above the scattering window
  bool isEnergyAboveScatteringWindow( const double energy_of_interest,
				      const double initial_energy ) const;

private:

  // Evaluate the scattering function
  double evaluateScatteringFunction(
				  const double incoming_energy,
				  const double max_energy,
				  const double scattering_angle_cosine ) const;

  // Evaluate the scattering function
  double evaluateScatteringFunction(
				  const double incoming_energy,
				  const double scattering_angle_cosine ) const;
  // The scattering function
  Teuchos::RCP<const Utility::OneDDistribution> d_scattering_function;
};

} // end MonteCarlo namespace

//---------------------------------------------------------------------------//
// Template Includes
//---------------------------------------------------------------------------//

#include "MonteCarlo_WHIncoherentAdjointPhotonScatteringDistribution_def.hpp"

//---------------------------------------------------------------------------//

#endif // end MONTE_CARLO_WH_INCOHERENT_ADJOINT_PHOTON_SCATTERING_DISTRIBUTION_HPP

//---------------------------------------------------------------------------//
// end MonteCarlo_WHAdjointIncoherentPhotonScatteringDistribution.hpp
//---------------------------------------------------------------------------//


text:
package usecase

import (
	model "github.com/thanhpk/sutu.shop/ecom/model"
)

type Registry struct {
	CustomerMgt model.ICustomerMgt
}

func (this Registry) Registry(phone string, password string) string {
	customer := &model.Customer{Phone: phone}
	customerid := this.CustomerMgt.Create(password, customer)
	return customerid;
}

func (this Registry) IsDuplicated(phone string) bool {
	c := this.CustomerMgt.MatchByPhone(phone)
	return c != nil
}


text:
<?php
// Version
define('VERSION', '3.0.2.0');

// Configuration
if (is_file('config.php')) {
	require_once('config.php');
}

// Install
if (!defined('DIR_APPLICATION')) {
	header('Location: install/index.php');
	exit;
}

// Startup
require_once(DIR_SYSTEM . 'startup.php');

start('catalog');


text:
#ifndef SVGURIReference_h
#define SVGURIReference_h

#include "core/dom/Document.h"
#include "core/svg/SVGAnimatedString.h"
#include "platform/heap/Handle.h"

namespace blink {

class Element;

class SVGURIReference : public WillBeGarbageCollectedMixin {
public:
    virtual ~SVGURIReference() { }

    bool isKnownAttribute(const QualifiedName&);
    void addSupportedAttributes(HashSet<QualifiedName>&);

    static AtomicString fragmentIdentifierFromIRIString(const String&, const TreeScope&);
    static Element* targetElementFromIRIString(const String&, const TreeScope&, AtomicString* = 0, Document* = 0);

    static inline bool isExternalURIReference(const String& uri, const Document& document)
    {
        // Fragment-only URIs are always internal
        if (uri.startsWith('#'))
            return false;

        // If the URI matches our documents URL, we're dealing with a local reference.
        KURL url = document.completeURL(uri);
        return !equalIgnoringFragmentIdentifier(url, document.url());
    }

    const String& hrefString() const { return m_href->currentValue()->value(); }

    // JS API
    SVGAnimatedString* href() const { return m_href.get(); }

    DECLARE_VIRTUAL_TRACE();

protected:
    explicit SVGURIReference(SVGElement*);

private:
    RefPtrWillBeMember<SVGAnimatedString> m_href;
};

} // namespace blink

#endif // SVGURIReference_h


text:
class SubjectSelector
  class MissingParameter < StandardError; end
  class MissingSubjectQueue < StandardError; end
  class MissingSubjectSet < StandardError; end
  class EmptyDatabaseSelect < StandardError; end

  attr_reader :user, :params, :workflow

  def initialize(user, workflow, params, scope)
    @user, @workflow, @params, @scope = user, workflow, params, scope
  end

  def queued_subjects
    raise workflow_id_error unless workflow
    raise group_id_error if needs_set_id?
    raise missing_subject_set_error if workflow.subject_sets.empty?
    unless queue = user_subject_queue
      raise MissingSubjectQueue.new("No queue defined for user. Building one now, please try again.")
    end
    subjects = selected_subjects(sms_ids_from_queue(queue))
    [ subjects, queue_context.merge(selected: true, url_format: :get) ]
  end

  def selected_subjects(sms_ids)
    @scope.eager_load(:set_member_subjects)
      .where(set_member_subjects: {id: sms_ids})
      .order("idx(array[#{sms_ids.join(',')}], set_member_subjects.id)")
  end

  private

  def sms_ids_from_queue(queue)
    set_member_subject_ids = queue.next_subjects(subjects_page_size)
    if set_member_subject_ids.blank?
      select_from_database
    else
      DequeueSubjectQueueWorker.perform_async(workflow.id, set_member_subject_ids, queue_user.try(:id), params[:subject_set_id])
      set_member_subject_ids
    end
  end

  def select_from_database
    sms_ids = PostgresqlSelection.new(workflow, user.user)
      .select(limit: 5, subject_set_id: params[:subject_set_id])
    empty_database_select_error if sms_ids.blank?
    sms_ids
  end

  def needs_set_id?
    workflow.grouped && !params.has_key?(:subject_set_id)
  end

  def workflow_id_error
    MissingParameter.new("workflow_id parameter missing")
  end

  def group_id_error
    MissingParameter.new("subject_set_id parameter missing for grouped workflow")
  end

  def missing_subject_set_error
    MissingSubjectSet.new("no subject set is associated with this workflow")
  end

  def empty_database_select_error
    message = params[:subject_set_id] ? "for subject_set_id = #{params[:subject_set_id]}" : nil
    raise EmptyDatabaseSelect.new("No data #{message} available for selection".squish)
  end

  def subjects_page_size
    page_size = params[:page_size] ? params[:page_size].to_i : 10
    params.merge!(page_size: page_size)
    page_size
  end

  def finished_workflow?
    @finished_workflow ||= workflow.finished? || user.has_finished?(workflow)
  end

  def queue_user
    @queue_user ||= finished_workflow? ? nil : user.user
  end

  def queue_context
    @queue_context ||= if finished_workflow?
      {workflow: workflow, user_seen: UserSeenSubject.where(user: user.user, workflow: workflow)}
    else
      {}
    end
  end

  def user_subject_queue
    queue = SubjectQueue.by_set(params[:subject_set_id])
      .find_by(user: queue_user, workflow: workflow)
    return queue if queue
    SubjectQueue.create_for_user(workflow, queue_user, set_id: params[:subject_set_id])
  end
end


text:
title: 'JavaScript - var, let and const - and when to use them'
date: 2016-06-19T18:50:00+02:00
author: Gjermund Bjaanes
layout: post
permalink: /javascript-var-let-and-const-and-when-to-use-them/
categories:
  - Uncategorized
tags:
  -
---
ES6 (ES2015) introduced the new keywords _let_ and _const_, to be used side by side with _var_.

In this post, we'll take a closer look at all three, how they differ, and when to use them.

<!--more-->

With ES6, you can use the _let_ and the _const_ keyword in basically the same places
as you would the _var_ keyword.

But, what are the differences?

To understand that, we first need to understand _var_ properly.

# The _var_ keyword

With _var_, the variables you create are function scoped.

That means that they are available inside the function it was created, as well as any nested functions.

To demonstrate this quickly, take a look at this code:

{% highlight javascript %}
function test() {
  var myFunctionScopedVariable = 42;

  console.log(myFunctionScopedVariable); // 42

  function nestedTest() {
    console.log(myFunctionScopedVariable); // 42
  }

  nestedTest();
}

test();
console.log(myFunctionScopedVariable); // ReferenceError: myFunctionScopedVariable is not defined
{% endhighlight %}

You can access the variable inside the function, and all nested functions, but not outside it.

As long as the variable is declared inside the function, it's available in the entire function.

Lets take a look at an example where this is slightly problematic:

{% highlight javascript %}
function test() {

  for (var i = 0; i < 3; i++) {
      var myFunctionScopedVariable = 42;
  }

  console.log(myFunctionScopedVariable); // 42
  console.log(i); // 3
}
{% endhighlight %}

Both the variable "i", and the variable "myFunctionScopedVariable" is available after the loop.

This is not so cool. It's almost never what you want. Ugh.
It just feels wrong...

But that is they way that _var_ works.

There is actually another quirk with _var_, and that is hoisting.
It's not really specific to _var_, but it's behaviour is a bit weird.

What hoisting does, is that it moves all declarations to the top of it's scope.
However, it does not move the initialization.

What that means in practice, is that this code block:

{% highlight javascript %}
console.log(typeof test); // "function"

function test() {

  for (var i = 0; i < 3; i++) {
      var myFunctionScopedVariable = 42;
  }
}
{% endhighlight %}

will be changed to something like this:

{% highlight javascript %}
function test() {
  var i;
  var myFunctionScopedVariable;

  for (i = 0; i < 3; i++) {
      myFunctionScopedVariable = 42;
  }
}

console.log(typeof test); // "function"
{% endhighlight %}

AND, to highlight the initialization part more clearly too (Thanks to Umamaheswararao Meka for pointing this out!)

{% highlight javascript %}
console.log(willBeHoisted) //undefined
var willBeHoisted;
{% endhighlight %}

This will actually be translated to:

{% highlight javascript %}
var willBeHoisted;
console.log(willBeHoisted) //undefined
{% endhighlight %}

which is why it does not behave the same way as:

{% highlight javascript %}
console.log(what) // Uncaught ReferenceError: what is not defined
{% endhighlight %}

# The _let_ keyword

Now that you mostly understand what goes on with _var_, we can start
looking at _let_, and how it actually works, compared to _var_.

The main difference between _var_ and _let_ is that _let_ is block scoped,
instead of function scoped.

This means that a lot of the crazyness we saw above, is not going to happen
with _let_. Phew!

More specifically, a variable created with the _let_ keyword is available
inside the block it was created, and any nested blocks as well.

Also, it *acts* like it is not hoisted, but I'll come back to that.

The first example still works the same way with _let_:

{% highlight javascript %}
function test() {
  let myFunctionScopedVariable = 42;

  console.log(myFunctionScopedVariable); // 42

  function nestedTest() {
    console.log(myFunctionScopedVariable); // 42
  }

  nestedTest();
}

test();
console.log(myFunctionScopedVariable); // uh, oh! Error still!
{% endhighlight %}

The second example, however, will now start throwing some errors our way:

{% highlight javascript %}
function test() {

  for (let i = 0; i < 3; i++) {
      let myFunctionScopedVariable = 42;
  }

  console.log(myFunctionScopedVariable); ReferenceError: myFunctionScopedVariable is not defined
  console.log(i); // Uncaught ReferenceError: i is not defined
}

test();
{% endhighlight %}

Sanity restored. This is most certainly what I wanted, and definitely what I meant.

And it's not only for functions and loops; this is the behaviour for all blocks.
This code explains it better:

{% highlight javascript %}
if (true) {
    let a = 1;
}

console.log(a); // ReferenceError: a is not defined

{
    let b = 2;
}

console.log(b); // ReferenceError: b is not defined;
{% endhighlight %}

But there is also another difference I briefly mentioned earlier,
and that is that _let_ "pretends" not to be hoisted.

It actually is hoisted, but if you try to use it before it's actual
declaration, an error will be thrown.

The space between the start of the block, and the declaration is called the
"Temporal Dead Zone". Don't try to use your variables in that zone.

Allow me to demonstrate:

{% highlight javascript %}
a = 1; // This works
b = 2; // Error: b is not defined

var a;
let b;
{% endhighlight %}

I personally think this is perfectly reasonable. But you have to keep
it in mind, especially if you are refactoring code.

There is one more example I would like to point out, and that is a special case
with _let_, that you might want to know about.

{% highlight javascript %}
for (var i = 0; i < 3; i++) {
    console.log("Inside the loop: " + i);
    setTimeout(function () {
        console.log("Inside the timeout: " + i)
    });
}
{% endhighlight %}

This will result in the following output:

{% highlight bash %}
Inside the loop: 0
Inside the loop: 1
Inside the loop: 2
Inside the timeout: 3
Inside the timeout: 3
Inside the timeout: 3
{% endhighlight %}

Well... That is unfortunate. It kind of makes sense, but given the powerful
closure patterns used in JavaScript, this kind of breaks the expectations, in my opinion.

You wouldn't really think that _let_ would fix this, but it turns out that it does!

The ES6 spec says that _let_ in a for loop is scoped not only to the loop, but to each iteration.

Which means that this code:
{% highlight javascript %}
for (let i = 0; i < 3; i++) {
    console.log("Inside the loop: " + i);
    setTimeout(function () {
        console.log("Inside the timeout: " + i)
    });
}
{% endhighlight %}

will result in the following output:

{% highlight bash %}
Inside the loop: 0
Inside the loop: 1
Inside the loop: 2
Inside the timeout: 0
Inside the timeout: 1
Inside the timeout: 2
{% endhighlight %}

Again, sanity resorted.

# The _const_ keyword

Now that we know a lot about _var_ and _let_, let's take a look at the _const_ keyword.

The difference between _let_ and _const_ is not too big.

In fact, all the differences between _var_ and _let_ are also true for _var_ and **_const_**.

In other words, _let_ and _const_ is almost the same.
They are both block scoped and work the same way.

The only thing that makes _const_ different is that is a constant:

**A variable created with _const_ cannot be changed after it is initialized.**

And just like constants in most languages (as far as I know...), you have to initialize it when you declare it.

{% highlight javascript %}
const a; // SyntaxError: Missing initializer in const declaration
const b = 42;
b = 43; // TypeError: Assignment to constant variable.
{% endhighlight %}

This is good, but you have to keep one thing in mind:

Objects in a _const_ variable are *not* immutable.

That means that you can still do this:
{% highlight javascript %}
const obj = {
    ultimateQuestionOf: "Life, the Universe, and Everything",
    answer: 42
};

obj.answer = 43; // This is OK, obj is not immutable
console.log(obj.answer); // 43
{% endhighlight %}

Which is fine, and also makes the const something that can be used in almost all cases.

We now know how _var_, _let_ and _const_ work. We also know how they differ from each other.

It's time to figure out when exactly we should use the different ones.

# When to use _var_

I would say: **almost never**.

And I really mean that. I see very few good reasons why you might want to use _var_.

It would have to be because you really want function scoped variables. For the most part,
that's absolutely not necessary, and is only confusing.

_let_ and _const_ gives you all the functionality you actually need from _var_, but with none of the
weird edge cases you really wouldn't expect (unless you are already a complete JavaScript expert).

# When to use _let_ and _const_

I grouped these two together, because their usage is dependent on when you wouldn't use the other.

Any variable that you *need* to redefine later should use _let_, and any other variable should for the
most part be _const_. If you make a mistake, most modern tools will give you a heads up anyways.

[![IntelliJ giving a heads up]({{ site.baseurl}}/img/posts/const-tool-help.png)]({{ site.baseurl }}/img/posts/const-tool-help.png)

# Summary

You should stop using _var_ as soon as you can.

There are few good reasons to ever use it, if you have access to _let_ and _const_.

I also think you should use _const_ whenever you can (whenever you don't need to reassign a variable).

_const_ should be your default choice, only using _let_ when you really have to.

It makes your code clearer and more explicit about it's variables.

If you have any questions, comments or constructive criticism (I'd love to get my views
challenged with a good discussion), reach out to me on twitter or in the comments.

You can find me on twitter here: [gjermundbjaanes](https://twitter.com/gjermundbjaanes/){:target="_blank"}


text:
class Deconvolve : public Operation {
public:
    void help();
    bool test();
    void parse(vector<string> args);
    static Image applyCho2009(Image im, Image kernel);
    static Image applyShan2008(Image im, Image kernel);
    static Image applyLevin2007(Image im, Image kernel, float weight);
private:
    static Image applyPadding(Image im);
};

#include "footer.h"
#endif
#endif


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Interactivity;
using Avalonia.Platform;
using Avalonia.Threading;

namespace Avalonia.Controls.ApplicationLifetimes
{
    public class ClassicDesktopStyleApplicationLifetime : IClassicDesktopStyleApplicationLifetime, IDisposable
    {
        private int _exitCode;
        private CancellationTokenSource _cts;
        private bool _isShuttingDown;
        private HashSet<Window> _windows = new HashSet<Window>();

        private static ClassicDesktopStyleApplicationLifetime _activeLifetime;
        static ClassicDesktopStyleApplicationLifetime()
        {
            Window.WindowOpenedEvent.AddClassHandler(typeof(Window), OnWindowOpened);
            Window.WindowClosedEvent.AddClassHandler(typeof(Window), WindowClosedEvent);
        }

        private static void WindowClosedEvent(object sender, RoutedEventArgs e)
        {
            _activeLifetime?._windows.Remove((Window)sender);
            _activeLifetime?.HandleWindowClosed((Window)sender);
        }

        private static void OnWindowOpened(object sender, RoutedEventArgs e)
        {
            _activeLifetime?._windows.Add((Window)sender);
        }

        public ClassicDesktopStyleApplicationLifetime()
        {
            if (_activeLifetime != null)
                throw new InvalidOperationException(
                    "Can not have multiple active ClassicDesktopStyleApplicationLifetime instances and the previously created one was not disposed");
            _activeLifetime = this;
        }

        /// <inheritdoc/>
        public event EventHandler<ControlledApplicationLifetimeStartupEventArgs> Startup;

        /// <inheritdoc/>
        public event EventHandler<ShutdownRequestedEventArgs> ShutdownRequested;

        /// <inheritdoc/>
        public event EventHandler<ControlledApplicationLifetimeExitEventArgs> Exit;

        /// <summary>
        /// Gets the arguments passed to the AppBuilder Start method.
        /// </summary>
        public string[] Args { get; set; }

        /// <inheritdoc/>
        public ShutdownMode ShutdownMode { get; set; }

        /// <inheritdoc/>
        public Window MainWindow { get; set; }

        public IReadOnlyList<Window> Windows => _windows.ToList();

        private void HandleWindowClosed(Window window)
        {
            if (window == null)
                return;

            if (_isShuttingDown)
                return;

            if (ShutdownMode == ShutdownMode.OnLastWindowClose && _windows.Count == 0)
                Shutdown();
            else if (ShutdownMode == ShutdownMode.OnMainWindowClose && window == MainWindow)
                Shutdown();
        }

        public void Shutdown(int exitCode = 0)
        {
            if (_isShuttingDown)
                throw new InvalidOperationException("Application is already shutting down.");

            _exitCode = exitCode;
            _isShuttingDown = true;

            try
            {
                foreach (var w in Windows)
                    w.Close();
                var e = new ControlledApplicationLifetimeExitEventArgs(exitCode);
                Exit?.Invoke(this, e);
                _exitCode = e.ApplicationExitCode;
            }
            finally
            {
                _cts?.Cancel();
                _cts = null;
                _isShuttingDown = false;
            }
        }

        public int Start(string[] args)
        {
            Startup?.Invoke(this, new ControlledApplicationLifetimeStartupEventArgs(args));

            var options = AvaloniaLocator.Current.GetService<ClassicDesktopStyleApplicationLifetimeOptions>();

            if(options != null && options.ProcessUrlActivationCommandLine && args.Length > 0)
            {
                ((IApplicationPlatformEvents)Application.Current).RaiseUrlsOpened(args);
            }

            var lifetimeEvents = AvaloniaLocator.Current.GetService<IPlatformLifetimeEventsImpl>();

            if (lifetimeEvents != null)
                lifetimeEvents.ShutdownRequested += OnShutdownRequested;

            _cts = new CancellationTokenSource();
            MainWindow?.Show();
            Dispatcher.UIThread.MainLoop(_cts.Token);
            Environment.ExitCode = _exitCode;
            return _exitCode;
        }

        public void Dispose()
        {
            if (_activeLifetime == this)
                _activeLifetime = null;
        }

        private void OnShutdownRequested(object sender, ShutdownRequestedEventArgs e)
        {
            ShutdownRequested?.Invoke(this, e);

            if (e.Cancel)
                return;

            // When an OS shutdown request is received, try to close all non-owned windows. Windows can cancel
            // shutdown by setting e.Cancel = true in the Closing event. Owned windows will be shutdown by their
            // owners.
            foreach (var w in Windows)
                if (w.Owner is null)
                    w.Close();
            if (Windows.Count > 0)
                e.Cancel = true;
        }
    }

    public class ClassicDesktopStyleApplicationLifetimeOptions
    {
        public bool ProcessUrlActivationCommandLine { get; set; }
    }
}

namespace Avalonia
{
    public static class ClassicDesktopStyleApplicationLifetimeExtensions
    {
        public static int StartWithClassicDesktopLifetime<T>(
            this T builder, string[] args, ShutdownMode shutdownMode = ShutdownMode.OnLastWindowClose)
            where T : AppBuilderBase<T>, new()
        {
            var lifetime = new ClassicDesktopStyleApplicationLifetime()
            {
                Args = args,
                ShutdownMode = shutdownMode
            };
            builder.SetupWithLifetime(lifetime);
            return lifetime.Start(args);
        }
    }
}


text:
            Menu
            Log out

Car Share

        Drivers Offers

        Passengers Offers


text:
"""elysia URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

from elysia import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.index, name="index"),
    url(r'^fplassist/', include('fplassist.urls')),
    url(r'^pathfinder/', include('pathfinder.urls')),
    url(r'^moviecritic/', include('moviecritic.urls')),
]


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/toolkit/components/commandlines/nsICommandLineRunner.idl
 */

#ifndef __gen_nsICommandLineRunner_h__
#define __gen_nsICommandLineRunner_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

#ifndef __gen_nsICommandLine_h__
#include "nsICommandLine.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif

/* starting interface:    nsICommandLineRunner */
#define NS_ICOMMANDLINERUNNER_IID_STR "c1f4cfbf-a41f-4628-aa6c-9fb914478af8"

#define NS_ICOMMANDLINERUNNER_IID \
  {0xc1f4cfbf, 0xa41f, 0x4628, \
    { 0xaa, 0x6c, 0x9f, 0xb9, 0x14, 0x47, 0x8a, 0xf8 }}

class NS_NO_VTABLE nsICommandLineRunner : public nsICommandLine {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICOMMANDLINERUNNER_IID)

  /* void init (in long argc, in nsCharPtrArray argv, in nsIFile workingDir, in unsigned long state); */
  NS_IMETHOD Init(PRInt32 argc, char* *argv, nsIFile *workingDir, PRUint32 state) = 0;

  /* void setWindowContext (in nsIDOMWindow aWindow); */
  NS_IMETHOD SetWindowContext(nsIDOMWindow *aWindow) = 0;

  /* void run (); */
  NS_IMETHOD Run(void) = 0;

  /* readonly attribute AUTF8String helpText; */
  NS_IMETHOD GetHelpText(nsACString & aHelpText) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsICommandLineRunner, NS_ICOMMANDLINERUNNER_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSICOMMANDLINERUNNER \
  NS_IMETHOD Init(PRInt32 argc, char* *argv, nsIFile *workingDir, PRUint32 state); \
  NS_IMETHOD SetWindowContext(nsIDOMWindow *aWindow); \
  NS_IMETHOD Run(void); \
  NS_IMETHOD GetHelpText(nsACString & aHelpText);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSICOMMANDLINERUNNER(_to) \
  NS_IMETHOD Init(PRInt32 argc, char* *argv, nsIFile *workingDir, PRUint32 state) { return _to Init(argc, argv, workingDir, state); } \
  NS_IMETHOD SetWindowContext(nsIDOMWindow *aWindow) { return _to SetWindowContext(aWindow); } \
  NS_IMETHOD Run(void) { return _to Run(); } \
  NS_IMETHOD GetHelpText(nsACString & aHelpText) { return _to GetHelpText(aHelpText); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSICOMMANDLINERUNNER(_to) \
  NS_IMETHOD Init(PRInt32 argc, char* *argv, nsIFile *workingDir, PRUint32 state) { return !_to ? NS_ERROR_NULL_POINTER : _to->Init(argc, argv, workingDir, state); } \
  NS_IMETHOD SetWindowContext(nsIDOMWindow *aWindow) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetWindowContext(aWindow); } \
  NS_IMETHOD Run(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Run(); } \
  NS_IMETHOD GetHelpText(nsACString & aHelpText) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetHelpText(aHelpText); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsCommandLineRunner : public nsICommandLineRunner
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSICOMMANDLINERUNNER

  nsCommandLineRunner();

private:
  ~nsCommandLineRunner();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsCommandLineRunner, nsICommandLineRunner)

nsCommandLineRunner::nsCommandLineRunner()
{
  /* member initializers and constructor code */
}

nsCommandLineRunner::~nsCommandLineRunner()
{
  /* destructor code */
}

/* void init (in long argc, in nsCharPtrArray argv, in nsIFile workingDir, in unsigned long state); */
NS_IMETHODIMP nsCommandLineRunner::Init(PRInt32 argc, char* *argv, nsIFile *workingDir, PRUint32 state)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void setWindowContext (in nsIDOMWindow aWindow); */
NS_IMETHODIMP nsCommandLineRunner::SetWindowContext(nsIDOMWindow *aWindow)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void run (); */
NS_IMETHODIMP nsCommandLineRunner::Run()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* readonly attribute AUTF8String helpText; */
NS_IMETHODIMP nsCommandLineRunner::GetHelpText(nsACString & aHelpText)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsICommandLineRunner_h__ */


text:
import { module, test } from "qunit";
import {
	getApplication,
	setupContext,
	teardownContext,
	setupApplicationContext,
	teardownApplicationContext
} from "@ember/test-helpers";
import { buildFakeApplication } from "test-utils";
import sinon from "sinon";

import KeyboardLayoutMapInitializer from "init/initializers/keyboard-layout-map";

module( "init/initializers/keyboard-layout-map", function( hooks ) {
	buildFakeApplication( hooks, { each: true }, {} );

	hooks.before(function() {
		this.getLayoutMapStub = sinon.stub( navigator.keyboard, "getLayoutMap" );
	});

	hooks.after(function() {
		this.getLayoutMapStub.restore();
	});

	hooks.beforeEach(function() {
		const application = getApplication();
		application.initializer( KeyboardLayoutMapInitializer );
	});

	hooks.afterEach(async function() {
		await teardownApplicationContext( this );
		await teardownContext( this );
	});

	test( "Initializer - success", async function( assert ) {
		class Subject extends Map {}
		this.getLayoutMapStub.callsFake( async () => new Subject() );

		await setupContext( this );
		await setupApplicationContext( this );

		const keyboardLayoutMap = this.owner.lookup( "keyboardlayoutmap:main" );
		assert.ok( keyboardLayoutMap instanceof Subject, "Registers the keyboard layout map" );
	});

	test( "Initializer - failure", async function( assert ) {
		this.getLayoutMapStub.rejects();

		await setupContext( this );
		await setupApplicationContext( this );

		const keyboardLayoutMap = this.owner.lookup( "keyboardlayoutmap:main" );
		assert.ok( keyboardLayoutMap instanceof Map, "Registers the empty fallback map" );
	});
});


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

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.prestosql.Session;
import io.prestosql.metadata.Metadata;
import io.prestosql.spi.expression.ConnectorExpression;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.parser.SqlParser;
import io.prestosql.sql.tree.ArithmeticBinaryExpression;
import io.prestosql.sql.tree.DereferenceExpression;
import io.prestosql.sql.tree.Expression;
import io.prestosql.sql.tree.FunctionCall;
import io.prestosql.sql.tree.Identifier;
import io.prestosql.sql.tree.NodeRef;
import io.prestosql.sql.tree.QualifiedName;
import io.prestosql.sql.tree.StringLiteral;
import io.prestosql.sql.tree.SymbolReference;
import io.prestosql.transaction.TransactionId;
import org.testng.annotations.Test;

import java.util.List;
import java.util.Map;

import static com.google.common.collect.Iterables.getOnlyElement;
import static io.prestosql.metadata.MetadataManager.createTestMetadataManager;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.DoubleType.DOUBLE;
import static io.prestosql.spi.type.IntegerType.INTEGER;
import static io.prestosql.spi.type.RowType.field;
import static io.prestosql.spi.type.RowType.rowType;
import static io.prestosql.spi.type.VarcharType.createVarcharType;
import static io.prestosql.sql.planner.ConnectorExpressionTranslator.translate;
import static io.prestosql.sql.planner.PartialTranslator.extractPartialTranslations;
import static io.prestosql.sql.tree.ArithmeticBinaryExpression.Operator.ADD;
import static io.prestosql.testing.TestingSession.testSessionBuilder;
import static org.testng.Assert.assertEquals;

public class TestPartialTranslator
{
    private static final Session TEST_SESSION = testSessionBuilder()
            .setTransactionId(TransactionId.create())
            .build();
    private static final Metadata METADATA = createTestMetadataManager();
    private static final TypeAnalyzer TYPE_ANALYZER = new TypeAnalyzer(new SqlParser(), METADATA);
    private static final TypeProvider TYPE_PROVIDER = TypeProvider.copyOf(ImmutableMap.<Symbol, Type>builder()
            .put(new Symbol("double_symbol_1"), DOUBLE)
            .put(new Symbol("double_symbol_2"), DOUBLE)
            .put(new Symbol("bigint_symbol_1"), BIGINT)
            .put(new Symbol("row_symbol_1"), rowType(field("int_symbol_1", INTEGER), field("varchar_symbol_1", createVarcharType(5))))
            .build());

    @Test
    public void testPartialTranslator()
    {
        Expression rowSymbolReference = new SymbolReference("row_symbol_1");
        Expression dereferenceExpression1 = new DereferenceExpression(rowSymbolReference, new Identifier("int_symbol_1"));
        Expression dereferenceExpression2 = new DereferenceExpression(rowSymbolReference, new Identifier("varchar_symbol_1"));
        Expression stringLiteral = new StringLiteral("abcd");
        Expression symbolReference1 = new SymbolReference("double_symbol_1");

        assertFullTranslation(symbolReference1);
        assertFullTranslation(dereferenceExpression1);
        assertFullTranslation(stringLiteral);

        Expression binaryExpression = new ArithmeticBinaryExpression(ADD, symbolReference1, dereferenceExpression1);
        assertPartialTranslation(binaryExpression, ImmutableList.of(symbolReference1, dereferenceExpression1));

        List<Expression> functionArguments = ImmutableList.of(stringLiteral, dereferenceExpression2);
        Expression functionCallExpression = new FunctionCall(QualifiedName.of("concat"), functionArguments);
        assertPartialTranslation(functionCallExpression, functionArguments);
    }

    private void assertPartialTranslation(Expression expression, List<Expression> subexpressions)
    {
        Map<NodeRef<Expression>, ConnectorExpression> translation = extractPartialTranslations(expression, TEST_SESSION, TYPE_ANALYZER, TYPE_PROVIDER);
        assertEquals(subexpressions.size(), translation.size());
        for (Expression subexpression : subexpressions) {
            assertEquals(translation.get(NodeRef.of(subexpression)), translate(TEST_SESSION, subexpression, TYPE_ANALYZER, TYPE_PROVIDER).get());
        }
    }

    private void assertFullTranslation(Expression expression)
    {
        Map<NodeRef<Expression>, ConnectorExpression> translation = extractPartialTranslations(expression, TEST_SESSION, TYPE_ANALYZER, TYPE_PROVIDER);
        assertEquals(getOnlyElement(translation.keySet()), NodeRef.of(expression));
        assertEquals(getOnlyElement(translation.values()), translate(TEST_SESSION, expression, TYPE_ANALYZER, TYPE_PROVIDER).get());
    }
}


text:
  <title>Awesome Meteor Chat!</title>

  {{> clearMessages}}
  {{> chatMessages}}
  {{> messageBox}}

<template name='clearMessages'>

    <button id='clearAllMessages'>Clear</button>

</template>

<template name='chatMessages'>

    {{#each allMessages}}

      {{message}} (x)

    {{/each}}

</template>

<template name='messageBox'>

    <textarea style="width:100%;height:100%" id='myMessage'></textarea>
    <button id='sendMessage'>Send</button>

</template>


text:
ACCEPTED

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

#### Published in
Trans. Br. mycol. Soc. 72: 420 (1979)

#### Original name
Hypochnus fuciformis McAlpine, 1907

### Remarks
null


text:
using CoreCmd.Attributes;
using CoreCmd.CommandExecution;
using CoreCmd.CommandLoading;
using CoreCmd.Help;
using System;
using System.Collections.Generic;
using System.Text;

namespace CoreCmd.BuiltinCommands
{
    [Help("Print the help information")]
    class HelpCommand
    {
        IHelpInfoService _helpSvc = new HelpInfoService();

        public void Default(string command)
        {
            CommandExecutorCreator _exeCreator = new CommandExecutorCreator();
            ICommandClassLoader _loader = new CommandClassLoader();

            var allClassTypes = _loader.LoadAllCommandClasses(null);
            var singleCommandExecutor = _exeCreator.GetSingleCommandExecutor(allClassTypes, new string[]{ command });

            if(singleCommandExecutor != null)
            {
                _helpSvc.PrintClassHelp(singleCommandExecutor.CommandClassType);
            }
        }
    }
}


text:
The :mod:`nova..tests.real_flags` Module
==============================================================================
.. automodule:: nova..tests.real_flags
  :members:
  :undoc-members:
  :show-inheritance:


text:
from django.db import models

# Create your models here.
from django.conf import settings

class Auditable(models.Model):
    create_timestamp = models.DateTimeField(auto_now_add = True, blank=True, null=True)
    create_user = models.ForeignKey('User', related_name='%(app_label)s_%(class)s_CREATE_USER', blank=True, null=True)

    update_timestamp = models.DateTimeField(auto_now = True, blank=True, null=True)
    update_user = models.ForeignKey('User', related_name='%(app_label)s_%(class)s_UPDATE_USER', blank=True, null=True)

    class Meta:
        abstract = True


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
  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.
-->
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

  <display-name>WebRTC</display-name>
  <description>
     WebRTC
  </description>
  <servlet>
      <servlet-name>ConferenceCreateServlet</servlet-name>
      <servlet-class>
          com.openvcx.webcall.ConferenceCreateServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
  </servlet>
      <servlet-mapping>
          <servlet-name>ConferenceCreateServlet</servlet-name>
          <url-pattern>/x/*</url-pattern>
      </servlet-mapping>
    <context-param>
      <param-name>config</param-name>
      <param-value>conf/sip-conference.conf</param-value>
    </context-param>
</web-app>


text:
using content::UserMetricsAction;

namespace {

// Layout constants.
const int kInset = 2;
const int kImageHeadlinePadding = 4;
const int kHeadlineMessagePadding = 4;
const int kMessageBubblePadding = 11;

// How long to give the user until auto-restart if no action is taken. The code
// assumes this to be less than a minute.
const int kCountdownDuration = 30;  // Seconds.

// How often to refresh the bubble UI to update the counter. As long as the
// countdown is in seconds, this should be 1000 or lower.
const int kRefreshBubbleEvery = 1000;  // Millisecond.

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// CriticalNotificationBubbleView

CriticalNotificationBubbleView::CriticalNotificationBubbleView(
    views::View* anchor_view)
    : BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_RIGHT),
      headline_(NULL),
      restart_button_(NULL),
      dismiss_button_(NULL) {
  set_close_on_deactivate(false);
  set_move_with_anchor(true);
}

CriticalNotificationBubbleView::~CriticalNotificationBubbleView() {
}

int CriticalNotificationBubbleView::GetRemainingTime() {
  base::TimeDelta time_lapsed = base::Time::Now() - bubble_created_;
  return kCountdownDuration - time_lapsed.InSeconds();
}

void CriticalNotificationBubbleView::UpdateBubbleHeadline(int seconds) {
  if (seconds > 0) {
    headline_->SetText(
        l10n_util::GetStringFUTF16(IDS_CRITICAL_NOTIFICATION_HEADLINE,
            l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
            base::IntToString16(seconds)));
  } else {
    headline_->SetText(
        l10n_util::GetStringFUTF16(IDS_CRITICAL_NOTIFICATION_HEADLINE_ALTERNATE,
            l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
  }
}

void CriticalNotificationBubbleView::OnCountdown() {
  UpgradeDetector* upgrade_detector = UpgradeDetector::GetInstance();
  if (upgrade_detector->critical_update_acknowledged()) {
    // The user has already interacted with the bubble and chosen a path.
    GetWidget()->Close();
    return;
  }

  int seconds = GetRemainingTime();
  if (seconds <= 0) {
    // Time's up!
    upgrade_detector->acknowledge_critical_update();

    content::RecordAction(
        UserMetricsAction("CriticalNotification_AutoRestart"));
    refresh_timer_.Stop();
    chrome::AttemptRestart();
  }

  // Update the counter. It may seem counter-intuitive to update the message
  // after we attempt restart, but remember that shutdown may be aborted by
  // an onbeforeunload handler, leaving the bubble up when the browser should
  // have restarted (giving the user another chance).
  UpdateBubbleHeadline(seconds);
  SchedulePaint();
}

void CriticalNotificationBubbleView::ButtonPressed(
    views::Button* sender, const ui::Event& event) {
  // Let other bubbles know we have an answer from the user.
  UpgradeDetector::GetInstance()->acknowledge_critical_update();

  if (sender == restart_button_) {
    content::RecordAction(UserMetricsAction("CriticalNotification_Restart"));
    chrome::AttemptRestart();
  } else if (sender == dismiss_button_) {
    content::RecordAction(UserMetricsAction("CriticalNotification_Ignore"));
    // If the counter reaches 0, we set a restart flag that must be cleared if
    // the user selects, for example, "Stay on this page" during an
    // onbeforeunload handler.
    PrefService* prefs = g_browser_process->local_state();
    if (prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown))
      prefs->ClearPref(prefs::kRestartLastSessionOnShutdown);
  } else {
    NOTREACHED();
  }

  GetWidget()->Close();
}

void CriticalNotificationBubbleView::WindowClosing() {
  refresh_timer_.Stop();
}

void CriticalNotificationBubbleView::GetAccessibleState(
    ui::AccessibleViewState* state) {
  state->role = ui::AccessibilityTypes::ROLE_ALERT;
}

void CriticalNotificationBubbleView::ViewHierarchyChanged(
    bool is_add, View* parent, View* child) {
  if (is_add && child == this) {
    GetWidget()->NotifyAccessibilityEvent(
        this, ui::AccessibilityTypes::EVENT_ALERT, true);
  }
}

bool CriticalNotificationBubbleView::AcceleratorPressed(
    const ui::Accelerator& accelerator) {
  if (accelerator.key_code() == ui::VKEY_ESCAPE)
    UpgradeDetector::GetInstance()->acknowledge_critical_update();
  return BubbleDelegateView::AcceleratorPressed(accelerator);
}

void CriticalNotificationBubbleView::Init() {
  bubble_created_ = base::Time::Now();

  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();

  views::GridLayout* layout = views::GridLayout::CreatePanel(this);
  layout->SetInsets(0, kInset, kInset, kInset);
  SetLayoutManager(layout);

  const int top_column_set_id = 0;
  views::ColumnSet* top_columns = layout->AddColumnSet(top_column_set_id);
  top_columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
                         0, views::GridLayout::USE_PREF, 0, 0);
  top_columns->AddPaddingColumn(0, kImageHeadlinePadding);
  top_columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
                         0, views::GridLayout::USE_PREF, 0, 0);
  top_columns->AddPaddingColumn(1, 0);
  layout->StartRow(0, top_column_set_id);

  views::ImageView* image = new views::ImageView();
  image->SetImage(rb.GetImageSkiaNamed(IDR_UPDATE_MENU3));
  layout->AddView(image);

  headline_ = new views::Label();
  headline_->SetFont(rb.GetFont(ui::ResourceBundle::MediumFont));
  UpdateBubbleHeadline(GetRemainingTime());
  layout->AddView(headline_);

  const int middle_column_set_id = 1;
  views::ColumnSet* middle_column = layout->AddColumnSet(middle_column_set_id);
  middle_column->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,
                           0, views::GridLayout::USE_PREF, 0, 0);
  layout->StartRowWithPadding(0, middle_column_set_id,
                              0, kHeadlineMessagePadding);

  views::Label* message = new views::Label();
  message->SetMultiLine(true);
  message->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  message->SetText(l10n_util::GetStringFUTF16(IDS_CRITICAL_NOTIFICATION_TEXT,
      l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
  message->SizeToFit(views::Widget::GetLocalizedContentsWidth(
      IDS_CRUCIAL_NOTIFICATION_BUBBLE_WIDTH_CHARS));
  layout->AddView(message);

  const int bottom_column_set_id = 2;
  views::ColumnSet* bottom_columns = layout->AddColumnSet(bottom_column_set_id);
  bottom_columns->AddPaddingColumn(1, 0);
  bottom_columns->AddColumn(views::GridLayout::CENTER,
      views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0);
  bottom_columns->AddPaddingColumn(0, views::kRelatedButtonHSpacing);
  bottom_columns->AddColumn(views::GridLayout::CENTER,
      views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0);
  layout->StartRowWithPadding(0, bottom_column_set_id,
                              0, kMessageBubblePadding);

  restart_button_ = new views::NativeTextButton(this,
      l10n_util::GetStringUTF16(IDS_CRITICAL_NOTIFICATION_RESTART));
  restart_button_->SetIsDefault(true);
  layout->AddView(restart_button_);
  dismiss_button_ = new views::NativeTextButton(this,
      l10n_util::GetStringUTF16(IDS_CRITICAL_NOTIFICATION_DISMISS));
  layout->AddView(dismiss_button_);

  refresh_timer_.Start(FROM_HERE,
      base::TimeDelta::FromMilliseconds(kRefreshBubbleEvery),
      this, &CriticalNotificationBubbleView::OnCountdown);

  content::RecordAction(UserMetricsAction("CriticalNotificationShown"));
}


text:
using UnityEngine;
using System;

public class FSliceSprite : FSprite
{
	private float _insetTop;
	private float _insetRight;
	private float _insetBottom;
	private float _insetLeft;

	private float _width;
	private float _height;

	private int _sliceCount;

	private Vector2[] _uvVertices;

	public FSliceSprite (string elementName, float width, float height, float insetTop, float insetRight, float insetBottom, float insetLeft) : this(Futile.atlasManager.GetElementWithName(elementName), width, height, insetTop, insetRight, insetBottom, insetLeft)
	{
	}

	public FSliceSprite (FAtlasElement element, float width, float height, float insetTop, float insetRight, float insetBottom, float insetLeft) : base()
	{
		_width = width;
		_height = height;

		_insetTop = insetTop;
		_insetRight = insetRight;
		_insetBottom = insetBottom;
		_insetLeft = insetLeft;

		Init(FFacetType.Quad, element,0); //this will call HandleElementChanged(), which will call SetupSlices();

		_isAlphaDirty = true;

		UpdateLocalVertices();
	}

	override public void HandleElementChanged()
	{
		SetupSlices();
	}

	public void SetupSlices ()
	{
		_insetTop = Math.Max (0,_insetTop);
		_insetRight = Math.Max(0,_insetRight);
		_insetBottom = Math.Max (0,_insetBottom);
		_insetLeft = Math.Max(0,_insetLeft);

		_sliceCount = 1;

		if(_insetTop > 0) _sliceCount++;
		if(_insetRight > 0) _sliceCount++;
		if(_insetLeft > 0) _sliceCount++;
		if(_insetBottom > 0) _sliceCount++;

		if(_insetTop > 0 && _insetRight > 0) _sliceCount++;
		if(_insetTop > 0 && _insetLeft > 0) _sliceCount++;
		if(_insetBottom > 0 && _insetRight > 0) _sliceCount++;
		if(_insetBottom > 0 && _insetLeft > 0) _sliceCount++;

		_numberOfFacetsNeeded = _sliceCount;

		_localVertices = new Vector2[_sliceCount*4];
		_uvVertices = new Vector2[_sliceCount*4];

		_areLocalVerticesDirty = true;

		if(_numberOfFacetsNeeded != _sliceCount)
		{
			_numberOfFacetsNeeded = _sliceCount;
			if(_isOnStage) _stage.HandleFacetsChanged();
		}

		UpdateLocalVertices();
	}

	override public void UpdateLocalVertices()
	{
		_areLocalVerticesDirty = false;

		Rect uvRect = element.uvRect;

		float itop = Math.Max(0,Math.Min(_insetTop, _element.sourceSize.y-_insetBottom));
		float iright = Math.Max(0,Math.Min(_insetRight, _element.sourceSize.x-_insetLeft));
		float ibottom = Math.Max(0,Math.Min(_insetBottom, _element.sourceSize.y-_insetTop));
		float ileft = Math.Max(0,Math.Min(_insetLeft, _element.sourceSize.x-_insetRight));

		float uvtop = uvRect.height*(itop/_element.sourceSize.y);
		float uvleft = uvRect.width*(ileft/_element.sourceSize.x);
		float uvbottom = uvRect.height*(ibottom/_element.sourceSize.y);
		float uvright = uvRect.width*(iright/_element.sourceSize.x);

		_textureRect.x = -_anchorX*_width;
		_textureRect.y = -_anchorY*_height;
		_textureRect.width = _width;
		_textureRect.height = _height;

		_localRect = _textureRect;

		float localXMin = _localRect.xMin;
		float localXMax = _localRect.xMax;
		float localYMin = _localRect.yMin;
		float localYMax = _localRect.yMax;

		float uvXMin = uvRect.xMin;
		float uvXMax = uvRect.xMax;
		float uvYMin = uvRect.yMin;
		float uvYMax = uvRect.yMax;

		int sliceVertIndex = 0;

		for(int s = 0; s<9; s++)
		{
			if(s == 0) //center slice
			{
				_localVertices[sliceVertIndex].Set   (localXMin + ileft,localYMax - itop);
				_localVertices[sliceVertIndex+1].Set (localXMax - iright,localYMax - itop);
				_localVertices[sliceVertIndex+2].Set (localXMax - iright,localYMin + ibottom);
				_localVertices[sliceVertIndex+3].Set (localXMin + ileft,localYMin + ibottom);

				_uvVertices[sliceVertIndex].Set   (uvXMin + uvleft,uvYMax - uvtop);
				_uvVertices[sliceVertIndex+1].Set (uvXMax - uvright,uvYMax - uvtop);
				_uvVertices[sliceVertIndex+2].Set (uvXMax - uvright,uvYMin + uvbottom);
				_uvVertices[sliceVertIndex+3].Set (uvXMin + uvleft,uvYMin + uvbottom);

				sliceVertIndex += 4;
			}
			else if (s == 1 && _insetTop > 0) //top center slice
			{
				_localVertices[sliceVertIndex].Set   (localXMin + ileft,localYMax);
				_localVertices[sliceVertIndex+1].Set (localXMax - iright,localYMax);
				_localVertices[sliceVertIndex+2].Set (localXMax - iright,localYMax - itop);
				_localVertices[sliceVertIndex+3].Set (localXMin + ileft,localYMax - itop);

				_uvVertices[sliceVertIndex].Set   (uvXMin + uvleft,uvYMax);
				_uvVertices[sliceVertIndex+1].Set (uvXMax - uvright,uvYMax);
				_uvVertices[sliceVertIndex+2].Set (uvXMax - uvright,uvYMax - uvtop);
				_uvVertices[sliceVertIndex+3].Set (uvXMin + uvleft,uvYMax - uvtop);

				sliceVertIndex += 4;
			}
			else if (s == 2 && _insetRight > 0) //right center slice
			{
				_localVertices[sliceVertIndex].Set   (localXMax - iright,localYMax - itop);
				_localVertices[sliceVertIndex+1].Set (localXMax,localYMax - itop);
				_localVertices[sliceVertIndex+2].Set (localXMax,localYMin + ibottom);
				_localVertices[sliceVertIndex+3].Set (localXMax - iright,localYMin + ibottom);

				_uvVertices[sliceVertIndex].Set   (uvXMax - uvright,uvYMax - uvtop);
				_uvVertices[sliceVertIndex+1].Set (uvXMax,uvYMax - uvtop);
				_uvVertices[sliceVertIndex+2].Set (uvXMax,uvYMin + uvbottom);
				_uvVertices[sliceVertIndex+3].Set (uvXMax - uvright,uvYMin + uvbottom);

				sliceVertIndex += 4;
			}
			else if (s == 3 && _insetBottom > 0) //bottom center slice
			{
				_localVertices[sliceVertIndex].Set   (localXMin + ileft,localYMin + ibottom);
				_localVertices[sliceVertIndex+1].Set (localXMax - iright,localYMin + ibottom);
				_localVertices[sliceVertIndex+2].Set (localXMax - iright,localYMin);
				_localVertices[sliceVertIndex+3].Set (localXMin + ileft,localYMin);

				_uvVertices[sliceVertIndex].Set   (uvXMin + uvleft,uvYMin + uvbottom);
				_uvVertices[sliceVertIndex+1].Set (uvXMax - uvright,uvYMin + uvbottom);
				_uvVertices[sliceVertIndex+2].Set (uvXMax - uvright,uvYMin);
				_uvVertices[sliceVertIndex+3].Set (uvXMin + uvleft,uvYMin);

				sliceVertIndex += 4;
			}
			else if (s == 4 && _insetLeft > 0) //left center slice
			{
				_localVertices[sliceVertIndex].Set   (localXMin,localYMax - itop);
				_localVertices[sliceVertIndex+1].Set (localXMin + ileft,localYMax - itop);
				_localVertices[sliceVertIndex+2].Set (localXMin + ileft,localYMin + ibottom);
				_localVertices[sliceVertIndex+3].Set (localXMin,localYMin + ibottom);

				_uvVertices[sliceVertIndex].Set   (uvXMin,uvYMax - uvtop);
				_uvVertices[sliceVertIndex+1].Set (uvXMin + uvleft,uvYMax - uvtop);
				_uvVertices[sliceVertIndex+2].Set (uvXMin + uvleft,uvYMin + uvbottom);
				_uvVertices[sliceVertIndex+3].Set (uvXMin,uvYMin + uvbottom);

				sliceVertIndex += 4;
			}
			else if (s == 5 && _insetTop > 0 && _insetLeft > 0) //top left slice
			{
				_localVertices[sliceVertIndex].Set   (localXMin,localYMax);
				_localVertices[sliceVertIndex+1].Set (localXMin + ileft,localYMax);
				_localVertices[sliceVertIndex+2].Set (localXMin + ileft,localYMax - itop);
				_localVertices[sliceVertIndex+3].Set (localXMin,localYMax - itop);

				_uvVertices[sliceVertIndex].Set   (uvXMin,uvYMax);
				_uvVertices[sliceVertIndex+1].Set (uvXMin + uvleft,uvYMax);
				_uvVertices[sliceVertIndex+2].Set (uvXMin + uvleft,uvYMax - uvtop);
				_uvVertices[sliceVertIndex+3].Set (uvXMin,uvYMax - uvtop);

				sliceVertIndex += 4;
			}
			else if (s == 6 && _insetTop > 0 && _insetRight > 0) //top right slice
			{
				_localVertices[sliceVertIndex].Set   (localXMax - iright,localYMax);
				_localVertices[sliceVertIndex+1].Set (localXMax,localYMax);
				_localVertices[sliceVertIndex+2].Set (localXMax,localYMax - itop);
				_localVertices[sliceVertIndex+3].Set (localXMax - iright,localYMax - itop);

				_uvVertices[sliceVertIndex].Set   (uvXMax - uvright, uvYMax);
				_uvVertices[sliceVertIndex+1].Set (uvXMax, uvYMax);
				_uvVertices[sliceVertIndex+2].Set (uvXMax, uvYMax - uvtop);
				_uvVertices[sliceVertIndex+3].Set (uvXMax - uvright, uvYMax - uvtop);

				sliceVertIndex += 4;
			}
			else if (s == 7 && _insetBottom > 0 && _insetRight > 0) //bottom right slice
			{
				_localVertices[sliceVertIndex].Set   (localXMax - iright,localYMin + ibottom);
				_localVertices[sliceVertIndex+1].Set (localXMax,localYMin + ibottom);
				_localVertices[sliceVertIndex+2].Set (localXMax,localYMin);
				_localVertices[sliceVertIndex+3].Set (localXMax - iright,localYMin);

				_uvVertices[sliceVertIndex].Set   (uvXMax - uvright, uvYMin + uvbottom);
				_uvVertices[sliceVertIndex+1].Set (uvXMax, uvYMin + uvbottom);
				_uvVertices[sliceVertIndex+2].Set (uvXMax, uvYMin);
				_uvVertices[sliceVertIndex+3].Set (uvXMax - uvright, uvYMin);

				sliceVertIndex += 4;
			}
			else if (s == 8 && _insetBottom > 0 && _insetLeft > 0) //bottom left slice
			{
				_localVertices[sliceVertIndex].Set   (localXMin,localYMin + ibottom);
				_localVertices[sliceVertIndex+1].Set (localXMin + ileft,localYMin + ibottom);
				_localVertices[sliceVertIndex+2].Set (localXMin + ileft,localYMin);
				_localVertices[sliceVertIndex+3].Set (localXMin,localYMin);

				_uvVertices[sliceVertIndex].Set   (uvXMin, uvYMin + uvbottom);
				_uvVertices[sliceVertIndex+1].Set (uvXMin + uvleft, uvYMin + uvbottom);
				_uvVertices[sliceVertIndex+2].Set (uvXMin + uvleft, uvYMin);
				_uvVertices[sliceVertIndex+3].Set (uvXMin, uvYMin);

				sliceVertIndex += 4;
			}
		}

		_isMeshDirty = true;
	}

	override public void PopulateRenderLayer()
	{
		if(_isOnStage && _firstFacetIndex != -1)
		{
			_isMeshDirty = false;

			for(int s = 0; s<_sliceCount; s++)
			{
				int sliceVertIndex = s*4;
				int vertexIndex0 = (_firstFacetIndex+s)*4;
				int vertexIndex1 = vertexIndex0 + 1;
				int vertexIndex2 = vertexIndex0 + 2;
				int vertexIndex3 = vertexIndex0 + 3;

				Vector3[] vertices = _renderLayer.vertices;
				Vector2[] uvs = _renderLayer.uvs;
				Color[] colors = _renderLayer.colors;

				_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0], _localVertices[sliceVertIndex],0);
				_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex1], _localVertices[sliceVertIndex+1],0);
				_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex2], _localVertices[sliceVertIndex+2],0);
				_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex3], _localVertices[sliceVertIndex+3],0);

				uvs[vertexIndex0] = _uvVertices[sliceVertIndex];
				uvs[vertexIndex1] = _uvVertices[sliceVertIndex+1];
				uvs[vertexIndex2] = _uvVertices[sliceVertIndex+2];
				uvs[vertexIndex3] = _uvVertices[sliceVertIndex+3];

				colors[vertexIndex0] = _alphaColor;
				colors[vertexIndex1] = _alphaColor;
				colors[vertexIndex2] = _alphaColor;
				colors[vertexIndex3] = _alphaColor;

				_renderLayer.HandleVertsChange();
			}
		}
	}

	public void SetInsets(float insetTop, float insetRight, float insetBottom, float insetLeft)
	{
		_insetTop = insetTop;
		_insetRight = insetRight;
		_insetBottom = insetBottom;
		_insetLeft = insetLeft;

		SetupSlices();
	}

	override public float width
	{
		get { return _width; }
		set { _width = value; _areLocalVerticesDirty = true; }
	}

	override public float height
	{
		get { return _height; }
		set { _height = value; _areLocalVerticesDirty = true; }
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Serialization;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis
{
    internal partial class ProjectState
    {
        public bool TryGetStateChecksums(out ProjectStateChecksums stateChecksums)
            => _lazyChecksums.TryGetValue(out stateChecksums);

        public Task<ProjectStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken)
            => _lazyChecksums.GetValueAsync(cancellationToken);

        public async Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken)
        {
            var collection = await _lazyChecksums.GetValueAsync(cancellationToken).ConfigureAwait(false);
            return collection.Checksum;
        }

        public Checksum GetParseOptionsChecksum()
            => GetParseOptionsChecksum(_solutionServices.Workspace.Services.GetService<ISerializerService>());

        private Checksum GetParseOptionsChecksum(ISerializerService serializer)
            => this.SupportsCompilation
                ? ChecksumCache.GetOrCreate(this.ParseOptions, _ => serializer.CreateParseOptionsChecksum(this.ParseOptions))
                : Checksum.Null;

        private async Task<ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken)
        {
            try
            {
                using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken))
                {
                    var documentChecksumsTasks = DocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken);
                    var additionalDocumentChecksumTasks = AdditionalDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken);
                    var analyzerConfigDocumentChecksumTasks = AnalyzerConfigDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken);

                    var serializer = _solutionServices.Workspace.Services.GetService<ISerializerService>();

                    var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken);

                    // these compiler objects doesn't have good place to cache checksum. but rarely ever get changed.
                    var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null;
                    cancellationToken.ThrowIfCancellationRequested();
                    var parseOptionsChecksum = GetParseOptionsChecksum(serializer);

                    var projectReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(ProjectReferences, _ => new ChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
                    var metadataReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(MetadataReferences, _ => new ChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
                    var analyzerReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(AnalyzerReferences, _ => new ChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));

                    var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false);
                    var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false);
                    var analyzerConfigDocumentChecksums = await Task.WhenAll(analyzerConfigDocumentChecksumTasks).ConfigureAwait(false);

                    return new ProjectStateChecksums(
                        infoChecksum,
                        compilationOptionsChecksum,
                        parseOptionsChecksum,
                        documentChecksums: new ChecksumCollection(documentChecksums),
                        projectReferenceChecksums,
                        metadataReferenceChecksums,
                        analyzerReferenceChecksums,
                        additionalDocumentChecksums: new ChecksumCollection(additionalChecksums),
                        analyzerConfigDocumentChecksumCollection: new ChecksumCollection(analyzerConfigDocumentChecksums));
                }
            }
            catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
    }
}


text:
using SF.Biz.Payments;
using SF.Sys.Annotations;
using SF.Sys.Auth;
using SF.Sys.Clients;
using SF.Sys.Entities;
using SF.Sys.NetworkService;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;

namespace SF.Biz.Accounting
{
    public class SettlementRollbackRecordQueryArguments :QueryArgument
    {
        /// <summary>
        /// 状态
        /// </summary>
        public SettlementRollbackState? State { get; set; }

        /// <summary>
        /// 买家
        /// </summary>
        [EntityIdent(typeof(User))]
        public long? BuyerId { get; set; }

        /// <summary>
        /// 卖家
        /// </summary>
        [EntityIdent(typeof(User))]
        public long? SellerId { get; set; }

        /// <summary>
        /// 支付平台
        /// </summary>
        [EntityIdent(typeof(PaymentPlatform))]
        public long? RefundPaymentPlatformId { get; set; }

        /// <summary>
        /// 时间
        /// </summary>
        public DateQueryRange CreatedTime { get; set; }

        /// <summary>
        /// 金额
        /// </summary>
        public QueryRange<decimal> Amount { get; set; }
    }

    public class SettlementRollbackCreateArgument
    {
        public long SettlementId { get; set; }
        public string Name { get; set; }
        public string Desc { get; set; }
        public decimal Amount { get; set; }
        public ClientInfo ClientInfo { get; set; }
        public TrackIdent BizRoot { get; set; }
        public TrackIdent BizParent { get; set; }
    }

    public enum SettlementRollbackState
    {
        Processing,
        Success,
        Failed
    }
    public class SettlementRollbackStatus
    {
        public long Id { get; set; }
        public SettlementRollbackState State { get; set; }
        public string Message { get; set; }
        public DateTime? Expires { get; set; }
    }

    /// <summary>
    /// 结算记录管理器
    /// </summary>
    [NetworkService]
    [EntityManager]
    [DefaultAuthorize(PredefinedRoles.财务专员)]
    [DefaultAuthorize(PredefinedRoles.系统管理员)]
    public interface ISettlementRollbackManager :
        IEntitySource<ObjectKey<long>, SettlementRollbackRecord, SettlementRollbackRecordDetail, SettlementRollbackRecordQueryArguments>
    {
        Task<SettlementRollbackStatus> Create(SettlementRollbackCreateArgument Argument);
        Task<SettlementRollbackStatus> UpdateAndQueryStatus(long Id,ClientInfo clientInfo=null);

    }
}


text:
/**
 * A module for the `axId` and `axFor` directives.
 *
 * @module axId
 */
import ng from 'angular';
import { assert } from 'laxar';

const module = ng.module( 'axId', [] );

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

const ID_DIRECTIVE_NAME = 'axId';

// eslint-disable-next-line valid-jsdoc
/**
 * This directive should be used within a widget whenever a unique id for a DOM element should be created.
 * It's value is evaluated as AngularJS expression and used as a local identifier to generate a distinct,
 * unique document wide id.
 *
 * A common use case is in combination with {@link axFor} for input fields having a label.
 *
 * Example:
 * ```html
 * <label ax-for="'userName'">Please enter your name:</label>
 * <input ax-id="'userName'" type="text" ng-model="username">
 * ```
 *
 * @name axId
 * @directive
 */
module.directive( ID_DIRECTIVE_NAME, [ () => {
   return {
      restrict: 'A',
      link( scope, element, attrs ) {
         const localId = scope.$eval( attrs[ ID_DIRECTIVE_NAME ] );
         assert.state( localId, 'directive axId needs a non-empty local id, e.g. ax-id="\'myLocalId\'".' );

         element.attr( 'id', scope.id( localId ) );
      }
   };
} ] );

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

const FOR_DIRECTIVE_NAME = 'axFor';

// eslint-disable-next-line valid-jsdoc
/**
 * This directive should be used within a widget whenever an id, generated using the {@link axId} directive,
 * should be referenced at a `label` element.
 *
 * Example:
 * ```html
 * <label ax-for="'userName'">Please enter your name:</label>
 * <input ax-id="'userName'" type="text" ng-model="username">
 * ```
 *
 * @name axFor
 * @directive
 */
module.directive( FOR_DIRECTIVE_NAME, [ () => {
   return {
      restrict: 'A',
      link( scope, element, attrs ) {
         const localId = scope.$eval( attrs[ FOR_DIRECTIVE_NAME ] );
         assert.state( localId, 'directive axFor needs a non-empty local id, e.g. ax-for="\'myLocalId\'".' );

         element.attr( 'for', scope.id( localId ) );
      }
   };
} ] );

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

export const name = module.name;


text:
#ifndef CryptoAlgorithmRsaKeyGenParams_h
#define CryptoAlgorithmRsaKeyGenParams_h

#include "CryptoAlgorithmParameters.h"
#include <wtf/Vector.h>

#if ENABLE(SUBTLE_CRYPTO)

namespace WebCore {

class CryptoAlgorithmRsaKeyGenParams final : public CryptoAlgorithmParameters {
public:
    CryptoAlgorithmRsaKeyGenParams()
        : hasHash(false)
    {
    }
    // The length, in bits, of the RSA modulus.
    unsigned modulusLength;
    // The RSA public exponent, encoded as BigInteger.
    Vector<uint8_t> publicExponent;
    // The hash algorith identifier
    bool hasHash;
    CryptoAlgorithmIdentifier hash;

    Class parametersClass() const override { return Class::RsaKeyGenParams; }
};

} // namespace WebCore

SPECIALIZE_TYPE_TRAITS_CRYPTO_ALGORITHM_PARAMETERS(RsaKeyGenParams)

#endif // ENABLE(SUBTLE_CRYPTO)
#endif // CryptoAlgorithmRsaKeyGenParams_h


text:
import requests
import unicodecsv
import utils

url = utils.API_URL
token = utils.get_api_key()
headers = utils.get_headers(token)

next_ = url + 'newagencytask'

task_fields = (
            'id',
            'agency',
            'resolved'
)

agency_fields = (
            'id',
            'name',
            'status',
            'jurisdiction',
            'address',
            'email',
            'other_emails',
            'phone',
            'fax',
            'website'
)

page = 1

csv_file = open('incomplete_agencies.csv', 'w')
csv_file.seek(0)
csv_writer = unicodecsv.writer(csv_file)
csv_writer.writerow(task_fields + agency_fields + ("Jurisdiction Name",))

print "OK, set up the file"

while next_ is not None:
    r = requests.get(next_, headers=headers)
    try:
        json = r.json()
        next_ = json['next']
        for datum in json['results']:
            print "The task " + str(datum["id"]) + " is " + str(datum["resolved"])
            if not (datum["resolved"]):
                a = requests.get((url+"agency/"+str(datum["agency"])), headers=headers)
                agency_json = a.json()
                print "We're looking up new agency info for " + agency_json["name"]
                all_fields = dict(datum)
                all_fields.update(agency_json)
                print "Created all fields. whatever the hell that is"
                print "Looking up jurisdiction " + str(agency_json["jurisdiction"])
                print url+"jurisdiction/"+str(agency_json["jurisdiction"])
                j = requests.get((url+"jurisdiction/"+str(agency_json["jurisdiction"])), headers=headers)
                jurisdiction_json = j.json()
                if jurisdiction_json["full_name"] is True:
                    jurisdiction2 = jurisdiction_json["full_name"]
                    print "The jurisdiction's full name is " + jurisdiction2
                else:
                    jurisdiction2 = jurisdiction_json["name"]
                    print "The jurisdiction is a state and its full name is " + jurisdiction2
                all_fields.update({'jurisdiction2': jurisdiction2})
                print all_fields
                csv_writer.writerow(all_fields[field] for field in task_fields+agency_fields+ ("jurisdiction2",))
        print 'Page %d of %d' % (page, json['count'] / 20 + 1)
        page += 1
    except:
        print "OMG!!!!"
        #print r
        #print r.text


text:
@implementation RideDayStatisticDb

@end