text:
using System;
using System.Drawing;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace ExifLibrary
{
	/// <summary>
	/// Represents the base class for image files.
	/// </summary>
	[TypeDescriptionProvider(typeof(ExifFileTypeDescriptionProvider))]
	public abstract class ImageFile
	{
		#region Constructor
		/// <summary>
		/// Initializes a new instance of the <see cref="ImageFile"/> class.
		/// </summary>
		protected ImageFile ()
		{
			Format = ImageFileFormat.Unknown;
			Properties = new ExifPropertyCollection ();
            Encoding = Encoding.Default;
		}
		#endregion

		#region Properties
		/// <summary>
		/// Returns the format of the <see cref="ImageFile"/>.
		/// </summary>
		public ImageFileFormat Format { get; protected set; }
		/// <summary>
		/// Gets the collection of Exif properties contained in the <see cref="ImageFile"/>.
		/// </summary>
		public ExifPropertyCollection Properties { get; private set; }
		/// <summary>
		/// Gets or sets the embedded thumbnail image.
		/// </summary>
		public ImageFile Thumbnail { get; set; }
		/// <summary>
		/// Gets or sets the Exif property with the given key.
		/// </summary>
		/// <param name="key">The Exif tag associated with the Exif property.</param>
		public ExifProperty this[int index] {
			get { return Properties[index]; }
			set { Properties[index] = value; }
		}
        /// <summary>
        /// Gets the encoding used for text metadata when the source encoding is unknown.
        /// </summary>
        public Encoding Encoding { get; protected set; }
		#endregion

		#region Instance Methods
		/// <summary>
		/// Converts the <see cref="ImageFile"/> to a <see cref="System.Drawing.Image"/>.
		/// </summary>
		/// <returns>Returns a <see cref="System.Drawing.Image"/> containing image data.</returns>
        public virtual Image ToImage()
        {
            MemoryStream stream = new MemoryStream();
            Save(stream);
            return Image.FromStream(stream);
        }

		/// <summary>
		/// Saves the <see cref="ImageFile"/> to the specified file.
		/// </summary>
		/// <param name="filename">A string that contains the name of the file.</param>
		public virtual void Save (string filename)
		{
			using (FileStream stream = new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.None)) {
				Save (stream);
			}
		}

		/// <summary>
		/// Saves the <see cref="ImageFile"/> to the specified stream.
		/// </summary>
		/// <param name="stream">A <see cref="Sytem.IO.Stream"/> to save image data to.</param>
		public abstract void Save (Stream stream);

        /// <summary>
        /// Decreases file size by removing all metadata.
        /// </summary>
        public abstract void Crush();
		#endregion

		#region Static Methods
		/// <summary>
		/// Creates an <see cref="ImageFile"/> from the specified file.
		/// </summary>
		/// <param name="filename">A string that contains the name of the file.</param>
		/// <returns>The <see cref="ImageFile"/> created from the file.</returns>
		public static ImageFile FromFile (string filename)
		{
            return FromFile(filename, Encoding.Default);
		}

        /// <summary>
        /// Creates an <see cref="ImageFile"/> from the specified file.
        /// </summary>
        /// <param name="filename">A string that contains the name of the file.</param>
        /// <param name="encoding">The encoding to be used for text metadata when the source encoding is unknown.</param>
        /// <returns>The <see cref="ImageFile"/> created from the file.</returns>
        public static ImageFile FromFile(string filename, Encoding encoding)
        {
            using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                return FromStream(stream, encoding);
            }
        }

        /// <summary>
		/// Creates an <see cref="ImageFile"/> from the specified data stream.
		/// </summary>
		/// <param name="stream">A <see cref="Sytem.IO.Stream"/> that contains image data.</param>
		/// <returns>The <see cref="ImageFile"/> created from the file.</returns>
        public static ImageFile FromStream(Stream stream)
        {
            return FromStream(stream, Encoding.Default);
        }

		/// <summary>
		/// Creates an <see cref="ImageFile"/> from the specified data stream.
		/// </summary>
		/// <param name="stream">A <see cref="Sytem.IO.Stream"/> that contains image data.</param>
        /// <param name="encoding">The encoding to be used for text metadata when the source encoding is unknown.</param>
		/// <returns>The <see cref="ImageFile"/> created from the file.</returns>
        public static ImageFile FromStream(Stream stream, Encoding encoding)
		{
			stream.Seek (0, SeekOrigin.Begin);
			byte[] header = new byte[8];
			stream.Seek (0, SeekOrigin.Begin);
			if (stream.Read (header, 0, header.Length) != header.Length)
				throw new NotValidImageFileException ();

			// JPEG
			if (header[0] == 0xFF && header[1] == 0xD8)
				return new JPEGFile (stream, encoding);

			// TIFF
			string tiffHeader = Encoding.ASCII.GetString (header, 0, 4);
			if (tiffHeader == "MM\x00\x2a" || tiffHeader == "II\x2a\x00")
				return new TIFFFile (stream, encoding);

            // PNG
            if (header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4E && header[3] == 0x47 &&
                header[4] == 0x0D && header[5] == 0x0A && header[6] == 0x1A && header[7] == 0x0A)
                return new PNGFile(stream, encoding);

			throw new NotValidImageFileException ();
		}
		#endregion
	}
}


text:
package me.ypedx.spigotboard.event;

import me.ypedx.spigotboard.SpigotBoard;
import me.ypedx.spigotboard.scoreboard.ScoreboardHandler;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;

public class QuitEvent implements Listener {

    private final ScoreboardHandler boardHandler;

    public QuitEvent(SpigotBoard instance) {
        this.boardHandler = instance.getBoardHandler();
    }

    @EventHandler
    public void onQuit(PlayerQuitEvent e) {
        Player player = e.getPlayer();

        if(boardHandler.hasBoard(player))
            boardHandler.removeBoardFromPlayer(player);
    }
}

redpajama_set_name: RedPajamaGithub


text:
has_vcards
==========

[![Build Status](https://secure.travis-ci.org/huerlisi/has_vcards.png)](http://travis-ci.org/huerlisi/has_vcards)

Rails plugin providing VCard like contact and address models and helpers.

Install
=======

In Rails simply add

    gem 'has_vcards'

License
=======

Released under the MIT license.


text:
using System;
using System.Collections.Generic;
using PokerLeagueManager.Common.Commands.Infrastructure;

namespace PokerLeagueManager.Commands.Domain.Infrastructure
{
    public interface IEventRepository
    {
        void PublishEvents(IAggregateRoot aggRoot, ICommand c);

        void PublishEvents(IEnumerable<IAggregateRoot> aggRoots, ICommand c);

        void PublishEvents(IAggregateRoot aggRoot, ICommand c, Guid originalVersion);

        T GetAggregateById<T>(Guid aggregateId) where T : IAggregateRoot;

        bool DoesAggregateExist(Guid aggregateId);

        void PublishAllUnpublishedEvents();
    }
}


text:
module Core.Prettify (prettify) where

import Renaming
import Utilities

import Algebra.Lattice

import Data.List (partition)
import qualified Data.Map as M
import qualified Data.Set as S

import Core.FreeVars
import Core.Renaming
import Core.Syntax

data Occurs = Once | Many
            deriving (Eq)

instance JoinSemiLattice Occurs where
    join _ _ = Many

prettify :: FVedTerm -> FVedTerm
prettify e = snd $ prettifyTerm prettifyIdSupply M.empty (mkIdentityRenaming (S.toList (fvedTermFreeVars e)), e)

type InlineEnv = M.Map (Out Var) (Out FVedTerm)
type OccursEnv = M.Map (Out Var) Occurs

prettifyTerm :: IdSupply -> InlineEnv -> In FVedTerm -> (OccursEnv, Out FVedTerm)
prettifyTerm ids inline (rn, e) = second fvedTerm $ prettifyTerm' ids inline (rn, fvee e)

prettifyTerm' :: IdSupply -> InlineEnv -> In (TermF FVed) -> (OccursEnv, Out (TermF FVed))
prettifyTerm' ids inline (rn, e) = case e of
    Var x -> prettifyVar inline (rn, x)
    Value v -> (occurs, e')
      where (occurs, e') = prettifyValue' ids inline (rn, v)
    App e x -> (M.insertWith join x' Many occurs, App e' x')
      where x' = rename rn x
            (occurs, e') = prettifyTerm ids inline (rn, e)
    PrimOp pop es -> (joins occurss, PrimOp pop es')
      where (occurss, es') = unzip $ map (\e -> prettifyTerm ids inline (rn, e)) es
    Case e alts -> (e_occurs `join` joins alt_occurss, Case e' alts')
      where (e_occurs, e') = prettifyTerm ids inline (rn, e)
            (alt_occurss, alts') = unzip $ map (\alt -> prettifyAlt ids inline (rn, alt)) alts
    LetRec xes e -> (xs' `deleteListMap` occurs', LetRec xes'_leave e')
      where (ids', rn', xes') = renameBounds (\_ x' -> x') ids rn xes
            (xs', in_es) = unzip xes'
            inline' = (xs' `deleteListMap` inline) `M.union` M.fromList xes'_inline
            (es_occurs, es') = unzip $ map (\in_e -> prettifyTerm ids' inline' in_e) in_es
            (e_occurs, e') = prettifyTerm ids' inline' (rn', e)
            occurs' = e_occurs `join` joins es_occurs

            -- Inline those bindings that occurred syntactically exactly once (or were dead):
            (xes'_inline, xes'_leave) = partition (\(x', _e') -> maybe True (== Once) (x' `M.lookup` occurs')) (xs' `zip` es')

prettifyVar :: InlineEnv -> In Var -> (OccursEnv, Out (TermF FVed))
prettifyVar inline (rn, x) = (M.singleton x' Once, case M.lookup x' inline of Just e' -> fvee e'; Nothing -> Var x') -- I *think* the substitution is OK, because in the pre-pass my Id threading ensures there is no shadowing
  where x' = rename rn x

prettifyValue' :: IdSupply -> InlineEnv -> In (ValueF FVed) -> (OccursEnv, Out (TermF FVed))
prettifyValue' ids inline (rn, v) = case v of
    Indirect x -> prettifyVar inline (rn, x)
    Lambda x e -> (M.delete x' occurs, Value (Lambda x' e'))
      where (ids', rn', x') = renameBinder ids rn x
            (occurs, e') = prettifyTerm ids' (M.delete x' inline) (rn', e)
    Data dc xs -> (listToMap Many xs', Value (Data dc xs'))
      where xs' = map (rename rn) xs
    Literal l  -> (M.empty, Value (Literal l))

prettifyAlt :: IdSupply -> InlineEnv -> In (AltF FVed) -> (OccursEnv, Out (AltF FVed))
prettifyAlt ids inline (rn, (alt_con, e)) = (bndrs' `deleteListMap` occurs, (alt_con', e'))
  where (ids', rn', alt_con') = renameAltCon ids rn alt_con
        (occurs, e') = prettifyTerm ids' (bndrs' `deleteListMap` inline) (rn', e)
        bndrs' = altConBinders alt_con'


text:
The Cancer Imaging Archive API Version 3  Client in Python with Requests

For more information about restful API visit:
    https://wiki.cancerimagingarchive.net/display/Public/TCIA+Programmatic+Interface+%28REST+API%29+Usage+Guide

# Requires:
    * Python 2.7.* (https://python.org)
    * Requests (http://docs.python-requests.org/en/latest/)

 Written for the latest version of the The Cancer Imaging Archive API (Version 3) as of 4/30/2015

# Install Requests

 To install requests use the command:

    python -m pip install requests


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

<title>PBESecretKeyEncryptor (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.openpgp.operator

Class PBESecretKeyEncryptor

java.lang.Object

org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor

public abstract class PBESecretKeyEncryptor
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

protected int
encAlgorithm

protected char[]
passPhrase

protected java.security.SecureRandom
random

protected S2K
s2k

protected int
s2kCount

protected PGPDigestCalculator
s2kDigestCalculator

Constructor Summary

Constructors

Modifier
Constructor and Description

protected
PBESecretKeyEncryptor(int encAlgorithm,
                     PGPDigestCalculator s2kDigestCalculator,
                     int s2kCount,
                     java.security.SecureRandom random,
                     char[] passPhrase)

protected
PBESecretKeyEncryptor(int encAlgorithm,
                     PGPDigestCalculator s2kDigestCalculator,
                     java.security.SecureRandom random,
                     char[] passPhrase)

Method Summary

Methods

Modifier and Type
Method and Description

byte[]
encryptKeyData(byte[] key,
              byte[] iv,
              byte[] keyData,
              int keyOff,
              int keyLen)

Encrypt the passed in keyData using the key and the iv provided.

abstract byte[]
encryptKeyData(byte[] key,
              byte[] keyData,
              int keyOff,
              int keyLen)

byte[]
encryptKeyData(byte[] keyData,
              int keyOff,
              int keyLen)

Key encryption method invoked for V4 keys and greater.

int
getAlgorithm()

abstract byte[]
getCipherIV()

int
getHashAlgorithm()

byte[]
getKey()

S2K
getS2K()

Methods inherited from class java.lang.Object

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

Field Detail

encAlgorithm

protected int encAlgorithm

passPhrase

protected char[] passPhrase

s2kDigestCalculator

protected PGPDigestCalculator s2kDigestCalculator

s2kCount

protected int s2kCount

s2k

protected S2K s2k

random

protected java.security.SecureRandom random

Constructor Detail

PBESecretKeyEncryptor

protected PBESecretKeyEncryptor(int encAlgorithm,
                     PGPDigestCalculator s2kDigestCalculator,
                     java.security.SecureRandom random,
                     char[] passPhrase)

PBESecretKeyEncryptor

protected PBESecretKeyEncryptor(int encAlgorithm,
                     PGPDigestCalculator s2kDigestCalculator,
                     int s2kCount,
                     java.security.SecureRandom random,
                     char[] passPhrase)

Method Detail

getAlgorithm

public int getAlgorithm()

getHashAlgorithm

public int getHashAlgorithm()

getKey

public byte[] getKey()
              throws PGPException

Throws:

PGPException

getS2K

public S2K getS2K()

encryptKeyData

public byte[] encryptKeyData(byte[] keyData,
                    int keyOff,
                    int keyLen)
                      throws PGPException

Key encryption method invoked for V4 keys and greater.

Parameters:

keyData - raw key data

keyOff - offset into raw key data

keyLen - length of key data to use.

Returns:

an encryption of the passed in keyData.

Throws:

PGPException - on error in the underlying encryption process.

encryptKeyData

public abstract byte[] encryptKeyData(byte[] key,
                    byte[] keyData,
                    int keyOff,
                    int keyLen)
                               throws PGPException

Throws:

PGPException

encryptKeyData

public byte[] encryptKeyData(byte[] key,
                    byte[] iv,
                    byte[] keyData,
                    int keyOff,
                    int keyLen)
                      throws PGPException

Encrypt the passed in keyData using the key and the iv provided.

 This method is only used for processing version 3 keys.

Throws:

PGPException

getCipherIV

public abstract byte[] getCipherIV()

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
:man_page: bson_json_opts_t

bson_json_opts_t
================

BSON to JSON encoding options

Synopsis
--------

.. code-block:: c

  #include <bson/bson.h>

  typedef struct _bson_json_opts_t bson_json_opts_t;

  bson_json_opts_t *
  bson_json_opts_new (bson_json_mode_t mode, int32_t max_len);

  void
  bson_json_opts_destroy (bson_json_opts_t *opts);

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

The :symbol:`bson_json_opts_t` structure contains options for encoding BSON into `MongoDB Extended JSON`_.

The ``mode`` member is a :symbol:`bson_json_mode_t` defining the encoding mode.

The ``max_len`` member holds a maximum length for the resulting JSON string. Encoding will stop once the serialised string has reached this length. To encode the full BSON document, ``BSON_MAX_LEN_UNLIMITED`` can be used.

.. seealso::

  | :symbol:`bson_as_json_with_opts()`

.. _MongoDB Extended JSON: https://github.com/mongodb/specifications/blob/master/source/extended-json.rst

.. only:: html

	  Functions
	  ---------

	  .. toctree::
	     :titlesonly:
	     :maxdepth: 1

	     bson_json_opts_new
	     bson_json_opts_destroy


text:
<?php

	require_once(DUPLICATOR_PLUGIN_PATH . '/views/javascript.php');
	require_once(DUPLICATOR_PLUGIN_PATH . '/views/inc.header.php');

	$logs = glob(DUPLICATOR_SSDIR_PATH . '/*.log') ;
	if ($logs != false && count($logs)) {
		usort($logs, create_function('$a,$b', 'return filemtime($b) - filemtime($a);'));
		@chmod(DUP_Util::SafePath($logs[0]), 0644);
	}

	$logname	 = (isset($_GET['logname'])) ? trim(sanitize_text_field($_GET['logname'])) : "";

	$refresh	 = (isset($_POST['refresh']) && $_POST['refresh'] == 1) ? 1 : 0;
	$auto		 = (isset($_POST['auto'])    && $_POST['auto'] == 1)    ? 1 : 0;

	//Check for invalid file
	if (!empty($logname)) {
		$validFiles = array_map('basename', $logs);
		if (validate_file($logname, $validFiles) > 0) {
			unset($logname);
		}
		unset($validFiles);
	}

	if (!isset($logname) || !$logname) {
		$logname  = (count($logs) > 0) ? basename($logs[0]) : "";
	}

	$logurl	 = get_site_url(null, '', is_ssl() ? 'https' : 'http') . '/' . DUPLICATOR_SSDIR_NAME . '/' . $logname;
	$logfound = (strlen($logname) > 0) ? true :false;

?>

<form id="dup-form-logs" method="post" action="">
<input type="hidden" id="refresh" name="refresh" value="<?php echo ($refresh) ? 1 : 0 ?>" />
<input type="hidden" id="auto" name="auto" value="<?php echo ($auto) ? 1 : 0 ?>" />
<?php if (! $logfound)  :	?>

<?php _e("Log file not found or unreadable", 'duplicator') ?>.

		<?php _e("Try to create a package, since no log files were found in the snapshots directory with the extension *.log", 'duplicator') ?>.

		<?php _e("Reasons for log file not showing", 'duplicator') ?>:

		- <?php _e("The web server does not support returning .log file extentions", 'duplicator') ?>.

		- <?php _e("The snapshots directory does not have the correct permissions to write files.  Try setting the permissions to 755", 'duplicator') ?>.

		- <?php _e("The process that PHP runs under does not have enough permissions to create files.  Please contact your hosting provider for more details", 'duplicator') ?>.

<?php else: ?>

 <?php echo basename($logurl); ?>

<?php _e("Options", 'duplicator') ?>

				<iframe id="dup-log-content" src="<?php echo $logurl ?>" >

<?php _e("Options", 'duplicator') ?>

					<input type="button" class="button" id="dup-refresh" value="<?php _e("Refresh", 'duplicator') ?>" />

						<input type='checkbox' id="dup-auto-refresh" style="margin-top:1px" />

							<?php _e("Auto Refresh", 'duplicator') ?>
							[

]

				<?php _e("Last 20 Logs", 'duplicator') ?>

					<?php
						$count=0;
						$active = basename($logurl);
						foreach ($logs as $log) {
							$time = date('h:i:s m/d/y', filemtime($log));
							$name = esc_html(basename($log));
							$url  = '?page=duplicator-tools&logname=' . $name;
							echo ($active == $name)
								? "{$time} - {$name}
"
								: "{$time} - {$name}
";
							if ($count > 20) break;
						}
					?>

<?php endif; ?>
</form>


text:
// Copyright (C) 2009 The Android Open Source Project
//
// 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 com.google.gerrit.pgm;

import com.google.gerrit.launcher.GerritLauncher;
import com.google.gerrit.pgm.util.AbstractProgram;

import org.kohsuke.args4j.Argument;

import java.io.IOException;
import java.io.InputStream;

/** Dump the contents of a file in our archive. */
public class Cat extends AbstractProgram {
  @Argument(index = 0, required = true, metaVar = "FILE", usage = "file to output")
  private String fileName;

  @Override
  public int run() throws IOException {
    while (fileName.startsWith("/")) {
      fileName = fileName.substring(1);
    }

    String name;
    if (fileName.equals("LICENSES.txt")) {
      name = fileName;
    } else {
      name = "WEB-INF/" + fileName;
    }

    try (InputStream in = open(name)) {
      if (in == null) {
        System.err.println("error: no such file " + fileName);
        return 1;
      }

      try {
        final byte[] buf = new byte[4096];
        int n;
        while ((n = in.read(buf)) >= 0) {
          System.out.write(buf, 0, n);
        }
      } finally {
        System.out.flush();
      }
    }
    return 0;
  }

  private InputStream open(String name) {
    return GerritLauncher.class.getClassLoader().getResourceAsStream(name);
  }
}


text:
(function () {
    var o;
    var o2;
    o = o.skipUntilWithTime(new Date());
    o = o.skipUntilWithTime(new Date(), Rx.Scheduler.default);
    o = o.skipUntilWithTime(1000);
    o = o.skipUntilWithTime(1000, Rx.Scheduler.default);
});
//# sourceMappingURL=skipuntilwithtime.js.map


text:
npm install
lein do clean, uberjar
DIR=deploy_assets
TAR=deploy.tar.gz
mkdir -p $DIR
cp target/objective8-0.0.1-SNAPSHOT-standalone.jar $DIR
cp -r resources/public $DIR
cp -r init-script $DIR
cp -r migrations $DIR
tar -cvzf $TAR $DIR
scp $TAR $REMOTE_USER@$SERVER_IP:~
ssh $REMOTE_USER@$SERVER_IP "tar -xvzf $TAR; cd $DIR; sudo bash init-script/remote_start_objective8.sh"
rm -rf $DIR
lein do clean


text:
CREATE TRIGGER inst_class
		ON class
		INSTEAD OF INSERT
AS
IF EXISTS (SELECT class.n_group	FROM class
		WHERE class.n_group IN (SELECT n_group FROM inserted)
		GROUP BY class.n_group
		HAVING COUNT( n_group ) >= 4)
PRINT 'Слишком много занятий'
ELSE
INSERT INTO class (audience, day_of_week, n_group, type_of_class)
SELECT audience, day_of_week, n_group, type_of_class FROM inserted

GO
INSERT INTO class (audience, day_of_week, n_group, type_of_class) VALUES(31, 'вт', 3221, 'лаб')
GO

-- for insert

CREATE TRIGGER for_class
		ON class
		FOR INSERT
AS
SELECT n_group, COUNT ( audience ) AS 'Количество аудиторий'
FROM class
GROUP BY n_group
GO

INSERT INTO class (audience, day_of_week, n_group, type_of_class) VALUES (21, 'вт', 2211, 'лаб')
GO

-- instead of delete

CREATE TRIGGER del_group
		ON uni_group
		INSTEAD OF DELETE
AS
    IF EXISTS( SELECT group_id FROM deleted WHERE group_id in (SELECT n_group FROM class))
		PRINT 'Невозможно удалить группу';
	ELSE
		DELETE FROM uni_group WHERE group_id in (SELECT group_id FROM deleted)
GO

DELETE FROM uni_group WHERE group_id = 3231

GO

-- instead of update

CREATE TRIGGER corps_update
		ON corps
		INSTEAD OF UPDATE
AS
BEGIN
	IF UPDATE(corps)
		BEGIN
			IF  EXISTS (
				SELECT corps
				FROM inserted
				WHERE corps IN (SELECT corps FROM corps ))

					UPDATE corps SET corps = inserted.corps
					FROM corps, inserted
					WHERE corps.corps = inserted.corps

			ELSE

					PRINT 'Невозможно изменить значение на неизвестное корпус'

		END
END

GO

UPDATE corps
SET
corps = 5555
GO

-- after delete

CREATE TRIGGER dell_after
		ON class
		AFTER DELETE
AS
DELETE audience
WHERE audience IN (SELECT audience FROM deleted
		      WHERE audience NOT IN (SELECT audience FROM class))
GO

DELETE FROM class where audience=32

-- after  update

CREATE TRIGGER after_update
		ON corps
		AFTER UPDATE
AS
IF UPDATE(corps)
BEGIN
	SELECT corps, COUNT(corps)
	FROM audience
	WHERE corps IN (SELECT corps FROM inserted )
	GROUP BY corps
END

ELSE ROLLBACK TRANSACTION

GO

UPDATE corps
SET corps = 2 where corps = 7


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.apimanagement.models;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;

/** Resource collection API of Products. */
public interface Products {
    /**
     * Lists a collection of products in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Products list representation as paginated response with {@link PagedIterable}.
     */
    PagedIterable<ProductContract> listByService(String resourceGroupName, String serviceName);

    /**
     * Lists a collection of products in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field | Usage | Supported operators | Supported functions
     *     |
|-------------|-------------|-------------|-------------|
| name | filter | ge, le, eq,
     *     ne, gt, lt | substringof, contains, startswith, endswith |
| displayName | filter | ge, le, eq, ne,
     *     gt, lt | substringof, contains, startswith, endswith |
| description | filter | ge, le, eq, ne, gt,
     *     lt | substringof, contains, startswith, endswith |
| terms | filter | ge, le, eq, ne, gt, lt |
     *     substringof, contains, startswith, endswith |
| state | filter | eq | |
| groups | expand
     *     | | |
.
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @param expandGroups When set to true, the response contains an array of groups that have visibility to the
     *     product. The default is false.
     * @param tags Products which are part of a specific tag.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Products list representation as paginated response with {@link PagedIterable}.
     */
    PagedIterable<ProductContract> listByService(
        String resourceGroupName,
        String serviceName,
        String filter,
        Integer top,
        Integer skip,
        Boolean expandGroups,
        String tags,
        Context context);

    /**
     * Gets the entity state (Etag) version of the product specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param productId Product identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void getEntityTag(String resourceGroupName, String serviceName, String productId);

    /**
     * Gets the entity state (Etag) version of the product specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param productId Product identifier. Must be unique in the current API Management service instance.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the entity state (Etag) version of the product specified by its identifier.
     */
    ProductsGetEntityTagResponse getEntityTagWithResponse(
        String resourceGroupName, String serviceName, String productId, Context context);

    /**
     * Gets the details of the product specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param productId Product identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the details of the product specified by its identifier.
     */
    ProductContract get(String resourceGroupName, String serviceName, String productId);

    /**
     * Gets the details of the product specified by its identifier.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param productId Product identifier. Must be unique in the current API Management service instance.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the details of the product specified by its identifier.
     */
    Response<ProductContract> getWithResponse(
        String resourceGroupName, String serviceName, String productId, Context context);

    /**
     * Delete product.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param productId Product identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void delete(String resourceGroupName, String serviceName, String productId, String ifMatch);

    /**
     * Delete product.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param productId Product identifier. Must be unique in the current API Management service instance.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @param deleteSubscriptions Delete existing subscriptions associated with the product or not.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response}.
     */
    Response<Void> deleteWithResponse(
        String resourceGroupName,
        String serviceName,
        String productId,
        String ifMatch,
        Boolean deleteSubscriptions,
        Context context);

    /**
     * Lists a collection of products associated with tags.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Tag list representation as paginated response with {@link PagedIterable}.
     */
    PagedIterable<TagResourceContract> listByTags(String resourceGroupName, String serviceName);

    /**
     * Lists a collection of products associated with tags.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field | Usage | Supported operators | Supported functions
     *     |
|-------------|-------------|-------------|-------------|
| name | filter | ge, le, eq,
     *     ne, gt, lt | substringof, contains, startswith, endswith |
| displayName | filter | ge, le, eq, ne,
     *     gt, lt | substringof, contains, startswith, endswith |
| description | filter | ge, le, eq, ne, gt,
     *     lt | substringof, contains, startswith, endswith |
| terms | filter | ge, le, eq, ne, gt, lt |
     *     substringof, contains, startswith, endswith |
| state | filter | eq | substringof, contains,
     *     startswith, endswith |
.
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @param includeNotTaggedProducts Include not tagged Products.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return paged Tag list representation as paginated response with {@link PagedIterable}.
     */
    PagedIterable<TagResourceContract> listByTags(
        String resourceGroupName,
        String serviceName,
        String filter,
        Integer top,
        Integer skip,
        Boolean includeNotTaggedProducts,
        Context context);

    /**
     * Gets the details of the product specified by its identifier.
     *
     * @param id the resource ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the details of the product specified by its identifier.
     */
    ProductContract getById(String id);

    /**
     * Gets the details of the product specified by its identifier.
     *
     * @param id the resource ID.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the details of the product specified by its identifier.
     */
    Response<ProductContract> getByIdWithResponse(String id, Context context);

    /**
     * Delete product.
     *
     * @param id the resource ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void deleteById(String id);

    /**
     * Delete product.
     *
     * @param id the resource ID.
     * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET
     *     request or it should be * for unconditional update.
     * @param deleteSubscriptions Delete existing subscriptions associated with the product or not.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response}.
     */
    Response<Void> deleteByIdWithResponse(String id, String ifMatch, Boolean deleteSubscriptions, Context context);

    /**
     * Begins definition for a new ProductContract resource.
     *
     * @param name resource name.
     * @return the first stage of the new ProductContract definition.
     */
    ProductContract.DefinitionStages.Blank define(String name);
}


text:
use clippy_utils::last_path_segment;
use if_chain::if_chain;
use rustc_hir::{GenericArg, QPath, TyKind};
use rustc_lint::LateContext;
use rustc_span::source_map::Span;

pub(super) fn match_borrows_parameter(_cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<Span> {
    let last = last_path_segment(qpath);
    if_chain! {
        if let Some(params) = last.args;
        if !params.parenthesized;
        if let Some(ty) = params.args.iter().find_map(|arg| match arg {
            GenericArg::Type(ty) => Some(ty),
            _ => None,
        });
        if let TyKind::Rptr(..) = ty.kind;
        then {
            return Some(ty.span);
        }
    }
    None
}


text:
package main

import (
	"bytes"
	"crypto/sha1"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"runtime"
	"strconv"
	"time"

	"github.com/goamz/goamz/aws"
	lsdb "github.com/goamz/goamz/exp/sdb"
	ls3 "github.com/goamz/goamz/s3"
	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
)

var (
	sdb       *lsdb.SDB
	domain    *lsdb.Domain
	bucket    *ls3.Bucket
	sdbDomain string
	s3Bucket  string
	startedAt string
)

var version = "0.0.0"

func addSlash(s string) string {
	return s[0:2] + "/" + s[2:40]
}

func WriteJSON(w http.ResponseWriter, data interface{}) {
	js, err := json.Marshal(data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.Write(js)
}

func blobHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	blob, err := bucket.Get(addSlash(vars["hash"]))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Write(blob)
}
func statsHandler(w http.ResponseWriter, r *http.Request) {
	query, err := sdb.Select(fmt.Sprintf("SELECT COUNT(*) FROM %v", sdbDomain), false)
	if err != nil {
		log.Printf("err:%v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	i := query.Items[0]
	cnt, _ := strconv.Atoi(i.Attrs[0].Value)
	sizeCounter := domain.Item("size")
	attrs, err := sizeCounter.Attrs(nil, false)
	if err != nil {
		log.Printf("err:%v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	var size int
	if len(attrs.Attrs) != 0 {
		size, _ = strconv.Atoi(attrs.Attrs[0].Value)
	}
	WriteJSON(w, map[string]interface{}{
		"blob_count": cnt - 1,
		"blob_size":  size,
		"version":    version,
		"started_at": startedAt,
		"s3_bucket":  s3Bucket,
		"sdb_domain": sdbDomain,
	})
}
func blobsHandler(w http.ResponseWriter, r *http.Request) {
	start := r.URL.Query().Get("start")
	if start == "" {
		start = "0"
	}
	end := r.URL.Query().Get("end")
	if end == "" {
		end = time.Now().UTC().Format(time.RFC3339Nano)
	}
	query, err := sdb.Select(fmt.Sprintf("SELECT * FROM %v where time > '%s' and time <= '%s' order by time asc", sdbDomain, start, end), false)
	if err != nil {
		log.Printf("err:%v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	res := []map[string]string{}
	for _, i := range query.Items {
		m := map[string]string{
			"hash": i.Name,
		}
		for _, attr := range i.Attrs {
			m[attr.Name] = attr.Value
		}
		res = append(res, m)
	}
	WriteJSON(w, map[string]interface{}{
		"blobs": res,
		"start": start,
		"end":   end,
	})
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		mr, err := r.MultipartReader()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		for {
			part, err := mr.NextPart()
			if err == io.EOF {
				break
			}
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			hash := part.FormName()
			var data bytes.Buffer
			data.ReadFrom(part)
			blob := data.Bytes()
			computedHash := fmt.Sprintf("%x", sha1.Sum(blob))
			if hash != computedHash {
				http.Error(w, "hash don't match", http.StatusInternalServerError)
			}
			if err := bucket.Put(addSlash(hash), blob, "", ls3.Private, ls3.Options{}); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			item := domain.Item(hash)
			pa := &lsdb.PutAttrs{}
			itemAttrs, err := item.Attrs(nil, false)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			if len(itemAttrs.Attrs) != 0 {
				// the blob is already indexed
				return
			}
			pa.Add("time", time.Now().UTC().Format(time.RFC3339Nano))
			if _, err := item.PutAttrs(pa); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			sizeCounter := domain.Item("size")
			for {
				attrs, err := sizeCounter.Attrs(nil, true)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
				}
				update := &lsdb.PutAttrs{}
				var prevSize int
				if len(attrs.Attrs) != 0 {
					prevSize, _ = strconv.Atoi(attrs.Attrs[0].Value)
					update.Replace("size", strconv.Itoa(prevSize+len(blob)))
					update.IfValue("size", strconv.Itoa(prevSize))
				} else {
					update.Add("size", strconv.Itoa(prevSize+len(blob)))
				}
				if _, err := sizeCounter.PutAttrs(update); err != nil {
					continue
				}
				break
			}
		}
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}

func main() {
	startedAt = time.Now().Format(time.RFC3339)
	auth, err := aws.EnvAuth()
	if err != nil {
		panic(err)
	}
	sdbDomain = os.Getenv("TS4_SDB_DOMAIN")
	if sdbDomain == "" {
		panic("TS4_SDB_DOMAIN not set")
	}
	s3Bucket = os.Getenv("TS4_S3_BUCKET")
	if s3Bucket == "" {
		panic("TS4_S3_BUCKET not set")
	}
	sdb = lsdb.New(auth, aws.USEast)
	s3 := ls3.New(auth, aws.USEast)
	domain = sdb.Domain(sdbDomain)
	if _, err := domain.CreateDomain(); err != nil {
		panic(err)
	}
	bucket = s3.Bucket(s3Bucket)
	if err := bucket.PutBucket(ls3.Private); err != nil {
		panic(err)
	}
	runtime.GOMAXPROCS(runtime.NumCPU())
	r := mux.NewRouter()
	r.Handle("/api/blobs", handlers.LoggingHandler(os.Stdout, http.HandlerFunc(blobsHandler)))
	r.Handle("/api/blob/{hash}", handlers.LoggingHandler(os.Stdout, http.HandlerFunc(blobHandler)))
	r.Handle("/api/upload", handlers.LoggingHandler(os.Stdout, http.HandlerFunc(uploadHandler)))
	r.Handle("/_stats", handlers.LoggingHandler(os.Stdout, http.HandlerFunc(statsHandler)))
	http.Handle("/", r)
	log.Printf("Starting ts4 version %v; %v (%v/%v)", version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
	log.Printf("HTTP API Listening on port 8010")
	http.ListenAndServe(":8010", nil)
}


text:
layout: home
excerpt: "A minimal Jekyll theme for your blog by designer Michael Rose."
tags: [Jekyll, theme, responsive, blog, template]
author: none
image:
  feature: team_hunk.png
  credit: TeachBack
  creditlink: http://teachback.co.uk
---

We – **Dario** (*left*) and **Thomas** (*right*) - are the horsepower behind TeachBack. We're both final year students at Imperial College London, and are spending our time working hard to scale TeachBack.

TeachBack is a platform to gain reliable feedback from students to help change the way universities around the UK access data. We have been selected as a winner of JISC's Summer of Innovation scheme in 2013, which will help us make TeachBack a reality.

Follow our progress and thoughts through this blog!

<hr />


text:
package org.apache.wiki.htmltowiki.syntax.markdown;

import org.apache.commons.lang3.StringUtils;
import org.apache.wiki.htmltowiki.WhitespaceTrimWriter;
import org.apache.wiki.htmltowiki.XHtmlElementToWikiTranslator;
import org.apache.wiki.htmltowiki.syntax.BrDecorator;

import java.io.PrintWriter;
import java.util.Deque;

/**
 * Markdown syntax implementation of {@link BrDecorator}.
 */
class MarkdownBrDecorator extends BrDecorator {

    private static final String INDENTATION_UNIT = StringUtils.repeat( WhitespaceTrimWriter.NO_TRIMMED_SPACE, 2 );

    MarkdownBrDecorator( final PrintWriter out, final Deque< String > preStack, final XHtmlElementToWikiTranslator chain ) {
        super( out, preStack, chain );
    }

    /** {@inheritDoc} */
    @Override
    protected String markupBr() {
        return INDENTATION_UNIT + "\n";
    }

}


text:
<readable><title>2434006663_207a284cec</title><content>
A brown dog is chasing a black dog on the sand .
A dog holding a stick running in the sand , chased by a grey dog .
Two dogs fetch sticks in the snow next to the tree line .
Two dogs running near a line of tall trees .
Two dogs running through sand .
</content></readable>


text:
function onRequest(context) {
    var log = new Log("listing.js");
    var DTYPE_CONF_DEVICE_TYPE_KEY = "deviceType";
    var DTYPE_CONF_DEVICE_CATEGORY = "category";
    var DTYPE_CONF_DEVICE_TYPE_LABEL_KEY = "label";
    var DTYPE_CONF_VIRTUAL_DEVICE_TYPE_LABEL_KEY = "virtualLabel";

    var viewModel = {};
    var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
    var utility = require("/app/modules/utility.js").utility;
    var typesListResponse = deviceModule.getDeviceTypes();
    // var typesListResponse = ['android'];
    if (typesListResponse["status"] == "success") {
        // var deviceTypes = typesListResponse.content.deviceTypes;
        var deviceTypes = ['android'];
        if (deviceTypes) {
            if (deviceTypes.length > 0) {
                viewModel.hasDeviceTypes = true;
            }
            var deviceTypesList = [],
                virtualDeviceTypesList = [];
            for (var i = 0; i < deviceTypes.length; i++) {
                var deviceType = deviceTypes[i];
                var deviceTypeLabel = deviceType;
                var configs = utility.getDeviceTypeConfig(deviceTypeLabel);
                var deviceCategory = "device";
                if (configs) {
                    if (configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_CATEGORY]) {
                        deviceCategory = configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_CATEGORY];
                    }
                    if (configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_TYPE_LABEL_KEY]) {
                        deviceTypeLabel = configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_TYPE_LABEL_KEY];
                    }
                }
                if (deviceCategory == 'virtual') {
                    virtualDeviceTypesList.push({
                        "hasCustTemplate": false,
                        "deviceTypeLabel": deviceTypeLabel,
                        "deviceTypeName": deviceType,
                        "deviceCategory": deviceCategory,
                        "thumb": utility.getDeviceThumb(deviceType)
                    });
                } else if (deviceCategory == 'hybrid') {
                    var virtualLabel = configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_VIRTUAL_DEVICE_TYPE_LABEL_KEY];
                    if (!virtualLabel) {
                        virtualLabel = deviceTypeLabel;
                    }
                    virtualDeviceTypesList.push({
                        "hasCustTemplate": false,
                        "deviceTypeLabel": virtualLabel,
                        "deviceTypeName": deviceType,
                        "deviceCategory": deviceCategory,
                        "thumb": utility.getDeviceThumb(deviceType)
                    });
                    deviceTypesList.push({
                        "hasCustTemplate": false,
                        "deviceTypeLabel": deviceTypeLabel,
                        "deviceTypeName": deviceType,
                        "deviceCategory": deviceCategory,
                        "thumb": utility.getDeviceThumb(deviceType)
                    });
                } else {
                    deviceTypesList.push({
                        "hasCustTemplate": false,
                        "deviceTypeLabel": deviceTypeLabel,
                        "deviceTypeName": deviceType,
                        "deviceCategory": deviceCategory,
                        "thumb": utility.getDeviceThumb(deviceType)
                    });
                }
            }
            if (virtualDeviceTypesList.length > 0) {
                viewModel.virtualDeviceTypesList = virtualDeviceTypesList;
            }
            viewModel.deviceTypesList = stringify(deviceTypesList);
        }
    } else {
        log.error("Unable to fetch device types data");
        throw new Error("Unable to fetch device types!");
    }

    return viewModel;
}


text:
template<typename T, typename U>
static T java_cast(U* u)
{
    if(!u) return static_cast<T>(nullptr);
    auto t = dynamic_cast<T>(u);
    if(!t) throw new ::java::lang::ClassCastException();
    return t;
}

template<typename T>
static T* npc(T* t)
{
    if(!t) throw new ::java::lang::NullPointerException();
    return t;
}

poi::hssf::usermodel::HSSFShapeGroup::HSSFShapeGroup(const ::default_init_tag&)
    : super(*static_cast< ::default_init_tag* >(0))
{
    clinit();
}

poi::hssf::usermodel::HSSFShapeGroup::HSSFShapeGroup(::poi::ddf::EscherContainerRecord* spgrContainer, ::poi::hssf::record::ObjRecord* objRecord)
    : HSSFShapeGroup(*static_cast< ::default_init_tag* >(0))
{
    ctor(spgrContainer,objRecord);
}

poi::hssf::usermodel::HSSFShapeGroup::HSSFShapeGroup(HSSFShape* parent, HSSFAnchor* anchor)
    : HSSFShapeGroup(*static_cast< ::default_init_tag* >(0))
{
    ctor(parent,anchor);
}

void poi::hssf::usermodel::HSSFShapeGroup::init()
{
    shapes = new ::java::util::ArrayList();
}

void poi::hssf::usermodel::HSSFShapeGroup::ctor(::poi::ddf::EscherContainerRecord* spgrContainer, ::poi::hssf::record::ObjRecord* objRecord)
{
    super::ctor(spgrContainer, objRecord);
    init();
    auto spContainer = java_cast< ::poi::ddf::EscherContainerRecord* >(npc(npc(spgrContainer)->getChildContainers())->get(0));
    _spgrRecord = java_cast< ::poi::ddf::EscherSpgrRecord* >(npc(spContainer)->getChild(int32_t(0)));
    for (auto _i = npc(npc(spContainer)->getChildRecords())->iterator(); _i->hasNext(); ) {
        ::poi::ddf::EscherRecord* ch = java_cast< ::poi::ddf::EscherRecord* >(_i->next());
        {
            switch (npc(ch)->getRecordId()) {
            case ::poi::ddf::EscherSpgrRecord::RECORD_ID:
                break;
            case ::poi::ddf::EscherClientAnchorRecord::RECORD_ID:
                anchor = new HSSFClientAnchor(java_cast< ::poi::ddf::EscherClientAnchorRecord* >(ch));
                break;
            case ::poi::ddf::EscherChildAnchorRecord::RECORD_ID:
                anchor = new HSSFChildAnchor(java_cast< ::poi::ddf::EscherChildAnchorRecord* >(ch));
                break;
            default:
                break;
            }

        }
    }
}

void poi::hssf::usermodel::HSSFShapeGroup::ctor(HSSFShape* parent, HSSFAnchor* anchor)
{
    super::ctor(parent, anchor);
    init();
    _spgrRecord = java_cast< ::poi::ddf::EscherSpgrRecord* >(npc((java_cast< ::poi::ddf::EscherContainerRecord* >(npc(getEscherContainer())->getChild(int32_t(0)))))->getChildById(::poi::ddf::EscherSpgrRecord::RECORD_ID));
}

poi::ddf::EscherContainerRecord* poi::hssf::usermodel::HSSFShapeGroup::createSpContainer()
{
    auto spgrContainer = new ::poi::ddf::EscherContainerRecord();
    auto spContainer = new ::poi::ddf::EscherContainerRecord();
    auto spgr = new ::poi::ddf::EscherSpgrRecord();
    auto sp = new ::poi::ddf::EscherSpRecord();
    auto opt = new ::poi::ddf::EscherOptRecord();
    ::poi::ddf::EscherRecord* anchor;
    auto clientData = new ::poi::ddf::EscherClientDataRecord();
    npc(spgrContainer)->setRecordId(::poi::ddf::EscherContainerRecord::SPGR_CONTAINER);
    npc(spgrContainer)->setOptions(static_cast< int16_t >(int32_t(15)));
    npc(spContainer)->setRecordId(::poi::ddf::EscherContainerRecord::SP_CONTAINER);
    npc(spContainer)->setOptions(static_cast< int16_t >(int32_t(15)));
    npc(spgr)->setRecordId(::poi::ddf::EscherSpgrRecord::RECORD_ID);
    npc(spgr)->setOptions(static_cast< int16_t >(int32_t(1)));
    npc(spgr)->setRectX1(0);
    npc(spgr)->setRectY1(0);
    npc(spgr)->setRectX2(1023);
    npc(spgr)->setRectY2(255);
    npc(sp)->setRecordId(::poi::ddf::EscherSpRecord::RECORD_ID);
    npc(sp)->setOptions(static_cast< int16_t >(int32_t(2)));
    if(dynamic_cast< HSSFClientAnchor* >(getAnchor()) != nullptr) {
        npc(sp)->setFlags(::poi::ddf::EscherSpRecord::FLAG_GROUP | ::poi::ddf::EscherSpRecord::FLAG_HAVEANCHOR);
    } else {
        npc(sp)->setFlags(::poi::ddf::EscherSpRecord::FLAG_GROUP | ::poi::ddf::EscherSpRecord::FLAG_HAVEANCHOR | ::poi::ddf::EscherSpRecord::FLAG_CHILD);
    }
    npc(opt)->setRecordId(::poi::ddf::EscherOptRecord::RECORD_ID);
    npc(opt)->setOptions(static_cast< int16_t >(int32_t(35)));
    npc(opt)->addEscherProperty(new ::poi::ddf::EscherBoolProperty(::poi::ddf::EscherProperties::PROTECTION__LOCKAGAINSTGROUPING, int32_t(262148)));
    npc(opt)->addEscherProperty(new ::poi::ddf::EscherBoolProperty(::poi::ddf::EscherProperties::GROUPSHAPE__PRINT, int32_t(524288)));
    anchor = npc(getAnchor())->getEscherAnchor();
    npc(clientData)->setRecordId(::poi::ddf::EscherClientDataRecord::RECORD_ID);
    npc(clientData)->setOptions(static_cast< int16_t >(int32_t(0)));
    npc(spgrContainer)->addChildRecord(spContainer);
    npc(spContainer)->addChildRecord(spgr);
    npc(spContainer)->addChildRecord(sp);
    npc(spContainer)->addChildRecord(opt);
    npc(spContainer)->addChildRecord(anchor);
    npc(spContainer)->addChildRecord(clientData);
    return spgrContainer;
}

poi::hssf::record::ObjRecord* poi::hssf::usermodel::HSSFShapeGroup::createObjRecord()
{
    auto obj = new ::poi::hssf::record::ObjRecord();
    auto cmo = new ::poi::hssf::record::CommonObjectDataSubRecord();
    npc(cmo)->setObjectType(::poi::hssf::record::CommonObjectDataSubRecord::OBJECT_TYPE_GROUP);
    npc(cmo)->setLocked(true);
    npc(cmo)->setPrintable(true);
    npc(cmo)->setAutofill(true);
    npc(cmo)->setAutoline(true);
    auto gmo = new ::poi::hssf::record::GroupMarkerSubRecord();
    auto end = new ::poi::hssf::record::EndSubRecord();
    npc(obj)->addSubRecord(cmo);
    npc(obj)->addSubRecord(gmo);
    npc(obj)->addSubRecord(end);
    return obj;
}

void poi::hssf::usermodel::HSSFShapeGroup::afterRemove(HSSFPatriarch* patriarch)
{
    npc(npc(patriarch)->getBoundAggregate())->removeShapeToObjRecord(java_cast< ::poi::ddf::EscherRecord* >(npc(java_cast< ::poi::ddf::EscherContainerRecord* >(npc(npc(getEscherContainer())->getChildContainers())->get(0)))->getChildById(::poi::ddf::EscherClientDataRecord::RECORD_ID)));
    for (auto i = int32_t(0); i < npc(shapes)->size(); i++) {
        auto shape = java_cast< HSSFShape* >(npc(shapes)->get(i));
        removeShape(shape);
        npc(shape)->afterRemove(getPatriarch());
    }
    npc(shapes)->clear();
}

void poi::hssf::usermodel::HSSFShapeGroup::onCreate(HSSFShape* shape)
{
    if(getPatriarch() != nullptr) {
        auto spContainer = npc(shape)->getEscherContainer();
        auto shapeId = npc(getPatriarch())->newShapeId();
        npc(shape)->setShapeId(shapeId);
        npc(getEscherContainer())->addChildRecord(spContainer);
        npc(shape)->afterInsert(getPatriarch());
        ::poi::ddf::EscherSpRecord* sp;
        if(dynamic_cast< HSSFShapeGroup* >(shape) != nullptr) {
            sp = java_cast< ::poi::ddf::EscherSpRecord* >(npc(java_cast< ::poi::ddf::EscherContainerRecord* >(npc(npc(npc(shape)->getEscherContainer())->getChildContainers())->get(0)))->getChildById(::poi::ddf::EscherSpRecord::RECORD_ID));
        } else {
            sp = java_cast< ::poi::ddf::EscherSpRecord* >(npc(npc(shape)->getEscherContainer())->getChildById(::poi::ddf::EscherSpRecord::RECORD_ID));
        }
        npc(sp)->setFlags(npc(sp)->getFlags() | ::poi::ddf::EscherSpRecord::FLAG_CHILD);
    }
}

poi::hssf::usermodel::HSSFShapeGroup* poi::hssf::usermodel::HSSFShapeGroup::createGroup(HSSFChildAnchor* anchor)
{
    auto group = new HSSFShapeGroup(static_cast< HSSFShape* >(this), static_cast< HSSFAnchor* >(anchor));
    npc(group)->setParent(this);
    npc(group)->setAnchor(anchor);
    npc(shapes)->add(static_cast< ::java::lang::Object* >(group));
    onCreate(group);
    return group;
}

void poi::hssf::usermodel::HSSFShapeGroup::addShape(HSSFShape* shape)
{
    npc(shape)->setPatriarch(this->getPatriarch());
    npc(shape)->setParent(this);
    npc(shapes)->add(static_cast< ::java::lang::Object* >(shape));
}

poi::hssf::usermodel::HSSFSimpleShape* poi::hssf::usermodel::HSSFShapeGroup::createShape(HSSFChildAnchor* anchor)
{
    auto shape = new HSSFSimpleShape(static_cast< HSSFShape* >(this), static_cast< HSSFAnchor* >(anchor));
    npc(shape)->setParent(this);
    npc(shape)->setAnchor(anchor);
    npc(shapes)->add(static_cast< ::java::lang::Object* >(shape));
    onCreate(shape);
    auto sp = java_cast< ::poi::ddf::EscherSpRecord* >(npc(npc(shape)->getEscherContainer())->getChildById(::poi::ddf::EscherSpRecord::RECORD_ID));
    if(npc(npc(shape)->getAnchor())->isHorizontallyFlipped()) {
        npc(sp)->setFlags(npc(sp)->getFlags() | ::poi::ddf::EscherSpRecord::FLAG_FLIPHORIZ);
    }
    if(npc(npc(shape)->getAnchor())->isVerticallyFlipped()) {
        npc(sp)->setFlags(npc(sp)->getFlags() | ::poi::ddf::EscherSpRecord::FLAG_FLIPVERT);
    }
    return shape;
}

poi::hssf::usermodel::HSSFTextbox* poi::hssf::usermodel::HSSFShapeGroup::createTextbox(HSSFChildAnchor* anchor)
{
    auto shape = new HSSFTextbox(this, anchor);
    npc(shape)->setParent(this);
    npc(shape)->setAnchor(anchor);
    npc(shapes)->add(static_cast< ::java::lang::Object* >(shape));
    onCreate(shape);
    return shape;
}

poi::hssf::usermodel::HSSFPolygon* poi::hssf::usermodel::HSSFShapeGroup::createPolygon(HSSFChildAnchor* anchor)
{
    auto shape = new HSSFPolygon(static_cast< HSSFShape* >(this), static_cast< HSSFAnchor* >(anchor));
    npc(shape)->setParent(this);
    npc(shape)->setAnchor(anchor);
    npc(shapes)->add(static_cast< ::java::lang::Object* >(shape));
    onCreate(shape);
    return shape;
}

poi::hssf::usermodel::HSSFPicture* poi::hssf::usermodel::HSSFShapeGroup::createPicture(HSSFChildAnchor* anchor, int32_t pictureIndex)
{
    auto shape = new HSSFPicture(static_cast< HSSFShape* >(this), static_cast< HSSFAnchor* >(anchor));
    npc(shape)->setParent(this);
    npc(shape)->setAnchor(anchor);
    npc(shape)->setPictureIndex(pictureIndex);
    npc(shapes)->add(static_cast< ::java::lang::Object* >(shape));
    onCreate(shape);
    auto sp = java_cast< ::poi::ddf::EscherSpRecord* >(npc(npc(shape)->getEscherContainer())->getChildById(::poi::ddf::EscherSpRecord::RECORD_ID));
    if(npc(npc(shape)->getAnchor())->isHorizontallyFlipped()) {
        npc(sp)->setFlags(npc(sp)->getFlags() | ::poi::ddf::EscherSpRecord::FLAG_FLIPHORIZ);
    }
    if(npc(npc(shape)->getAnchor())->isVerticallyFlipped()) {
        npc(sp)->setFlags(npc(sp)->getFlags() | ::poi::ddf::EscherSpRecord::FLAG_FLIPVERT);
    }
    return shape;
}

java::util::List* poi::hssf::usermodel::HSSFShapeGroup::getChildren()
{
    return ::java::util::Collections::unmodifiableList(shapes);
}

void poi::hssf::usermodel::HSSFShapeGroup::setCoordinates(int32_t x1, int32_t y1, int32_t x2, int32_t y2)
{
    npc(_spgrRecord)->setRectX1(x1);
    npc(_spgrRecord)->setRectX2(x2);
    npc(_spgrRecord)->setRectY1(y1);
    npc(_spgrRecord)->setRectY2(y2);
}

void poi::hssf::usermodel::HSSFShapeGroup::clear()
{
    auto copy = new ::java::util::ArrayList(static_cast< ::java::util::Collection* >(shapes));
    for (auto _i = npc(copy)->iterator(); _i->hasNext(); ) {
        HSSFShape* shape = java_cast< HSSFShape* >(_i->next());
        {
            removeShape(shape);
        }
    }
}

int32_t poi::hssf::usermodel::HSSFShapeGroup::getX1()
{
    return npc(_spgrRecord)->getRectX1();
}

int32_t poi::hssf::usermodel::HSSFShapeGroup::getY1()
{
    return npc(_spgrRecord)->getRectY1();
}

int32_t poi::hssf::usermodel::HSSFShapeGroup::getX2()
{
    return npc(_spgrRecord)->getRectX2();
}

int32_t poi::hssf::usermodel::HSSFShapeGroup::getY2()
{
    return npc(_spgrRecord)->getRectY2();
}

int32_t poi::hssf::usermodel::HSSFShapeGroup::countOfAllChildren()
{
    auto count = npc(shapes)->size();
    for (auto *iterator = npc(shapes)->iterator(); npc(iterator)->hasNext(); ) {
        auto shape = java_cast< HSSFShape* >(npc(iterator)->next());
        count += npc(shape)->countOfAllChildren();
    }
    return count;
}

void poi::hssf::usermodel::HSSFShapeGroup::afterInsert(HSSFPatriarch* patriarch)
{
    auto agg = npc(patriarch)->getBoundAggregate();
    auto containerRecord = java_cast< ::poi::ddf::EscherContainerRecord* >(npc(getEscherContainer())->getChildById(::poi::ddf::EscherContainerRecord::SP_CONTAINER));
    npc(agg)->associateShapeToObjRecord(java_cast< ::poi::ddf::EscherRecord* >(npc(containerRecord)->getChildById(::poi::ddf::EscherClientDataRecord::RECORD_ID)), getObjRecord());
}

void poi::hssf::usermodel::HSSFShapeGroup::setShapeId(int32_t shapeId)
{
    auto containerRecord = java_cast< ::poi::ddf::EscherContainerRecord* >(npc(getEscherContainer())->getChildById(::poi::ddf::EscherContainerRecord::SP_CONTAINER));
    auto spRecord = java_cast< ::poi::ddf::EscherSpRecord* >(npc(containerRecord)->getChildById(::poi::ddf::EscherSpRecord::RECORD_ID));
    npc(spRecord)->setShapeId(shapeId);
    auto cod = java_cast< ::poi::hssf::record::CommonObjectDataSubRecord* >(java_cast< ::poi::hssf::record::SubRecord* >(npc(npc(getObjRecord())->getSubRecords())->get(0)));
    npc(cod)->setObjectId(static_cast< int16_t >((shapeId % int32_t(1024))));
}

int32_t poi::hssf::usermodel::HSSFShapeGroup::getShapeId()
{
    auto containerRecord = java_cast< ::poi::ddf::EscherContainerRecord* >(npc(getEscherContainer())->getChildById(::poi::ddf::EscherContainerRecord::SP_CONTAINER));
    return npc((java_cast< ::poi::ddf::EscherSpRecord* >(java_cast< ::poi::ddf::EscherRecord* >(npc(containerRecord)->getChildById(::poi::ddf::EscherSpRecord::RECORD_ID)))))->getShapeId();
}

poi::hssf::usermodel::HSSFShape* poi::hssf::usermodel::HSSFShapeGroup::cloneShape()
{
    throw new ::java::lang::IllegalStateException(u"Use method cloneShape(HSSFPatriarch patriarch)"_j);
}

poi::hssf::usermodel::HSSFShape* poi::hssf::usermodel::HSSFShapeGroup::cloneShape(HSSFPatriarch* patriarch)
{
    auto spgrContainer = new ::poi::ddf::EscherContainerRecord();
    npc(spgrContainer)->setRecordId(::poi::ddf::EscherContainerRecord::SPGR_CONTAINER);
    npc(spgrContainer)->setOptions(static_cast< int16_t >(int32_t(15)));
    auto spContainer = new ::poi::ddf::EscherContainerRecord();
    auto cont = java_cast< ::poi::ddf::EscherContainerRecord* >(npc(getEscherContainer())->getChildById(::poi::ddf::EscherContainerRecord::SP_CONTAINER));
    auto inSp = npc(cont)->serialize();
    npc(spContainer)->fillFields(inSp, int32_t(0), static_cast< ::poi::ddf::EscherRecordFactory* >(new ::poi::ddf::DefaultEscherRecordFactory()));
    npc(spgrContainer)->addChildRecord(spContainer);
    ::poi::hssf::record::ObjRecord* obj = nullptr;
    if(nullptr != getObjRecord()) {
        obj = java_cast< ::poi::hssf::record::ObjRecord* >(npc(getObjRecord())->cloneViaReserialise());
    }
    auto group = new HSSFShapeGroup(spgrContainer, obj);
    npc(group)->setPatriarch(patriarch);
    for (auto _i = npc(getChildren())->iterator(); _i->hasNext(); ) {
        HSSFShape* shape = java_cast< HSSFShape* >(_i->next());
        {
            HSSFShape* newShape;
            if(dynamic_cast< HSSFShapeGroup* >(shape) != nullptr) {
                newShape = npc((java_cast< HSSFShapeGroup* >(shape)))->cloneShape(patriarch);
            } else {
                newShape = npc(shape)->cloneShape();
            }
            npc(group)->addShape(newShape);
            npc(group)->onCreate(newShape);
        }
    }
    return group;
}

bool poi::hssf::usermodel::HSSFShapeGroup::removeShape(HSSFShape* shape)
{
    auto isRemoved = npc(getEscherContainer())->removeChildRecord(npc(shape)->getEscherContainer());
    if(isRemoved) {
        npc(shape)->afterRemove(this->getPatriarch());
        npc(shapes)->remove(static_cast< ::java::lang::Object* >(shape));
    }
    return isRemoved;
}

java::util::Iterator* poi::hssf::usermodel::HSSFShapeGroup::iterator()
{
    return npc(shapes)->iterator();
}

extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* poi::hssf::usermodel::HSSFShapeGroup::class_()
{
    static ::java::lang::Class* c = ::class_(u"org.apache.poi.hssf.usermodel.HSSFShapeGroup", 44);
    return c;
}

java::lang::Class* poi::hssf::usermodel::HSSFShapeGroup::getClass0()
{
    return class_();
}


text:
package com.eiffel.psi;

import com.eiffel.EiffelSourceFileType;
import com.eiffel.psi.stubs.EiffelStubIndexKeys;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.FileTypeIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.stubs.StubIndex;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.Nullable;

import java.util.*;
import java.util.stream.Collectors;

public class EiffelClassUtil {
    private static String bindingMap(String name) {
        if (name.equals("INTEGER")) name = "INTEGER_32";
        if (name.equals("CHARACTER")) name = "CHARACTER_8";
        if (name.equals("STRING")) name = "STRING_8";
        return name;
    }

    public static String formalizeName(String name) {
        if (name == null) return null;
        name = bindingMap(name);
        return name
                .replace("like", "$like$") // HACK well, you see it
                .replace("detachable", "$det$")
                .replace("separate", "$sep$")
                .replace(" ", "")
                .replace("[", " [")
                .replace(",", ", ")
                .replace(":", ": ")
                .replace(";", "; ")
                .replace("$like$", "like ")
                .replace("$det$", " detachable ")
                .replace("$sep$", " separate ");
    }

    public static String ungenerify(String className) {
        if (className == null) return null;
        className = bindingMap(className);
        return className.replaceAll("\\[.*]", "").trim();
    }

    public static List<EiffelClassDeclaration> findClassDeclarations(Project project) {
        return findClassDeclarationsWithPrefix(project, "");
    }

    public static List<EiffelClassDeclaration> findClassDeclarationsWithPrefix(Project project, String prefix) {
        List<EiffelClassDeclaration> result = new ArrayList<>();

        Collection<VirtualFile> virtualFiles = FileTypeIndex.getFiles(EiffelSourceFileType.INSTANCE, GlobalSearchScope.allScope(project));

        for (VirtualFile virtualFile : virtualFiles) {
            EiffelFile file = (EiffelFile) PsiManager.getInstance(project).findFile(virtualFile);
            if (file != null) {
                EiffelClassDeclaration[] classDeclarations = PsiTreeUtil.getChildrenOfType(file, EiffelClassDeclaration.class);
                if (classDeclarations != null && classDeclarations.length > 0) {
                    for (EiffelClassDeclaration declaration : classDeclarations) {
                        if (formalizeName(declaration.getName()).startsWith(prefix)) {
                            result.add(declaration);
                        }
                    }
                }
            }
        }

        return result;
    }

    public static List<String> findClassDeclarationNames(Project project) {
        return (List<String>)
                StubIndex.getInstance().getAllKeys(EiffelStubIndexKeys.SYMBOLS_KEY, project)
                        .stream()
                        .filter((Object s) -> !((String)s).contains("."))
                        .collect(Collectors.toList());
    }

    /**
     * Find class declaration from any child element
     * @param element - child element
     * @return ancestor class declaration
     */
    public static EiffelClassDeclaration findClassDeclaration(PsiElement element) {
        ASTNode classDeclaration = findParentOfType(element.getNode(), EiffelTypes.CLASS_DECLARATION);
        if (classDeclaration == null) return null;
        return classDeclaration.getPsi(EiffelClassDeclaration.class);
    }

    /**
     * Find feature declaration from any element (closest ancestor)
     * @param element - child element
     * @return ancestor feature declaration
     */
    public static EiffelFeatureDeclaration findFeatureDeclaration(PsiElement element) {
        ASTNode featureDeclaration = findParentOfType(element.getNode(), EiffelTypes.FEATURE_DECLARATION);
        if (featureDeclaration == null) return null;
        return featureDeclaration.getPsi(EiffelFeatureDeclaration.class);
    }

    public static EiffelClassDeclaration findClassDeclaration(Project project, String name) {
        Collection<EiffelClassDeclaration> declarations = StubIndex.getElements(
                EiffelStubIndexKeys.SYMBOLS_KEY,
                ungenerify(name),
                project,
                GlobalSearchScope.allScope(project),
                EiffelClassDeclaration.class
        );
        if (declarations.size() == 0) return null;
        return declarations.toArray(new EiffelClassDeclaration[1])[0];
    }

    public static EiffelFeatureDeclaration findFeatureDeclaration(Project project, String className, String feature) {
        EiffelClassDeclaration classDeclaration = findClassDeclaration(project, className);
        if (classDeclaration == null) return null;
        for (EiffelNewFeature newFeature : classDeclaration.getAllNewFeatures()) {
            if (newFeature.getFeatureName().getText().equals(feature)) {
                return newFeature.getFeatureDeclaration();
            }
        }
        return null;
    }

    @Nullable
    public static String findFeatureReturnType(Project project, String className, String feature) {
        EiffelClassDeclaration classDeclaration = findClassDeclaration(project, className);
        if (classDeclaration == null) return null;
        EiffelNewFeature newFeature = classDeclaration.getNewFeature(feature);
        if (newFeature == null) return null;
        return newFeature.getTypeString();
//        if (className.equals("APPLICATION")) {
//            return "STD_FILES";
//        }
//        return null;
    }

    @Nullable
    public static ASTNode findParentOfType(ASTNode node, IElementType type) {
        while (node != null) {
            if (node.getElementType().equals(type)) {
                break;
            }
            node = node.getTreeParent();
        }
        return node;
    }

    @Nullable
    public static String findParentingClassForFeatureCall(Project project, PsiElement unqualifiedCall) {
        return EiffelTypeResolutionUtil.getTypeString(project, unqualifiedCall, true);
        // TODO: -
//        return "STD_FILES";
    }

    @Nullable
    public static EiffelTypedElement findReferencedElementInContext(PsiElement reference) {
        final String name = reference.getText();
        EiffelFeatureDeclaration featureDeclaration = findFeatureDeclaration(reference);
        if (featureDeclaration != null) {
            EiffelEntityIdentifier identifier = featureDeclaration.getLocalEntityIdentifier(name);
            if (identifier != null) return identifier;
            identifier = featureDeclaration.getFormalArgumentIdentifier(name);
            if (identifier != null) return identifier;
        }
        EiffelClassDeclaration classDeclaration = findClassDeclaration(reference);
        if (classDeclaration != null) {
            EiffelNewFeature feature = classDeclaration.getNewFeature(name);
            if (feature != null) return feature;
        }
        return null;
    }
}


text:
.. title:: MochiKit.Async - manage asynchronous tasks

Name
====

MochiKit.Async - manage asynchronous tasks

Synopsis
========

::

    var url = "/src/b/bo/bob/MochiKit.Async/META.json";
    /*

        META.json looks something like this:

        {"name": "MochiKit", "version": "0.5"}

    */
    var d = loadJSONDoc(url);
    var gotMetadata = function (meta) {
        if (MochiKit.Async.VERSION == meta.version) {
            alert("You have the newest MochiKit.Async!");
        } else {
            alert("MochiKit.Async "
                + meta.version
                + " is available, upgrade!");
        }
    };
    var metadataFetchFailed = function (err) {
      alert("The metadata for MochiKit.Async could not be fetched :(");
    };
    d.addCallbacks(gotMetadata, metadataFetchFailed);

Description
===========

MochiKit.Async provides facilities to manage asynchronous (as in AJAX
[1]_) tasks. The model for asynchronous computation used in this
module is heavily inspired by Twisted [2]_.

Dependencies
============

- :mochiref:`MochiKit.Base`

Overview
========

Deferred
--------

The Deferred constructor encapsulates a single value that is not
available yet. The most important example of this in the context of a
web browser would be an ``XMLHttpRequest`` to a server. The importance
of the Deferred is that it allows a consistent API to be exposed for
all asynchronous computations that occur exactly once.

The producer of the Deferred is responsible for doing all of the
complicated work behind the scenes. This often means waiting for a
timer to fire, or waiting for an event (e.g. ``onreadystatechange`` of
``XMLHttpRequest``).  It could also be coordinating several events
(e.g.  ``XMLHttpRequest`` with a timeout, or several Deferreds
(e.g. fetching a set of XML documents that should be processed at the
same time).

Since these sorts of tasks do not respond immediately, the producer of
the Deferred does the following steps before returning to the
consumer:

1. Create a ``new`` :mochiref:`Deferred();` object and keep a
   reference to it, because it will be needed later when the value is
   ready.
2. Setup the conditions to create the value requested (e.g.  create a
   new ``XMLHttpRequest``, set its ``onreadystatechange``).
3. Return the :mochiref:`Deferred` object.

Since the value is not yet ready, the consumer attaches a function to
the Deferred that will be called when the value is ready. This is not
unlike ``setTimeout``, or other similar facilities you may already be
familiar with.  The consumer can also attach an "errback" to the
:mochiref:`Deferred`, which is a callback for error handling.

When the value is ready, the producer simply calls
``myDeferred.callback(theValue)``. If an error occurred, it should
call ``myDeferred.errback(theValue)`` instead.  As soon as this
happens, the callback that the consumer attached to the
:mochiref:`Deferred` is called with ``theValue`` as the only argument.

There are quite a few additional "advanced" features baked into
:mochiref:`Deferred`, such as cancellation and callback chains, so
take a look at the API reference if you would like to know more!

API Reference
=============

Errors
------

:mochidef:`AlreadyCalledError`:

    Thrown by a :mochiref:`Deferred` if ``.callback`` or ``.errback``
    are called more than once.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`BrowserComplianceError`:

    Thrown when the JavaScript runtime is not capable of performing
    the given function. Currently, this happens if the browser does
    not support ``XMLHttpRequest``.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`CancelledError`:

    Thrown by a :mochiref:`Deferred` when it is cancelled, unless a
    canceller is present and throws something else.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`GenericError`:

    Results passed to ``.fail`` or ``.errback`` of a
    :mochiref:`Deferred` are wrapped by this ``Error`` if ``!(result
    instanceof Error)``.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`XMLHttpRequestError`:

    Thrown when an ``XMLHttpRequest`` does not complete successfully
    for any reason. The ``req`` property of the error is the failed
    ``XMLHttpRequest`` object, and for convenience the ``number``
    property corresponds to ``req.status``.

    *Availability*:
        Available in MochiKit 1.3.1+

Constructors
------------

:mochidef:`Deferred()`:

    Encapsulates a sequence of callbacks in response to a value that
    may not yet be available. This is modeled after the Deferred class
    from Twisted [3]_.

.. _`Twisted`: http://twistedmatrix.com/

    Why do we want this?  JavaScript has no threads, and even if it
    did, threads are hard. Deferreds are a way of abstracting
    non-blocking events, such as the final response to an
    ``XMLHttpRequest``.

    The sequence of callbacks is internally represented as a list of
    2-tuples containing the callback/errback pair. For example, the
    following call sequence::

        var d = new Deferred();
        d.addCallback(myCallback);
        d.addErrback(myErrback);
        d.addBoth(myBoth);
        d.addCallbacks(myCallback, myErrback);

    is translated into a :mochiref:`Deferred` with the following
    internal representation::

        [
            [myCallback, null],
            [null, myErrback],
            [myBoth, myBoth],
            [myCallback, myErrback]
        ]

    The :mochiref:`Deferred` also keeps track of its current status
    (fired).  Its status may be one of the following three values:

        ===== ================================
        Value Condition
        ===== ================================
        -1    no value yet (initial condition)
        0     success
        1     error
        ===== ================================

    A :mochiref:`Deferred` will be in the error state if one of the
    following conditions are met:

    1. The result given to callback or errback is "``instanceof
       Error``"
    2. The callback or errback threw while executing. If the thrown
       object is not ``instanceof Error``, it will be wrapped with
       :mochiref:`GenericError`.

    Otherwise, the :mochiref:`Deferred` will be in the success
    state. The state of the :mochiref:`Deferred` determines the next
    element in the callback sequence to run.

    When a callback or errback occurs with the example deferred chain,
    something equivalent to the following will happen (imagine that
    exceptions are caught and returned as-is)::

        // d.callback(result) or d.errback(result)
        if (!(result instanceof Error)) {
            result = myCallback(result);
        }
        if (result instanceof Error) {
            result = myErrback(result);
        }
        result = myBoth(result);
        if (result instanceof Error) {
            result = myErrback(result);
        } else {
            result = myCallback(result);
        }

    The result is then stored away in case another step is added to
    the callback sequence. Since the :mochiref:`Deferred` already has
    a value available, any new callbacks added will be called
    immediately.

    There are two other "advanced" details about this implementation
    that are useful:

    Callbacks are allowed to return :mochiref:`Deferred` instances, so
    you can build complicated sequences of events with (relative)
    ease.

    The creator of the :mochiref:`Deferred` may specify a
    canceller. The canceller is a function that will be called if
    :mochiref:`Deferred.prototype.cancel` is called before the
    :mochiref:`Deferred` fires. You can use this to allow an
    ``XMLHttpRequest`` to be cleanly cancelled, for example. Note that
    cancel will fire the :mochiref:`Deferred` with a
    :mochiref:`CancelledError` (unless your canceller throws or
    returns a different ``Error``), so errbacks should be prepared to
    handle that ``Error`` gracefully for cancellable
    :mochiref:`Deferred` instances.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`Deferred.prototype.addBoth(func)`:

    Add the same function as both a callback and an errback as the
    next element on the callback sequence. This is useful for code
    that you want to guarantee to run, e.g. a finalizer.

    If additional arguments are given, then ``func`` will be replaced
    with :mochiref:`MochiKit.Base.partial.apply(null,
    arguments)`. This differs from `Twisted`_, because the result of
    the callback or errback will be the *last* argument passed to
    ``func``.

    If ``func`` returns a :mochiref:`Deferred`, then it will be
    chained (its value or error will be passed to the next
    callback). Note that once the returned ``Deferred`` is chained, it
    can no longer accept new callbacks.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`Deferred.prototype.addCallback(func[, ...])`:

    Add a single callback to the end of the callback sequence.

    If additional arguments are given, then ``func`` will be replaced
    with :mochiref:`MochiKit.Base.partial.apply(null,
    arguments)`. This differs from `Twisted`_, because the result of
    the callback will be the *last* argument passed to ``func``.

    If ``func`` returns a :mochiref:`Deferred`, then it will be
    chained (its value or error will be passed to the next
    callback). Note that once the returned ``Deferred`` is chained, it
    can no longer accept new callbacks.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`Deferred.prototype.addCallbacks(callback, errback)`:

    Add separate callback and errback to the end of the callback
    sequence. Either callback or errback may be ``null``, but not
    both.

    If ``callback`` or ``errback`` returns a :mochiref:`Deferred`,
    then it will be chained (its value or error will be passed to the
    next callback). Note that once the returned ``Deferred`` is
    chained, it can no longer accept new callbacks.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`Deferred.prototype.addErrback(func)`:

    Add a single errback to the end of the callback sequence.

    If additional arguments are given, then ``func`` will be replaced
    with :mochiref:`MochiKit.Base.partial.apply(null,
    arguments)`. This differs from `Twisted`_, because the result of
    the errback will be the *last* argument passed to ``func``.

    If ``func`` returns a :mochiref:`Deferred`, then it will be
    chained (its value or error will be passed to the next
    callback). Note that once the returned ``Deferred`` is chained, it
    can no longer accept new callbacks.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`Deferred.prototype.callback([result])`:

    Begin the callback sequence with a non-``Error`` result. Result
    may be any value except for a :mochiref:`Deferred`.

    Either ``.callback`` or ``.errback`` should be called exactly once
    on a :mochiref:`Deferred`.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`Deferred.prototype.cancel()`:

    Cancels a :mochiref:`Deferred` that has not yet received a value,
    or is waiting on another :mochiref:`Deferred` as its value.

    If a canceller is defined, the canceller is called.  If the
    canceller did not return an ``Error``, or there was no canceller,
    then the errback chain is started with :mochiref:`CancelledError`.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`Deferred.prototype.errback([result])`:

    Begin the callback sequence with an error result.  Result may be
    any value except for a :mochiref:`Deferred`, but if ``!(result
    instanceof Error)``, it will be wrapped with
    :mochiref:`GenericError`.

    Either ``.callback`` or ``.errback`` should be called exactly once
    on a :mochidef:`Deferred`.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`DeferredLock()`:

    A lock for asynchronous systems.

    The ``locked`` property of a :mochiref:`DeferredLock` will be
    ``true`` if it locked, ``false`` otherwise. Do not change this
    property.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`DeferredLock.prototype.acquire()`:

    Attempt to acquire the lock. Returns a :mochiref:`Deferred` that
    fires on lock acquisition with the :mochiref:`DeferredLock` as the
    value.  If the lock is locked, then the :mochiref:`Deferred` goes
    into a waiting list.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`DeferredLock.prototype.release()`:

    Release the lock. If there is a waiting list, then the first
    :mochiref:`Deferred` in that waiting list will be called back.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`DeferredList(list, [fireOnOneCallback, fireOnOneErrback, consumeErrors, canceller])`:

    Combine a list of :mochiref:`Deferred` into one. Track the
    callbacks and return a list of (success, result) tuples, 'success'
    being a boolean indicating whether result is a normal result or an
    error.

    Once created, you have access to all :mochiref:`Deferred` methods,
    like addCallback, addErrback, addBoth. The behaviour can be
    changed by the following options:

    ``fireOnOneCallback``:
        Flag for launching the callback once the first Deferred of the
        list has returned.

    ``fireOnOneErrback``:
        Flag for calling the errback at the first error of a Deferred.

    ``consumeErrors``:
        Flag indicating that any errors raised in the Deferreds should
        be consumed by the DeferredList.

    Example::

        // We need to fetch data from 2 different urls
        var d1 = loadJSONDoc(url1);
        var d2 = loadJSONDoc(url2);
        var l1 = new DeferredList([d1, d2], false, false, true);
        l1.addCallback(function (resultList) {
            MochiKit.Base.map(function (result) {
                if (result[0]) {
                    alert("Data is here: " + result[1]);
                } else {
                    alert("Got an error: " + result[1]);
                }
            }, resultList);
        });

    *Availability*:
        Available in MochiKit 1.3.1+

Functions
---------

:mochidef:`callLater(seconds, func[, args...])`:

    Call ``func(args...)`` after at least ``seconds`` seconds have
    elapsed.  This is a convenience method for::

        func = partial.apply(extend(null, arguments, 1));
        return wait(seconds).addCallback(function (res) { return func() });

    Returns a cancellable :mochiref:`Deferred`.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`doXHR(url[, {option: value, ...}])`:

    Perform a customized ``XMLHttpRequest`` and wrap it with a
    :mochiref:`Deferred` that may be cancelled.

    Note that only ``200`` (OK), ``201`` (CREATED),
    ``204`` (NO CONTENT) and ``304`` (NOT MODIFIED) are considered
    success codes. All other status codes will
    result in an errback with an ``XMLHttpRequestError``.

    ``url``:
        The URL for this request.

    The following options are currently accepted:

    ``method``:
        The HTTP method. Default is ``'GET'``.

    ``sendContent``:
        The content to send (e.g. with POST). Default is no content.

    ``queryString``:
        If present it will be used to build a query string to append to
        the url using :mochiref:`MochiKit.Base.queryString`. Default is
        no query string.

    ``username``:
        The username for the request. Default is no username.

    ``password``:
        The password for the request. Default is no password.

    ``headers``:
        Additional headers to set in the request, either as an object
        such as ``{'Accept': 'text/xml'}`` or as an Array of 2-Arrays
        ``[['Accept', 'text/xml']]``. Default is no additional headers.

    ``mimeType``:
        An override mime type. The typical use of this is to pass
        'text/xml' to force XMLHttpRequest to attempt to parse responseXML.
        Default is no override.

    *returns*:
        :mochiref:`Deferred` that will callback with the
        ``XMLHttpRequest`` instance on success

    *Availability*:
        Available in MochiKit 1.4+.

:mochidef:`doSimpleXMLHttpRequest(url[, queryArguments...])`:

    Perform a simple ``XMLHttpRequest`` and wrap it with a
    :mochiref:`Deferred` that may be cancelled.

    Note that only ``200`` (OK), ``201`` (CREATED),
    ``204`` (NO CONTENT) and ``304`` (NOT MODIFIED) are considered
    success codes. All other status codes will
    result in an errback with an ``XMLHttpRequestError``.

    ``url``:
        The URL to GET

    ``queryArguments``:
        If this function is called with more than one argument, a
        ``"?"`` and the result of
        :mochiref:`MochiKit.Base.queryString` with the rest of the
        arguments are appended to the URL.

        For example, this will do a GET request to the URL
        ``http://example.com?bar=baz``::

            doSimpleXMLHttpRequest("http://example.com", {bar: "baz"});

    *returns*:
        :mochiref:`Deferred` that will callback with the
        ``XMLHttpRequest`` instance on success

    *Availability*:
        Available in MochiKit 1.3.1+. Support for 201 and 204 were added in
        MochiKit 1.4.

:mochidef:`evalJSONRequest(req)`:

    Evaluate a JSON [4]_ ``XMLHttpRequest``

    ``req``:
        The request whose ``.responseText`` property is to be
        evaluated

    *returns*:
        A JavaScript object

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`fail([result])`:

    Return a :mochiref:`Deferred` that has already had
    ``.errback(result)`` called.

    See ``succeed`` documentation for rationale.

    ``result``:
        The result to give to
        :mochiref:`Deferred.prototype.errback(result)`.

    *returns*:
        A ``new`` :mochiref:`Deferred()`

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`gatherResults(deferreds)`:

    A convenience function that returns a :mochiref:`DeferredList`
    from the given ``Array`` of :mochiref:`Deferred` instances that
    will callback with an ``Array`` of just results when they're
    available, or errback on the first array.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`getXMLHttpRequest()`:

    Return an ``XMLHttpRequest`` compliant object for the current
    platform.

    In order of preference:

    - ``new XMLHttpRequest()``
    - ``new ActiveXObject('Msxml2.XMLHTTP')``
    - ``new ActiveXObject('Microsoft.XMLHTTP')``
    - ``new ActiveXObject('Msxml2.XMLHTTP.4.0')``

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`maybeDeferred(func[, argument...])`:

    Call a ``func`` with the given arguments and ensure the result is
    a :mochiref:`Deferred`.

    ``func``:
        The function to call.

    *returns*:
        A new :mochiref:`Deferred` based on the call to ``func``. If
        ``func`` does not naturally return a :mochiref:`Deferred`, its
        result or error value will be wrapped by one.

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`loadJSONDoc(url[, queryArguments...])`:

    Do a simple ``XMLHttpRequest`` to a URL and get the response as a
    JSON [4]_ document.

    ``url``:
        The URL to GET

    ``queryArguments``:
        If this function is called with more than one argument, a
        ``"?"`` and the result of
        :mochiref:`MochiKit.Base.queryString` with the rest of the
        arguments are appended to the URL.

        For example, this will do a GET request to the URL
        ``http://example.com?bar=baz``::

            loadJSONDoc("http://example.com", {bar: "baz"});

    *returns*:
        :mochiref:`Deferred` that will callback with the evaluated
        JSON [4]_ response upon successful ``XMLHttpRequest``

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`sendXMLHttpRequest(req[, sendContent])`:

    Set an ``onreadystatechange`` handler on an ``XMLHttpRequest``
    object and send it off. Will return a cancellable
    :mochiref:`Deferred` that will callback on success.

    Note that only ``200`` (OK), ``201`` (CREATED),
    ``204`` (NO CONTENT) and ``304`` (NOT MODIFIED) are considered
    success codes. All other status codes will
    result in an errback with an ``XMLHttpRequestError``.

    ``req``:
        An preconfigured ``XMLHttpRequest`` object (open has been
        called).

    ``sendContent``:
        Optional string or DOM content to send over the
        ``XMLHttpRequest``.

    *returns*:
        :mochiref:`Deferred` that will callback with the
        ``XMLHttpRequest`` instance on success.

    *Availability*:
        Available in MochiKit 1.3.1+. Support for 201 and 204 were added in
        MochiKit 1.4.

:mochidef:`succeed([result])`:

    Return a :mochiref:`Deferred` that has already had
    ``.callback(result)`` called.

    This is useful when you're writing synchronous code to an
    asynchronous interface: i.e., some code is calling you expecting a
    :mochiref:`Deferred` result, but you don't actually need to do
    anything asynchronous. Just return ``succeed(theResult)``.

    See ``fail`` for a version of this function that uses a failing
    :mochiref:`Deferred` rather than a successful one.

    ``result``:
        The result to give to
        :mochiref:`Deferred.prototype.callback(result)`

    *returns*:
        a ``new`` :mochiref:`Deferred`

    *Availability*:
        Available in MochiKit 1.3.1+

:mochidef:`wait(seconds[, res])`:

    Return a new cancellable :mochiref:`Deferred` that will
    ``.callback(res)`` after at least ``seconds`` seconds have
    elapsed.

    *Availability*:
        Available in MochiKit 1.3.1+

See Also
========

.. [1] AJAX, Asynchronous JavaScript and XML: http://en.wikipedia.org/wiki/AJAX
.. [2] Twisted, an event-driven networking framework written in Python: http://twistedmatrix.com/
.. [3] Twisted Deferred Reference: http://twistedmatrix.com/projects/core/documentation/howto/defer.html
.. [4] JSON, JavaScript Object Notation: http://json.org/

Authors
=======

- Bob Ippolito <bob@redivi.com>

Copyright
=========

Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is
dual-licensed free software; you can redistribute it and/or modify it
under the terms of the `MIT License`_ or the `Academic Free License
v2.1`_.

.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php


text:
<Alloy>
	<Window class="container"  title = "Dettaglio Aspect">

		<TableView id="aspectsDetailTable"/>

	</Window>
</Alloy>


text:
class RegistrationPaymentController < ApplicationController
  before_action :get_event, :get_registration

  def get_registration
    @user_event = UserEvent.find(params[:user_event_id])
  end

  def new; end

  def create
    # Amount in cents
    # This needs to be via the user_event
    @amount = @user_event.total_owed * 100

    customer = Stripe::Customer.create(
      email: params[:stripeEmail],
      source: params[:stripeToken]
    )

    charge = Stripe::Charge.create(
      customer: customer.id,
      amount: @amount,
      description: "#{@user_event.user.name} payment for #{@event.name}",
      currency: 'usd'
    )

    logger.info "I have a charge #{charge}"
    logger.info "The charge ID is #{charge.id} and it was in the amount of #{charge.amount / 100}"

    @user_event.paid = true
    @user_event.payment_amount = charge.amount # Will be in cents, not dollars!
    @user_event.payment_id = charge.id
    @user_event.payment_date = Time.now
    @user_event.save!

    # send email!
    ReceiptMailer.event_registration_payment_email(@user_event).deliver

    redirect_to @event, notice: "Thank you! Payment has been received for #{@event.name}"
  rescue Stripe::CardError => e
    Rails.logger.error "'Payment error for #{@user_event.user.email}'s payment for #{@event.name}' error: #{e.message}"
    flash[:error] = e.message
    redirect_to event_user_event_path(@event, @user_event)
  end
end


text:
#include "csconverter.h"

#include <QCoreApplication>
#include <QWebFrame>

#include "utils.h"
#include "terminal.h"

static CSConverter *csconverter_instance = 0;

CSConverter *CSConverter::instance()
{
    if (!csconverter_instance)
        csconverter_instance = new CSConverter();

    return csconverter_instance;
}

CSConverter::CSConverter()
    : QObject(QCoreApplication::instance())
{
    m_webPage.mainFrame()->evaluateJavaScript(
        Utils::readResourceFileUtf8(":/coffee-script/extras/coffee-script.js"),
        QString("phantomjs://coffee-script/extras/coffee-script.js")
    );
    m_webPage.mainFrame()->addToJavaScriptWindowObject("converter", this);
}

QVariant CSConverter::convert(const QString &script)
{
    setProperty("source", script);
    QVariant result = m_webPage.mainFrame()->evaluateJavaScript(
        "try {" \
        "    [true, this.CoffeeScript.compile(converter.source)];" \
        "} catch (error) {" \
        "    [false, error.message];" \
        "}",
        QString()
    );
    return result;
}


text: Simple GUI for md5sum, made with Visual Basic