text:
-- This scripts for MySQL for Yet Another Forum http://sourceforge.net/projects/yafdotnet/
-- were created by vzrus from vz-team https://github.com/vzrus http://sourceforge.net/projects/yaf-datalayers/
-- They are distributed under terms of GPLv2 only licence as in http://www.fsf.org/licensing/licenses/gpl.html
-- Copyright vzrus(c) 2006-2012

DROP  PROCEDURE IF EXISTS {databaseSchema}.{objectQualifier}add_or_check_indexes;
--GO
CREATE PROCEDURE {databaseSchema}.{objectQualifier}add_or_check_indexes()
BEGIN

SET foreign_key_checks=0;

/*ADD  INDEXES AT FIRST INSTALL*/

IF EXISTS (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}BannedIP' AND S.TABLE_NAME='{objectQualifier}BannedIP' AND (S.COLUMN_NAME='BoardID' OR  S.COLUMN_NAME='Mask')) < 1 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}BannedIP
ADD UNIQUE INDEX  `IX_{databaseSchema}_{objectQualifier}BannedIP` (`BoardID`, `Mask`);

END IF;

 /* Thanks - it gives duplicate entry

IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Thanks_UserID' AND S.TABLE_NAME='{objectQualifier}Thanks' AND (S.COLUMN_NAME='ThanksToUserID' OR  S.COLUMN_NAME='ThanksFromUserID')) < 2 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Thanks
ADD UNIQUE INDEX  `IX_{databaseSchema}_{objectQualifier}Thanks_UserID` (`ThanksFromUserID`, `ThanksToUserID`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}ActiveAccess_UserID_Forum' AND S.TABLE_NAME='{objectQualifier}ActiveAccess' AND (S.COLUMN_NAME='UserID' OR  S.COLUMN_NAME='ForumID') LIMIT 1) THEN

ALTER TABLE {databaseSchema}.{objectQualifier}ActiveAccess
ADD UNIQUE INDEX  `IX_{databaseSchema}_{objectQualifier}ActiveAccess_UserID_Forum` (`UserID`,`ForumID`);

END IF;*/

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}MessageHistory_Edited_MessageID' AND S.TABLE_NAME='{objectQualifier}MessageHistory' AND (S.COLUMN_NAME='Edited' OR  S.COLUMN_NAME='MessageID') LIMIT 1) THEN

ALTER TABLE {databaseSchema}.{objectQualifier}MessageHistory
ADD INDEX  `IX_{databaseSchema}_{objectQualifier}MessageHistory_Edited_MessageID` (`Edited`);

END IF;

/* IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}ForumReadTracking_UserID_ForumID' AND S.TABLE_NAME='{objectQualifier}ForumReadTracking' AND (S.COLUMN_NAME='UserID' OR  S.COLUMN_NAME='ForumID') LIMIT 1) THEN

ALTER TABLE {databaseSchema}.{objectQualifier}ForumReadTracking
ADD  INDEX  `IX_{databaseSchema}_{objectQualifier}ForumReadTracking_UserID_ForumID` (`UserID`,`ForumID`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}TopicReadTracking_UserID_TopicID' AND S.TABLE_NAME='{objectQualifier}TopicReadTracking' AND (S.COLUMN_NAME='UserID' OR  S.COLUMN_NAME='TopicID') LIMIT 1) THEN

ALTER TABLE {databaseSchema}.{objectQualifier}TopicReadTracking
ADD  INDEX  `IX_{databaseSchema}_{objectQualifier}TopicReadTracking_UserID_TopicID` (`UserID`,`TopicID`);

END IF; */

-- Buddies

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Buddy_UserID' AND S.TABLE_NAME='{objectQualifier}Buddy' AND (S.COLUMN_NAME='ToUserID' OR  S.COLUMN_NAME='FromUserID')) THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Buddy
ADD UNIQUE INDEX  `IX_{databaseSchema}_{objectQualifier}Buddy_UserID` (`FromUserID`, `ToUserID`);

END IF;

/*CheckEmail*/

IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE INDEX_SCHEMA='{databaseSchema}' AND TABLE_NAME ='{objectQualifier}CheckEmail' AND S.COLUMN_NAME='Hash' AND INDEX_NAME='IX_{databaseSchema}_{objectQualifier}CheckEmail') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}CheckEmail
ADD
UNIQUE INDEX `IX_{databaseSchema}_{objectQualifier}CheckEmail` (`Hash`);

END IF;

/*Category*/

IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Category' AND S.TABLE_NAME='{objectQualifier}Category' AND (S.COLUMN_NAME='BoardID' OR  S.COLUMN_NAME='Name')) < 2 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Category
ADD UNIQUE INDEX `IX_{databaseSchema}_{objectQualifier}Category` (`BoardID`, `Name`);

END IF;

IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE INDEX_SCHEMA='{databaseSchema}' AND TABLE_NAME ='{objectQualifier}Category' AND S.COLUMN_NAME='BoardID' AND INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Category_BoardID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Category
ADD INDEX `IX_{databaseSchema}_{objectQualifier}Category_BoardID` (`BoardID`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Category_Name' AND S.TABLE_NAME='{objectQualifier}Category' AND S.COLUMN_NAME='Name') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Category
ADD INDEX `IX_{databaseSchema}_{objectQualifier}Category_Name` (`Name`);

END IF;

/*Forum*/

IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Forum' AND S.TABLE_NAME='{objectQualifier}Forum' AND (S.COLUMN_NAME='ParentID' OR  S.COLUMN_NAME='Name')) < 2 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Forum
ADD
UNIQUE INDEX `IX_{databaseSchema}_{objectQualifier}Forum` (`ParentID`, `Name`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Forum_CategoryID' AND S.TABLE_NAME='{objectQualifier}Forum' AND S.COLUMN_NAME='CategoryID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Forum
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Forum_CategoryID` (`CategoryID`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Forum_Flags' AND S.TABLE_NAME='{objectQualifier}Forum' AND S.COLUMN_NAME='Flags') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Forum
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Forum_Flags` (`Flags`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Forum_ParentID' AND S.TABLE_NAME='{objectQualifier}Forum' AND S.COLUMN_NAME='ParentID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Forum
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Forum_ParentID` (`ParentID`);

END IF;

/*ForumAccess*/

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}ForumAccess_ForumID' AND S.TABLE_NAME='{objectQualifier}ForumAccess' AND S.COLUMN_NAME='ForumID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}ForumAccess
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}ForumAccess_ForumID` (`ForumID`);

END IF;

/*Group*/

IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Group' AND S.TABLE_NAME='{objectQualifier}Group' AND (S.COLUMN_NAME='BoardID' OR  S.COLUMN_NAME='Name')) < 2 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Group
ADD
UNIQUE INDEX `IX_{databaseSchema}_{objectQualifier}Group` (`BoardID`, `Name`);

END IF;

/*Message*/

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Message_Flags' AND S.TABLE_NAME='{objectQualifier}Message' AND S.COLUMN_NAME='Flags') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Message
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Message_Flags` (`Flags`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Message_TopicID' AND S.TABLE_NAME='{objectQualifier}Message' AND S.COLUMN_NAME='TopicID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Message
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Message_TopicID` (`TopicID`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Message_UserID' AND S.TABLE_NAME='{objectQualifier}Message' AND S.COLUMN_NAME='UserID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Message
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Message_UserID` (`UserID`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Message_Posted_Desc' AND S.TABLE_NAME='{objectQualifier}Message' AND S.COLUMN_NAME='Posted') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Message
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Message_Posted_Desc` (`Posted` DESC);
END IF;

/*PollVote*/

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}PollVote_PollID' AND S.TABLE_NAME='{objectQualifier}PollVote' AND S.COLUMN_NAME='PollID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}PollVote
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}PollVote_PollID` (`PollID`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}PollVote_RemoteIP' AND S.TABLE_NAME='{objectQualifier}PollVote' AND S.COLUMN_NAME='RemoteIP') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}PollVote
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}PollVote_RemoteIP` (`RemoteIP`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}PollVote_UserID' AND S.TABLE_NAME='{objectQualifier}PollVote' AND S.COLUMN_NAME='UserID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}PollVote
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}PollVote_UserID` (`UserID`);

END IF;

/*Rank*/

IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Rank' AND S.TABLE_NAME='{objectQualifier}Rank' AND (S.COLUMN_NAME='BoardID' OR  S.COLUMN_NAME='Name')) < 2 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Rank
ADD
UNIQUE INDEX `IX_{databaseSchema}_{objectQualifier}Rank` (`BoardID`, `Name`);

END IF;

/*Registry*/

IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Registry_Name' AND S.TABLE_NAME='{objectQualifier}Registry' AND (S.COLUMN_NAME='BoardID' OR  S.COLUMN_NAME='Name')) < 2 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Registry
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Registry_Name` (`BoardID`, `Name`);

END IF;

/*Reputation*/
IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}ReputationVote_FU_TU' AND S.TABLE_NAME='{objectQualifier}ReputationVote' AND (S.COLUMN_NAME='ReputationFromUserID' OR  S.COLUMN_NAME='ReputationToUserID')) < 2 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}ReputationVote
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}ReputationVote_FU_TU` (`ReputationFromUserID`, `ReputationToUserID`);

END IF;

/*Smiley*/

IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Smiley' AND S.TABLE_NAME='{objectQualifier}Smiley' AND (S.COLUMN_NAME='BoardID' OR  S.COLUMN_NAME='Code')) < 2 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Smiley
ADD
UNIQUE INDEX `IX_{databaseSchema}_{objectQualifier}Smiley` (`BoardID`, `Code`);

END IF;

/*Topic*/

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Topic_Flags' AND S.TABLE_NAME='{objectQualifier}Topic' AND S.COLUMN_NAME='Flags') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Topic
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Topic_Flags` (`Flags`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Topic_ForumID' AND S.TABLE_NAME='{objectQualifier}Topic' AND S.COLUMN_NAME='ForumID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Topic
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Topic_ForumID` (`ForumID`);

END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Topic_UserID' AND S.TABLE_NAME='{objectQualifier}Topic' AND S.COLUMN_NAME='UserID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}Topic
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Topic_UserID` (`UserID`);

END IF;

/* User

-- too long for 5.5
IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}User' AND S.TABLE_NAME='{objectQualifier}User' AND (S.COLUMN_NAME='BoardID' OR  S.COLUMN_NAME='Name')) < 2 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}User
ADD
UNIQUE INDEX `IX_{databaseSchema}_{objectQualifier}User` (`BoardID`, `Name`);

END IF;
*/

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}User_Flags' AND S.TABLE_NAME='{objectQualifier}User'
AND S.COLUMN_NAME='Flags') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}User
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}User_Flags` (`Flags`);

END IF;

/* too long for 5.5
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}User_Name' AND S.TABLE_NAME='{objectQualifier}User'
AND S.COLUMN_NAME='Name') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}User
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}User_Name` (`Name`);

END IF; */

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.TABLE_NAME='{objectQualifier}User' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}User_ProviderUserKey' AND S.COLUMN_NAME='ProviderUserKey') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}User
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}User_ProviderUserKey` (`ProviderUserKey`);

END IF;

/*UserGroup*/

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}UserGroup_UserID' AND S.TABLE_NAME='{objectQualifier}UserGroup' AND S.COLUMN_NAME='UserID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}UserGroup
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}UserGroup_UserID` (`UserID`);

END IF;

/*UserPMessage*/

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}UserPMessage_UserID' AND S.TABLE_NAME='{objectQualifier}UserPMessage' AND S.COLUMN_NAME='UserID') THEN

ALTER TABLE {databaseSchema}.{objectQualifier}UserPMessage
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}UserPMessage_UserID` (`UserID`);

END IF;

/*WatchForum*/

IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}WatchForum' AND S.TABLE_NAME='{objectQualifier}WatchForum' AND (S.COLUMN_NAME='ForumID' OR  S.COLUMN_NAME='UserID'))< 2 THEN

ALTER TABLE {databaseSchema}.{objectQualifier}WatchForum
ADD
UNIQUE INDEX `IX_{databaseSchema}_{objectQualifier}WatchForum` (`ForumID`, `UserID`);

END IF;

/*WatchTopic*/

IF (SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}WatchTopic'  AND S.TABLE_NAME='{objectQualifier}WatchTopic' AND (S.COLUMN_NAME='TopicID' OR  S.COLUMN_NAME='UserID')) < 2 THEN
ALTER TABLE {databaseSchema}.{objectQualifier}WatchTopic
ADD
UNIQUE INDEX `IX_{databaseSchema}_{objectQualifier}WatchTopic` (`TopicID`, `UserID`);
END IF;

-- {databaseSchema}.{objectQualifier}Thanks

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Thanks_MessageID'  AND S.TABLE_NAME='{objectQualifier}Thanks' AND S.COLUMN_NAME='MessageID')  THEN
ALTER TABLE {databaseSchema}.{objectQualifier}Thanks
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Thanks_MessageID` (`MessageID`);
END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Thanks_ThanksFromUserID'  AND S.TABLE_NAME='{objectQualifier}Thanks' AND S.COLUMN_NAME='ThanksFromUserID')  THEN
ALTER TABLE {databaseSchema}.{objectQualifier}Thanks
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Thanks_ThanksFromUserID` (`ThanksFromUserID`);
END IF;

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS S WHERE S.TABLE_SCHEMA='{databaseSchema}' AND S.INDEX_NAME='IX_{databaseSchema}_{objectQualifier}Thanks_ThanksToUserID'  AND S.TABLE_NAME='{objectQualifier}Thanks' AND S.COLUMN_NAME='ThanksToUserID')  THEN
ALTER TABLE {databaseSchema}.{objectQualifier}Thanks
ADD
INDEX `IX_{databaseSchema}_{objectQualifier}Thanks_ThanksToUserID` (`ThanksToUserID`);
END IF;

SET foreign_key_checks=1;
END;
--GO

CALL {databaseSchema}.{objectQualifier}add_or_check_indexes();
--GO


text:
layout: post
title: Déboguer vos applications dockerisées avec PhpStorm
excerpt: Aujourd'hui je vais vous expliquer comment lancer vos tests unitaires et les déboguer avec PhpStorm, le tout sans avoir besoin d'installer php, phpunit, ou Xdebug sur votre machine...
authors:
- rmasclef
lang: fr
permalink: /fr/debug-run-phpunit-tests-using-docker-remote-interpreters-with-phpstorm/
categories:
    - php
    - docker
tags:
    - PhpStorm
    - Docker
    - Tests Unitaires
    - Xdebug

cover: /img/covers/StockSnap_X7ZB66F677.jpg
---

Aujourd'hui je vais vous expliquer comment lancer vos tests unitaires et les déboguer avec PhpStorm, le tout sans avoir besoin d'installer php, phpunit, ou Xdebug sur votre machine...

## Pré-requis
### Sur votre machine locale

- [PhpStorm](https://www.jetbrains.com/phpstorm/)  >= 2016.3
- [Docker CE](https://docs.docker.com/install/linux/docker-ce/ubuntu/)
- [Docker Compose](https://docs.docker.com/compose/install/)

## PhpStorm plugins
Admettons qu'aucun plugin jetbrain ne soit actif sur votre Phpstorm. Voici la liste des plugins que vous allez devoir installer et que nous allons configurer :

- [Docker](https://www.jetbrains.com/help/idea/docker.html)
- PHPDocker
- PHP remote interpreter

**C'est tout**, vous n'avez pas besoin d'installer `php`, `phpunit`, `php-xdebug`... :D

## Un exemple à réutiliser

Afin de rester simple, je me suis permis de créer un petit projet qui regroupe les différentes configurations que je vais vous présenter dans un instant.

Je vous invite donc à cloner le [projet](https://github.com/rmasclef/docker-remote-php-debuging) afin de pouvoir vous entraîner.

Une fois le repo cloné, vous pouvez lancer un `docker-compose up -d` suivi par un `docker-compose exec test_app composer install --prefer-dist`.

Vous aurez alors accès à un container nommé `test-app` faisant tourner un `php-fpm-7.2` avec l'extension `xdebug` ainsi que `phpunit`.

## Configuration des plugins
### Docker
- Ouvrez la fenêtre des paramètres phpStorm (`ctrl`+`alt`+`s` ou **File/Settings/...**)
- Allez dans l'onglet **Build, execution, deployment**
- Cliquez sur **Docker**

> Note : Vous pouvez également effectuer un `ctrl`+`Shift`+`a` et taper **Docker** dans le champ de recherche comme ceci :
>
> ![Quick Docker settings access]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/quick-docker-settings-access.png)

Nous arrivons alors sur la page suivante, qui va nous permettre d'ajouter notre interpréteur `docker` :

![Docker plugin settings page]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/docker-plugin-settings-page.png)

- Cliquez sur ![Plus phpstorm button]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/plus-phpstorm-button.png) pour ajouter une nouvelle configuration Docker et indiquer à phpStorm comment se connecter au démon Docker.
> Le message "Connection successful" doit apparaître.

![Docker configuration]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/docker-configuration.png)

- Allons maintenant dans **Tools** pour fournir à phpStorm les interpréteurs de `docker` et `docker-compose`

![Docker interpreters configuration]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/docker-interpreters-configuration.png)

Voilà tout pour le plugin Docker. Si vous souhaitez en savoir plus sur son utilisation, je vous invite à visiter [cette page](https://www.jetbrains.com/help/idea/docker.html).

### Remote interpreter
L'objectif ici est de configurer l'interpréteur `php` que nous allons utiliser pour lancer un script de notre projet.

Avant d'attaquer la configuration, attardons-nous quelques instants sur les fichiers présents dans ce projet :

**Dockerfile**
```yml
FROM php:7.2-fpm

RUN apt-get update && apt-get install -y \
    zip

RUN pecl install xdebug \
    && docker-php-ext-enable xdebug

# Install composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
RUN mkdir /var/composer
ENV COMPOSER_HOME /var/composer
ENV COMPOSER_ALLOW_SUPERUSER 1

# Those lines are important for remote interpreter configuration
RUN mkdir -p /var/www/TEST_APP
WORKDIR /var/www/TEST_APP

# Install PHP Xdebug configuration, (see https://blog.eleven-labs.com/fr/debugger-avec-xdebug/)
ADD xdebug.ini /etc/php/conf.d/

CMD ["php-fpm"]
```
> Note : J'ai utilisé l'image php de base, et non une alpine, pour des raisons de simplification du Dockerfile.

Comme vous pouvez le voir, j'ai simplement ajouté `xdebug` , `zip` et `composer` (inutile d'installer `git` étant donné que nous utilisons l'option `--prefer-dist` de composer 🙂).

**docker-compose**
```yml
version: '3'
services:
  test_app:
    build:
      context: ./
    dockerfile: Dockerfile
    volumes:
      - "./:/var/www/TEST_APP:cached"
      - "~/.composer:/var/composer:cached"
    environment:
      # Keep attention to that env variable
      PHP_IDE_CONFIG: serverName=test-app
```
Ici, on notera la présence de la variable d'environnement `PHP_IDE_CONFIG`. Nous allons utiliser la valeur de `serverName` pour indiquer à phpStorm le nom du serveur sur lequel il va écouter les connexions.

Pour ce faire, rendez-vous dans **File/Settings.../Languages & Framework/PHP***
![PHPStorm Settings PHP]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-settings-php.png)

- Cliquez sur ![PHPStorm Browse button]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-browse-button.png) à droite de **CLI Interpreter**
- Dans **Remote** sélectionnez **Docker** (le serveur que nous avons créé précédemment est automatiquement sélectionné)
- Dans **Image name** sélectionnez **dockerremotephpdebugingexample_test_app:latest**

![PHPStorm Settings CLI interpreter]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-settings-CLI-interpreter.png)

PhpStorm va alors automatiquement récupérer l'image si elle n'est pas déjà présente, et va détecter la version de `php` présente sur le container ainsi que ses extensions.

![PHPStorm Settings PHP]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-settings-php.png)
  - sélectionnez l'interpréteur que nous venons de créer...

PhpStorm va de nouveau détecter (ou au moins essayer...) le mapping entre le chemin du projet en local, et celui sur le container. Je dis "essayer" car vous devrez peut-être configurer manuellement ce mapping de la manière suivante :
- Dans la partie `Docker container` cliquez sur les ![PHPStorm browse buttons]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-browse-button.png)

Vous pouvez alors modifier le mapping entre le volume docker et le chemin en local (ici `/home/rmasclef/Documents/projects/ElevenLabs/DockerRemotePhpDebugingExample` doit être bindé avec `var/www/TEST_APP` étant donné que nous avons effectué ce binding dans le [Dockerfile](https://github.com/rmasclef/docker-remote-php-debuging/blob/master/docker-compose.yml#L8).

![PHPStorm]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm.png)

### PHPUnit
Ici, nous allons faire en sorte de pouvoir lancer nos tests unitaires sur le container en utilisant une simple combinaison de touches :)

- Rendez-vous dans **Files\Settings...\Languages & framework\PHP\Test frameworks**.
- Cliquez sur ![Plus phpstorm button]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/plus-phpstorm-button.png) puis **phpUnit by remote interpreter**.
- Sélectionnez l'interpréteur php que nous avons créé précédemment.

![PHPStorm PHPUnit by remote interpreter]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-PHPUnit-by-remote-interpreter.png)

- Ajoutez `/var/www/TEST_APP/vendor/autoload.php` en tant que path vers le fichier d'autoload composer

![PHPStorm PHPUnit interpreter]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-PHPUnit-interpreter.png)

PhpStorm doit alors détecter la version de phpunit installée sur le container.
> Note : Vous pouvez également ajouter un fichier de configuration phpunit (ici `/var/www/TEST_APP/phpunit.xml.dist`).

**À présent, vous pouvez lancer les tests unitaires sur votre container via phpStorm**

### PHP Remote debugger
![PHPStorm menu tests]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-menu-tests.png)

- Cliquez sur ![Plus phpstorm button]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/plus-phpstorm-button.png) puis **PHP remote debug**
- Donnez un nom à cette configuration
- Cliquez sur ![PHPStorm browse buttons]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-browse-button.png) afin d'ajouter un serveur de débogage

![PHPStorm Settings Server]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-settings-server.png)

**/!\ Ici, il faut mettre en nom de serveur le nom que nous avons mis dans la variable d'environnement `PHP_IDE_CONFIG`**

Notez également qu'il faut ajouter le mapping entre notre environnement local et le container.

Sélectionnez le serveur précédemment créé et ajoutez l'IDE key qui est renseignée dans le fichier de configuration [xdebug.ini](https://github.com/rmasclef/docker-remote-php-debuging/blob/master/xdebug.ini#L5).

![PHPStorm Remote debug configuration]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-remote-debug-configuration.png)

Félicitations ! Vous êtes maintenant capable de déboguer votre application sans avoir php, phpunit, Xdebug ou tout autre librairie sur votre environnement local.

## Lancement des tests unitaires
Nous pouvons à présent lancer notre suite de tests unitaires sur notre container. Vous pouvez effectuer un clic droit sur le dossier `tests` puis cliquer sur `run tests` (ou `ctrl`+`Shift`+`F10`).

> Vous pouvez également lancer les tests d'une seule classe ou encore lancer un test d'une classe en particulier.
![PHPStorm test class]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-test-class.png)
> Tips: Dans une classe de tests unitaires, si vous placez votre curseur à l'intérieur d'une fonction et que vous effectuez un `ctrl`+`Shift`+`F10`, alors seul ce test sera lancé.
>
> À l'inverse, si vous placez votre curseur à l'extérieur des fonctions et que vous effectuez un `ctrl`+`Shift`+`F10`, alors tous les tests de la classe seront lancés.

## Déboguer

Ajoutons un point d'arrêt dans notre code :

![PHPStorm IDE Break point]({{site.baseurl}}/assets/2018-04-26-deboguer-vos-applications-dockerisees-avec-phpstorm/PHPStorm-IDE-break-point.png)

Cette fonction est testée unitairement, nous allons donc pouvoir la déboguer...
- Effectuez un clic droit sur le test unitaire que vous souhaitez déboguer puis cliquez sur **Debug 'testGetContent'**. Le débogueur se lance alors et arrive au point d'arrêt ajouté dans notre classe concrète :D
> De la même manière, vous pouvez également déboguer des scripts tels que des commandes symfony.

## Conclusion
C'est terminé, vous êtes maintenant capable de configurer PHPStorm afin qu'il lance vos tests unitaires et/ou une session de débogage à travers un container Docker.

N'hésitez pas à commenter ce post pour toute question/remarque, demande d'ajout, ou éventuel point de bloquage rencontré lors de la configuration de votre environement, nous serons ravis de pouvoir échanger avec vous !

## Sources
[configuring-remote-python-interpreters.html](https://www.jetbrains.com/help/phpstorm/configuring-remote-python-interpreters.html)
[docker-remote-interpreters](https://blog.jetbrains.com/phpstorm/2016/11/docker-remote-interpreters/)

redpajama_set_name: RedPajamaGithub


text:
package net.blay09.mods.chattweaks.chat.badges;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import net.blay09.mods.chattweaks.image.renderable.IChatRenderable;
import net.blay09.mods.chattweaks.image.ITooltipProvider;
import net.minecraft.util.text.TextFormatting;

import java.util.List;
import java.util.Set;

public class NameBadge implements ITooltipProvider {

	private final int id;
	private final String name;
	private final IChatRenderable image;
	private final List<String> tooltip = Lists.newArrayList();
	private final Set<String> players = Sets.newHashSet();

	public NameBadge(int id, String name, IChatRenderable image) {
		this.id = id;
		this.name = name;
		this.image = image;
		tooltip.add(TextFormatting.YELLOW + name);
	}

	@Override
	public List<String> getTooltip() {
		return tooltip;
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void addPlayer(String name) {
		players.add(name);
	}

	public IChatRenderable getImage() {
		return image;
	}
}


text:
<?php

namespace Liber\AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * PublisherRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PublisherRepository extends EntityRepository
{
}


text:
export LowRankIntegralOperator

immutable LowRankIntegralOperator{S<:Space,M<:Space,T} <: AbstractLowRankOperator{T}
    U::Vector{Fun{S,T}}
    V::Vector{Fun{M,T}}

    function LowRankIntegralOperator(U::Vector{Fun{S,T}},V::Vector{Fun{M,T}})
        @assert length(U) == length(V)
        @assert length(U) > 0
        ds=space(first(V))
        for k=2:length(V)
            @assert space(V[k])==ds
        end
        rs=space(first(U))
        for k=2:length(U)
            @assert space(U[k])==rs
        end
        new(U,V)
    end
end

LowRankIntegralOperator{S,M,T}(U::Vector{Fun{S,T}},V::Vector{Fun{M,T}})=LowRankIntegralOperator{S,M,T}(U,V)

LowRankIntegralOperator{S,M,T1,T2}(U::Vector{Fun{S,T1}},V::Vector{Fun{M,T2}})=LowRankIntegralOperator(convert(Vector{Fun{S,promote_type(T1,T2)}},U),convert(Vector{Fun{M,promote_type(T1,T2)}},V))

LowRankIntegralOperator(A::Fun,B::Fun)=LowRankIntegralOperator([A],[B])

Base.promote_rule{S,M,T,S1,M1,T1}(::Type{LowRankIntegralOperator{S,M,T}},::Type{LowRankIntegralOperator{S1,M1,T1}})=LowRankIntegralOperator{promote_type(S,S1),promote_type(M,M1),promote_type(T,T1)}
Base.rank(L::AbstractLowRankOperator)=length(L.U)

domainspace(L::LowRankIntegralOperator)=space(first(L.V))
rangespace(L::LowRankIntegralOperator)=space(first(L.U))
promoterangespace(L::LowRankIntegralOperator,sp::Space)=LowRankIntegralOperator(map(u->Fun(u,sp),L.U),L.V)

+(L::LowRankIntegralOperator)=LowRankIntegralOperator(+L.U,L.V)
-(L::LowRankIntegralOperator)=LowRankIntegralOperator(-L.U,L.V)

*(L::LowRankIntegralOperator,f::Fun)=sum(map((u,v)->u*dot(v,f),L.U,L.V))

+(A::LowRankIntegralOperator,B::LowRankIntegralOperator)=LowRankIntegralOperator([A.U;B.U],[A.V;B.V])
-(A::LowRankIntegralOperator,B::LowRankIntegralOperator)=LowRankIntegralOperator([A.U;-B.U],[A.V;B.V])


text:
<?php defined('SYSPATH') or die('No direct script access.');
session_start();

class Controller_Cliente extends Controller {

	public function action_index(){
		if (!isset($_SESSION['validado'])){
			throw new HTTP_Exception_403;
			exit;
		}
		else{
		$deputy = $_SESSION['deputy'];
		$estado= ($deputy->allowed('Cliente/'));
		if($estado){
			$parametro = array();
			$model_cliente = new Model_Cliente();
			$resultado = $model_cliente->listaCliente();
			$parametro['datos'] = $resultado;

			$vista = Kodwoo_View::factory('/Cliente/list', $parametro);
			$this->response->body($vista);
		}

		else{
			throw new HTTP_Exception_403;
			exit;

		}

	}

	}

	public function action_changeEstado()
	{
		if (!isset($_SESSION['validado'])){
			throw new HTTP_Exception_403;
			exit;
		}
		else{
		$deputy = $_SESSION['deputy'];
		$estado= ($deputy->allowed('Cliente/*'));
		if($estado){
			try{
			$key = isset($_POST['key'])?strip_tags($_POST['key']):'';
			$estado = isset($_POST['estado'])?strip_tags($_POST['estado']):'';
			$model_cliente = new Model_Cliente();
			$model_cliente->changeEstado($key , $estado);
			echo "ok";
			}catch (Exception $e) {
	   			echo "err";

			}
		}

		else{
			throw new HTTP_Exception_403;
			exit;

		}
		}

	}

	public function action_create(){
		if (!isset($_SESSION['validado'])){
			throw new HTTP_Exception_403;
			exit;
		}
		else{
		$deputy = $_SESSION['deputy'];
		$estado= ($deputy->allowed('Cliente/*'));
		if($estado){
			$parametro = array();
			$vista = Kodwoo_View::factory('/Cliente/create', $parametro);
			$this->response->body($vista);
		}

		else{
			throw new HTTP_Exception_403;
			exit;

		}

		}
	}

	public function action_new(){
		if (!isset($_SESSION['validado'])){
			throw new HTTP_Exception_403;
			exit;
		}
		else{
		$deputy = $_SESSION['deputy'];
		$estado= ($deputy->allowed('Cliente/*'));
		if($estado){
			try{
			$id_cliente = isset($_POST['id_cliente'])?strip_tags($_POST['id_cliente']):'';
			$rut = isset($_POST['rut'])?strip_tags($_POST['rut']):'';
			$razon_social = isset($_POST['razon_social'])?strip_tags($_POST['razon_social']):'';
			$direccion = isset($_POST['direccion'])?strip_tags($_POST['direccion']):'';
			$comuna = isset($_POST['comuna'])?strip_tags($_POST['comuna']):'';
			$email = isset($_POST['email'])?strip_tags($_POST['email']):'';
			$telefono = isset($_POST['telefono'])?strip_tags($_POST['telefono']):'';
			$estado = isset($_POST['estado'])?strip_tags($_POST['estado']):'';
			$model_cliente = new Model_Cliente();
			$result= $model_cliente->validarCliente($id_cliente);

			if(!isset($result[0])){

	   			$model_cliente->newCliente($id_cliente , $rut, $razon_social, $direccion, $comuna, $email,$telefono,$estado);
	   			echo '
El cliente fue registrado con exito
';
	   		}
	   		else {
	   			echo '
El cliente ya se encuentra registrado en el sistema
';
	   		}
	   		}catch (Exception $e) {
	   			echo '
Error en el sistema ',$e->getMessage(),'
';

			}
		}

		else{
			throw new HTTP_Exception_403;
			exit;

		}
		}
	}

	public function action_editCliente()
	{
		if (!isset($_SESSION['validado'])){
			throw new HTTP_Exception_403;
			exit;
		}
		else{
		$deputy = $_SESSION['deputy'];
		$estado= ($deputy->allowed('Cliente/*'));
		if($estado){
			$id_cliente = isset($_GET['Id_cliente'])?strip_tags($_GET['Id_cliente']):'';
			$model_cliente = new Model_Cliente();
			$datos = $model_cliente->editCliente($id_cliente);
			$parametro = array();
			$parametro['datos'] = $datos;
			$vista = Kodwoo_View::factory('/Cliente/edit', $parametro);
			$this->response->body($vista);
		}

		else{
			throw new HTTP_Exception_403;
			exit;

		}

		}
	}

	public function action_updateCliente()
	{
		if (!isset($_SESSION['validado'])){
			throw new HTTP_Exception_403;
			exit;
		}
		else{
		$deputy = $_SESSION['deputy'];
		$estado= ($deputy->allowed('Cliente/'));
		if($estado){
			try{
			$id_cliente = isset($_POST['id_cliente'])?strip_tags($_POST['id_cliente']):'';
			$rut = isset($_POST['rut'])?strip_tags($_POST['rut']):'';
			$razon_social = isset($_POST['razon_social'])?strip_tags($_POST['razon_social']):'';
			$direccion = isset($_POST['direccion'])?strip_tags($_POST['direccion']):'';
			$comuna = isset($_POST['comuna'])?strip_tags($_POST['comuna']):'';
			$email = isset($_POST['email'])?strip_tags($_POST['email']):'';
			$telefono = isset($_POST['telefono'])?strip_tags($_POST['telefono']):'';
			$estado = isset($_POST['estado'])?strip_tags($_POST['estado']):'';
			$model_cliente = new Model_Cliente();
			$result= $model_cliente->validarCliente($id_cliente);

			if(isset($result[0])){

	   			$model_cliente->updateCliente($id_cliente , $rut, $razon_social, $direccion, $comuna, $email,$telefono,$estado);
	   			echo '
El cliente fue actualizado con exito
';
	   		}
	   		else {
	   			echo '
El cliente no  se encuentra registrado en el sistema
';
	   		}
	   		}catch (Exception $e) {
	   			echo '
Error en el sistema ',$e->getMessage(),'
';

			}
		}

		else{
			throw new HTTP_Exception_403;
			exit;

		}
		}
	}
}


text:
package com.google.enterprise.cloudsearch.sdk.identity;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.Directory.Users;
import com.google.api.services.admin.directory.Directory.Users.Get;
import com.google.api.services.admin.directory.Directory.Users.Update;
import com.google.api.services.admin.directory.model.User;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.RateLimiter;
import com.google.enterprise.cloudsearch.sdk.AsyncRequest;
import com.google.enterprise.cloudsearch.sdk.BaseApiService;
import com.google.enterprise.cloudsearch.sdk.BatchPolicy;
import com.google.enterprise.cloudsearch.sdk.BatchRequestService;
import com.google.enterprise.cloudsearch.sdk.CredentialFactory;
import com.google.enterprise.cloudsearch.sdk.GoogleProxy;
import com.google.enterprise.cloudsearch.sdk.PaginationIterable;
import com.google.enterprise.cloudsearch.sdk.RetryPolicy;
import com.google.enterprise.cloudsearch.sdk.StatsManager;
import com.google.enterprise.cloudsearch.sdk.StatsManager.OperationStats;
import com.google.enterprise.cloudsearch.sdk.config.Configuration;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;

public class UsersServiceImpl extends BaseApiService<Directory> implements UsersService {

  private static final Set<String> APPLICATION_SCOPES =
      ImmutableSet.of("https://www.googleapis.com/auth/admin.directory.user");
  private static final OperationStats USER_SERVICE_STATS =
      StatsManager.getComponent("UsersService");
  private static final String CUSTOMER_ID_CONFIG = "api.customerId";
  private static final RateLimiter API_RATE_LIMITER = RateLimiter.create(10);

  private final BatchRequestService batchService;
  private final String customerId;

  private UsersServiceImpl(Builder builder) {
    super(builder);
    this.batchService = checkNotNull(builder.batchService);
    checkArgument(
        !Strings.isNullOrEmpty(builder.customerId), "customerId can not be null or empty");
    this.customerId = builder.customerId;
  }

  /** Creates an instance of {@link UsersServiceImpl} from connector configuration. */
  public static UsersServiceImpl fromConfiguration(CredentialFactory credentialFactory)
      throws GeneralSecurityException, IOException {
    checkState(Configuration.isInitialized(), "configuration not initialized");
    return new UsersServiceImpl.Builder()
        .setCredentialFactory(credentialFactory)
        .setBatchPolicy(BatchPolicy.fromConfiguration())
        .setRetryPolicy(RetryPolicy.fromConfiguration())
        .setCustomer(Configuration.getString(CUSTOMER_ID_CONFIG, null).get())
        .setProxy(GoogleProxy.fromConfiguration())
        .build();
  }

  /** Builder for creating an instance of {@link UsersServiceImpl} */
  public static class Builder extends BaseApiService.AbstractBuilder<Builder, Directory> {

    private BatchRequestService batchService;
    private String customerId;

    /** Returns this {@link UsersServiceImpl.Builder} instance */
    @Override
    public Builder getThis() {
      return this;
    }

    /**
     * Sets {@link BatchRequestService} to be used for request batching.
     *
     * @param batchService to be used for request batching
     */
    public Builder setBatchRequestService(BatchRequestService batchService) {
      this.batchService = batchService;
      return this;
    }

    /**
     * Sets customer ID to be used for syncing user identities.
     *
     * @param customerId to be used for syncing user identities.
     */
    public Builder setCustomer(String customerId) {
      this.customerId = customerId;
      return this;
    }

    /** Returns API scopes to be use for making Google Admin SDK API requests. */
    @Override
    public Set<String> getApiScopes() {
      return APPLICATION_SCOPES;
    }

    /**
     * Gets an instance of {@link com.google.api.services.admin.directory.Directory.Builder} for
     * creating an instance of {@link Directory} to make Google Admin SDK API requests.
     */
    @Override
    public Directory.Builder getServiceBuilder(
        HttpTransport transport,
        JsonFactory jsonFactory,
        HttpRequestInitializer requestInitializer) {
      return new Directory.Builder(transport, jsonFactory, requestInitializer);
    }

    /** Builds an instance of {@link UsersServiceImpl} */
    @Override
    public UsersServiceImpl build() throws GeneralSecurityException, IOException {
      GoogleCredential credentials = setupServiceAndCredentials();
      if (batchService == null) {
        batchService =
            new BatchRequestService.Builder(service)
                .setBatchPolicy(batchPolicy)
                .setRetryPolicy(retryPolicy)
                .setGoogleCredential(credentials)
                .build();
      }

      return new UsersServiceImpl(this);
    }
  }

  /** Gets {@link User} from Google Admin SDK API. */
  @Override
  public ListenableFuture<User> getUserMapping(String userId) throws IOException {
    Get get = service.users().get(userId).setProjection("full");
    return batchRequest(get, retryPolicy, batchService);
  }

  /** Updates {@link User}'s custom schema attributes using Google Admin SDK API. */
  @Override
  public ListenableFuture<User> updateUserMapping(
      String userId, String schemaName, String attributeName, Optional<String> value)
      throws IOException {
    Update update =
        service
            .users()
            .update(
                userId,
                new User()
                    .setCustomSchemas(
                        Collections.singletonMap(
                            schemaName,
                            Collections.singletonMap(attributeName, value.orElse("")))));
    return batchRequest(update, retryPolicy, batchService);
  }

  /** Lists all {@link User}s using Google Admin SDK API. */
  @Override
  public Iterable<User> listUsers(String schemaName) throws IOException {
    return new UsersIterable(schemaName);
  }

  @Override
  protected void startUp() throws Exception {
    batchService.startAsync().awaitRunning();
  }

  @Override
  protected void shutDown() throws Exception {
    batchService.stopAsync().awaitTerminated();
  }

  private class UsersIterable extends PaginationIterable<User, String> {

    private final String schemaName;

    UsersIterable(String schemaName) {
      super(Optional.empty());
      this.schemaName = schemaName;
    }

    @Override
    public Page<User, String> getPage(Optional<String> nextPage) throws IOException {
      Users.List list =
          service
              .users()
              .list()
              .setCustomer(customerId)
              .setCustomFieldMask(schemaName)
              .setProjection("custom")
              .setPageToken(nextPage.orElse(null));
      API_RATE_LIMITER.acquire();
      com.google.api.services.admin.directory.model.Users users = list.execute();
      List<User> toReturn = users.getUsers();
      return new Page<>(
          toReturn == null ? Collections.emptyList() : toReturn,
          Optional.ofNullable(users.getNextPageToken()));
    }
  }

  private static <T> ListenableFuture<T> batchRequest(
      AbstractGoogleJsonClientRequest<T> requestToExecute,
      RetryPolicy retryPolicy,
      BatchRequestService batchService)
      throws IOException {
    AsyncRequest<T> userRequest =
        new AsyncRequest<>(requestToExecute, retryPolicy, USER_SERVICE_STATS);
    try {
      API_RATE_LIMITER.acquire();
      batchService.add(userRequest);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new IOException("Interrupted while batching request", e);
    }
    return userRequest.getFuture();
  }
}


text:
.. -*- coding: utf-8 -*-

.. role:: raw-html(raw)
   :format: html

Writing Specter Tests
######################

Naming Rules
~~~~~~~~~~~~~~~~~
Most frameworks require you to start your test with a given prefix such as :raw-html:`"test_"`. Specter does not impose any prefix rules on test functions. We believe that it is better to give the developer more flexibility in naming so that their test names better describe what they are actually testing. However, while Specter does have a couple rules that should be followed.

* All helper functions should start with an underscore (_). Just as Python treats a single underscore as "protected", so does Specter.
* "before_each", "after_each", "before_all", and "after_all" are reserved for setup functions on your test suites (Specs).
* Currently, we also treat "serialize" and "execute" as reserved names as well.

Writing Tests
~~~~~~~~~~~~~~
Writing a test in Specter is simple.

1. Create a class which extends Spec
2. Create a function in that class that calls expect or require once

:raw-html:`<i>Example:</i>`

.. code-block:: python

    from specter import Spec, expect

    class SampleSpec(Spec):
        """Docstring describing the specification"""
        def it_can_create_an_object(self):
            """ Test docstring"""
            expect('something').to.equal('something')

Test Setup / Teardown
~~~~~~~~~~~~~~~~~~~~~~
:raw-html:`<i>Example:</i>`

.. code-block:: python

    from specter import Spec, expect

    class SampleSpec(Spec):
        """Docstring describing the specification"""

        # Called once before any tests or child Specs are called
        def before_all(self):
            pass

        # Called after all tests and child Specs have been called
        def after_all(self):
            pass

        # Called before each test
        def before_each(self):
            pass

        # Called after each test
        def after_each(self):
            pass

        def it_can_create_an_object(self):
            """ Test docstring"""
            expect('something').to.equal('something')

Nested Tests
~~~~~~~~~~~~~~
Specter tests utilizes the concept of nested test suites. This allows for you to provide a clearer picture of what you are testing within your test suites. For those who have used Jasmine or RSpec should be relatively familiar with this concept from their implementation of Spec.

Within Specter you can create a nested test description (suite) in the form of a class that inherits from the Spec class.

:raw-html:`<i>Example:</i>`

.. code-block:: python

    from specter import Spec, expect

    class SampleSpec(Spec):

        class OtherFunctionalityOfSample(Spec):
            """ Docstring goes here """

            def it_should_do_something(self):
                """ Test Docstring """
                expect('trace').to.equal('trace')

Test Fixtures
~~~~~~~~~~~~~~
In Specter, a test fixture is defined as a test base class that is not treated as a runnable test specification. This allows for you to build reusable test suites through inheritance. To facilitate this, there is a decorator named "fixture" available in the spec module.

:raw-html:`<i>Example:</i>`

.. code-block:: python

    from specter import Spec, fixture, expect

    @fixture
    class ExampleTestFixture(Spec):

        def _random_helper_func(self):
            pass

        def sample_test(self):
            """This test will be on every Spec that inherits this fixture"""
            expect('something').to.equal('something')

    class UsingFixture(ExampleTestFixture):

        def another_test(self):
            expect('this').not_to.equal('that')

:raw-html:`<i>Expected Output (using --show-all-expects):</i>`

.. code-block:: bash

    UsingFixture
      ∟ sample test
        ✔ 'something' to equal 'something'
      ∟ another test
        ✔ 'this' not to equal 'that'

Test State and Inheritance
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Each test spec executes its tests under a clean state that does not contain the attributes of the actual Spec class. This allows for users to not worry about conflicting with the Specter infrastructure. However, the drawback to this is that the instance of "self" within a test is not actually an instance of the type defined in your hardcoded tests. This makes calling super a little bit unconventional as you can see in the example below.

.. code-block:: python

    from specter import Spec

    class FirstSpec(Spec):
        def before_all(self):
            # Do something
            pass

    class SecondSpec(FirstSpec):
        def before_all(self):
            # self is actually an instance of the state object and not an instance of SecondSpec
            super(type(self), self).before_all()

            # Do something else

As you can see in the example, you still can inherit the attributes of your other spec classes. However, you just have to keep in mind, that "self" is actually the state object and not the actual instance of the spec.

Assertions / Expectations
~~~~~~~~~~~~~~~~~~~~~~~~~~
Assertions or expectations in specter attempt to be as expressive as possible. This allows for cleaner and more expressive tests which can help with overall code-awareness and effectiveness. It is important to note that an expectation does not fast-fail the test; it will continue executing the test even if the expectation fails.

Expecations follow this flow
    expect [target object] [to or not_to] [comparison] [expected object]

If you were expecting a status_code object was equal to 200 you would write:
    expect(request.status_code).to.equal(200)

Available Comparisons
^^^^^^^^^^^^^^^^^^^^^^^
    * equal(expected_object)
    * be_greater_than(expected_object)
    * be_less_than(expected_object)
    * be_none()
    * be_true()
    * be_false()
    * be_a(expected_object_type)
    * be_an_instance_of(expected_object_type)
    * be_in(expected_object)
    * contain(expected_object)
    * raise_a(expected_exception_type)

Asserting a raised exception
-----------------------------
.. code::

    expect(example_func, ['args_here']).to.raise_a(Exception)

Fast-fail expectations
^^^^^^^^^^^^^^^^^^^^^^^
In some cases, you need to stop the execution of a test immediately upon the failure of an expectation. With specter, we call these requirements. While they follow the same flow as expectations, the name for this action is "require".

Lets say you are writing a test that checks for valid content within a request body. You could do something like:

.. code-block:: python

    expect(request.status_code).to.equal(200)
    require(request.content).not_to.be_none()
    # ... continue processing content

Utilizing this concept can allow for better visibility into an issue when a test fails. For example, if in the given example, the request status code was 202, but the rest of the test passes, you will instantly can see the problem is with the response code and not the body of the message. This has the ability to save you quite a bit of time; especially if you are testing web APIs.

Data-Driven Tests
~~~~~~~~~~~~~~~~~~
Often times you find that you need to run numerous types of data through a given test case. Rather than having to duplicate your tests a large number of times, you can utilize the concept of Data-Driven Tests. This will allow for you to subject your test cases to specified dataset.

:raw-html:`<i>Example:</i>`

.. code-block:: python

    from specter import DataSpec

    class ExampleData(DataSpec):
        DATASET = {
            'test': {'data_val': 'sample_text'},
            'second_test': {'data_val': 'sample_text2'}
        }

        def sample_data(self, data_val):
            expect(data_val).to.equal('sample_text')

This dataset will produce a Spec with two tests: "sample_data_test" and "sample_data_second_test" each passed in "sample_text" under the data_val parameter.

:raw-html:`<i>This would produce a console output similar to (using --show-all-expects):</i>`

.. code-block:: bash

    Example Data
      ∟ sample data test
        ✔ "sample_text" to equal "sample_text"
      ∟ sample data second test
        ✘ "sample_text2" to equal "sample_text"

.. note::

    Specter will automatically remove duplicated tests within a dataset and will inform you about how many duplications were found.

Metadata in Data-Driven
^^^^^^^^^^^^^^^^^^^^^^^^^
There are two different methods of adding metadata to your data-driven tests. The first method is to assign metadata to the entire set of data-driven tests.

.. code-block:: python

    from specter import DataSpec

    class ExampleData(DataSpec):
        DATASET = {
            'test': {'data_val': 'sample_text'},
            'second_test': {'data_val': 'sample_text'}
        }

        @metadata(test='smoke')
        def sample_data(self, data_val):
            expect(data_val).to.equal('sample_text')

This will assign the metadata attributes to all tests that are generated from the decoratored instance method.
The second way of assigning metadata is by creating a more complex dataset item. A complex dataset item contains two keys; args and meta.

.. code-block:: python

    from specter import DataSpec

    class ExampleData(DataSpec):
        DATASET = {
            'test': {'data_val': 'sample_text'},
            'second_test': {'args': {'data_val': 'sample_text'}, 'meta': {'network': 'yes'}
        }

        def sample_data(self, data_val):
            expect(data_val).to.equal('sample_text')

By doing this, only the 'second_test' will contain metadata. It is important to remember that you can use this format in conjunction with standard metadata tags as mentioned above.

Skipping Tests
~~~~~~~~~~~~~~~~~~
Specter provided a few different ways of skipping tests.

.. autofunction:: specter.skip
.. autofunction:: specter.skip_if
.. autofunction:: specter.incomplete()

Adding Metadata to Tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Specter allows for you to tag tests with metadata. The primary purpose of this is to be able to carry misc information along with your test. At some point in the future, Specter will be able to output this information for consumption and processing. However, currently, metadata information can be used to select which tests you want to run.

.. autofunction:: specter.metadata


text:
module Codewars.G964.Johnann (ann, john, sumAnn, sumJohn) where

aList :: [Int]
aList = 1 : zipWith (-) [1..] (map (jList !!) aList)
jList :: [Int]
jList = 0 : zipWith (-) [1..] (map (aList !!) jList)

ann :: Int -> [Integer]
ann = map fromIntegral . (`take` aList)
john :: Int -> [Integer]
john = map fromIntegral . (`take` jList)

sumAnn :: Int -> Integer
sumAnn = sum . ann
sumJohn :: Int -> Integer
sumJohn = sum . john


text:
osvers=$(sw_vers -productVersion | awk -F. '{print $2}')
sw_vers=$(sw_vers -productVersion)

# Determine OS build number

sw_build=$(sw_vers -buildVersion)

# Checks first to see if the Mac is running 10.7.0 or higher.
# If so, the script checks the system default user template
# for the presence of the Library/Preferences directory. Once
# found, the iCloud and Diagnostic pop-up settings are set
# to be disabled.

if [[ ${osvers} -ge 7 ]]; then

 for USER_TEMPLATE in "/System/Library/User Template"/*
  do
    /usr/bin/defaults write "${USER_TEMPLATE}"/Library/Preferences/com.apple.SetupAssistant DidSeeCloudSetup -bool TRUE
    /usr/bin/defaults write "${USER_TEMPLATE}"/Library/Preferences/com.apple.SetupAssistant GestureMovieSeen none
    /usr/bin/defaults write "${USER_TEMPLATE}"/Library/Preferences/com.apple.SetupAssistant LastSeenCloudProductVersion "${sw_vers}"
    /usr/bin/defaults write "${USER_TEMPLATE}"/Library/Preferences/com.apple.SetupAssistant LastSeenBuddyBuildVersion "${sw_build}"
  done

 # Checks first to see if the Mac is running 10.7.0 or higher.
 # If so, the script checks the existing user folders in /Users
 # for the presence of the Library/Preferences directory.
 #
 # If the directory is not found, it is created and then the
 # iCloud and Diagnostic pop-up settings are set to be disabled.

 for USER_HOME in /Users/*
  do
    USER_UID=`basename "${USER_HOME}"`
    if [ ! "${USER_UID}" = "Shared" ]; then
      if [ ! -d "${USER_HOME}"/Library/Preferences ]; then
        /bin/mkdir -p "${USER_HOME}"/Library/Preferences
        /usr/sbin/chown "${USER_UID}" "${USER_HOME}"/Library
        /usr/sbin/chown "${USER_UID}" "${USER_HOME}"/Library/Preferences
      fi
      if [ -d "${USER_HOME}"/Library/Preferences ]; then
        /usr/bin/defaults write "${USER_HOME}"/Library/Preferences/com.apple.SetupAssistant DidSeeCloudSetup -bool TRUE
        /usr/bin/defaults write "${USER_HOME}"/Library/Preferences/com.apple.SetupAssistant GestureMovieSeen none
        /usr/bin/defaults write "${USER_HOME}"/Library/Preferences/com.apple.SetupAssistant LastSeenCloudProductVersion "${sw_vers}"
        /usr/bin/defaults write "${USER_HOME}"/Library/Preferences/com.apple.SetupAssistant LastSeenBuddyBuildVersion "${sw_build}"
        /usr/sbin/chown "${USER_UID}" "${USER_HOME}"/Library/Preferences/com.apple.SetupAssistant.plist
      fi
    fi
  done
fi

exit 0


text:
module Azure::Compute::Mgmt::V2020_06_30
  module Models
    #
    # Key Vault Key Url and vault id of KeK, KeK is optional and when provided
    # is used to unwrap the encryptionKey
    #
    class KeyVaultAndKeyReference

      include MsRestAzure

      # @return [SourceVault] Resource id of the KeyVault containing the key or
      # secret
      attr_accessor :source_vault

      # @return [String] Url pointing to a key or secret in KeyVault
      attr_accessor :key_url

      #
      # Mapper for KeyVaultAndKeyReference class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'KeyVaultAndKeyReference',
          type: {
            name: 'Composite',
            class_name: 'KeyVaultAndKeyReference',
            model_properties: {
              source_vault: {
                client_side_validation: true,
                required: true,
                serialized_name: 'sourceVault',
                type: {
                  name: 'Composite',
                  class_name: 'SourceVault'
                }
              },
              key_url: {
                client_side_validation: true,
                required: true,
                serialized_name: 'keyUrl',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package io.druid.security.basic.authentication.db.updater;

import io.druid.security.basic.authentication.entity.BasicAuthenticatorCredentialUpdate;
import io.druid.security.basic.authentication.entity.BasicAuthenticatorUser;

import java.util.Map;

/**
 * Implementations of this interface are responsible for connecting directly to the metadata storage,
 * modifying the authenticator database state or reading it. This interface is used by the
 * MetadataStoragePollingBasicAuthenticatorCacheManager (for reads) and the CoordinatorBasicAuthenticatorResourceHandler
 * (for handling configuration read/writes).
 */
public interface BasicAuthenticatorMetadataStorageUpdater
{
  void createUser(String prefix, String userName);

  void deleteUser(String prefix, String userName);

  void setUserCredentials(String prefix, String userName, BasicAuthenticatorCredentialUpdate update);

  Map<String, BasicAuthenticatorUser> getCachedUserMap(String prefix);

  byte[] getCachedSerializedUserMap(String prefix);

  byte[] getCurrentUserMapBytes(String prefix);

  void refreshAllNotification();
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Macro BOOST_ACCUMULATORS_DEFINE_EXTRACTOR</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="index.html" title="Chapter 1. Boost.Accumulators">
<link rel="up" href="accumulators/reference.html#header.boost.accumulators.framework.extractor_hpp" title="Header <boost/accumulators/framework/extractor.hpp>">
<link rel="prev" href="boost/accumulators/extractor/result_this_ty_idp15485152.html" title="Struct template result<this_type(A1)>">
<link rel="next" href="boost/accumulators/features.html" title="Struct template features">

Home
Libraries
People
FAQ
More

Macro BOOST_ACCUMULATORS_DEFINE_EXTRACTOR

BOOST_ACCUMULATORS_DEFINE_EXTRACTOR

Synopsis

// In header: <boost/accumulators/framework/extractor.hpp>

BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(Tag, Feature, ParamSeq)

Copyright © 2005, 2006 Eric Niebler

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package org.apache.cloudstack.framework.rpc;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class RpcCallbackDispatcher<T> {
	private Method _callbackMethod;
	private T _targetObject;

	private RpcCallbackDispatcher(T target) {
		_targetObject = target;
	}

	@SuppressWarnings("unchecked")
	public T getTarget() {
		return (T)Enhancer.create(_targetObject.getClass(), new MethodInterceptor() {
			@Override
			public Object intercept(Object arg0, Method arg1, Object[] arg2,
				MethodProxy arg3) throws Throwable {
				_callbackMethod = arg1;
				return null;
			}
		});
	}

	public RpcCallbackDispatcher<T> setCallback(Object useless) {
		return this;
	}

	public static <P> RpcCallbackDispatcher<P> create(P target)  {
		return new RpcCallbackDispatcher<P>(target);
	}

	public boolean dispatch(RpcClientCall clientCall) {
		assert(clientCall != null);

		if(_callbackMethod == null)
			return false;

		try {
			_callbackMethod.invoke(_targetObject, clientCall, clientCall.getContext());
		} catch (IllegalArgumentException e) {
			throw new RpcException("IllegalArgumentException when invoking RPC callback for command: " + clientCall.getCommand());
		} catch (IllegalAccessException e) {
			throw new RpcException("IllegalAccessException when invoking RPC callback for command: " + clientCall.getCommand());
		} catch (InvocationTargetException e) {
			throw new RpcException("InvocationTargetException when invoking RPC callback for command: " + clientCall.getCommand());
		}

		return true;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UIComposition.Tests.AcceptanceTest.TestInfrastructure
{
    public class EmployeeDataProvider : DataProviderBase<Employee>
    {
        public override string GetDataFilePath()
        {
            throw new NotImplementedException();
        }
    }
}


text:
package com.nokia.xfolite.xforms.model.datatypes;

import java.util.*;

import com.nokia.xfolite.xforms.model.XFormsModelException;

public class DataTypeDate extends DataTypeBase {

    public DataTypeDate(int typeID) {
        super(typeID);
    }

    // TODO: getDisplayString
    public String getDisplayString(ValueProvider prov) {

        //Calendar cal = getCalendarValue(prov)
//        boolean valid = validate(prov);
//        if (valid) {
            return prov.getStringValue();
//        } else {
//            return formatDateTime(prov.getStringValue());
//        }
    }

    public void setCalendarValue(Calendar cal, ValueProvider prov) {
        String strValue;
        if (this.typeID == DataTypeBase.XML_SCHEMAS_DATE) {
           strValue = calendar2xsdDate(cal);
        } else if (this.typeID == DataTypeBase.XML_SCHEMAS_DATETIME) {
            strValue = calendar2xsdDateTime(cal);
        } else if (typeID == DataTypeBase.XML_SCHEMAS_TIME) {
            strValue = calendar2xsdTime(cal);
        } else if (typeID == DataTypeBase.XML_SCHEMAS_GYEARMONTH) {
            strValue = calendar2xsdGYearMonth(cal);
        } else if (typeID == DataTypeBase.XML_SCHEMAS_GYEAR) {
            strValue = calendar2xsdGYear(cal);
        } else if (typeID == DataTypeBase.XML_SCHEMAS_GMONTHDAY) {
            strValue = calendar2xsdGMonthDay(cal);
        } else if (typeID == DataTypeBase.XML_SCHEMAS_GDAY) {
            strValue = calendar2xsdGDay(cal);
        } else if (typeID == DataTypeBase.XML_SCHEMAS_GMONTH) {
            strValue = calendar2xsdGMonth(cal);
        }
        else {
            strValue = calendar2xsdDate(cal);
        }
        prov.setStringValue(strValue);
    }

    public static final String[] MONTH_NAMES = {
    	"January","February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    };

    public static final String[] WEEKDAY_NAMES = {
    	"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    };

    public static String calendar2displayTime(Calendar cal) {
    	return getHour(cal) + ":" + getMinute(cal) + ":" + getSecond(cal);
    }
    public static String calendar2displayTimeShort(Calendar cal) {
    	return getHour(cal) + ":" + getMinute(cal);
    }

    public static String calendar2displayDateShort(Calendar cal) {
    	return calendar2xsdDate(cal);
    }

    public static String calendar2displayDate(Calendar cal, String[] months, String[] weekdays) {
    	return getWeekDayName(cal, weekdays) + ", " + getMonthName(cal, months) + " " + getOrdered(cal.get(Calendar.DAY_OF_MONTH)) + " " + getYear(cal);
    }

    public static String getOrdered(int number) {
    	int last = number % 10;
    	switch (last) {
    	case 1:
    		return number + "st";
    	case 2:
    		return number + "nd";
    	case 3:
    		return number + "rd";
    	default:
    		return number + "th";
    	}
    }

    public static String calendar2displayDateTime(Calendar cal, String[] months, String[] weekdays) {
    	return calendar2displayDate(cal, months, weekdays) + ", " + calendar2displayTime(cal);
    }

    public static String calendar2displayDateTimeShort(Calendar cal) {
    	return calendar2displayDateShort(cal) + " " + calendar2displayTimeShort(cal);
    }

    public static String calendar2xsdGMonth(Calendar cal) {
        return "--" + getMonth(cal) + "--";
    }

    public static String calendar2xsdGDay(Calendar cal) {
        return "---" + getDay(cal);
    }

    public static String calendar2xsdGMonthDay(Calendar cal) {
        return "--" + getMonth(cal) + "-" + getDay(cal);
    }

    public static String calendar2xsdGYear(Calendar cal) {
        return getYear(cal);
    }

    public static String calendar2xsdGYearMonth(Calendar cal) {
        return getYear(cal) + "-" + getMonth(cal);
    }

    public static String calendar2xsdDateTime(Calendar cal) {
    	// Need to convert calendar to GMT before getting date so that also date is GMT-corrected.
    	// Cannot put that in calendar2xsdDate() since that would not be done for a pure date.
    	TimeZone oldTz = cal.getTimeZone();
        TimeZone gmtTz = TimeZone.getTimeZone("GMT");
        cal.setTimeZone(gmtTz);
        String datePart = calendar2xsdDate(cal);
        cal.setTimeZone(oldTz);
        return datePart + "T" + calendar2xsdTime(cal);
    }

    public static String calendar2xsdDate(Calendar cal) {
        return getYear(cal) + "-" + getMonth(cal) + "-" + getDay(cal);
    }

    public static String calendar2xsdTime(Calendar cal) {
        TimeZone oldTz = cal.getTimeZone();
        TimeZone gmtTz = TimeZone.getTimeZone("GMT");
        cal.setTimeZone(gmtTz);
        String rval = getHour(cal) + ":" + getMinute(cal) + ":" + getSecond(cal)
        + "." + getMillisecond(cal)
        + "Z";
        cal.setTimeZone(oldTz);
        return rval;
    }

    public static Calendar xsdDateTime2Calendar(String stringVal) {
        // TODO: validate that stringVal is a legal datetime
        Calendar cal = Calendar.getInstance();
        setDateTime(cal, stringVal);
        return cal;
    }

    public static Calendar xsdDate2Calendar(String stringVal) {
        // TODO: validate that stringVal is a legal datetime
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(0));
        setDate(cal, stringVal);
        return cal;
    }

    public static Calendar xsdTime2Calendar(String stringVal) {
        // TODO: validate that stringVal is a legal datetime
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(0));
        setTime(cal, stringVal);
        return cal;
    }

    /*
    public static Calendar xsdDate2Calendar(String stringVal) {
        // TODO: validate that stringVal is a legal datetime
        Calendar cal = Calendar.getInstance();
        String dateStr = stringVal.substring(0, 10);
        setDate(cal, dateStr);
        return cal;
    }
    */
    public Calendar getCalendarValue(ValueProvider prov) {

        // TODO: internalValidate?
        //xmlSchemaValPtr pVal = InternalValidateL(aProv,ret);

        // validation in our case is supposed to be implemented by
        // subclasses, such as DateTime
        boolean valid = validate(prov);
        if (!valid) {
            throw new XFormsModelException("Illegal date value: " + prov.getStringValue());
            //return Calendar.getInstance();
        } else {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date(0));
            // TODO: timezones (right now ignored, if they were attached)
            if (this.typeID == DataTypeBase.XML_SCHEMAS_DATE) {
                // format: CCYY-MM-DD
            	return xsdDate2Calendar(prov.getStringValue());
            } else if (this.typeID == DataTypeBase.XML_SCHEMAS_DATETIME) {
                // format: CCYY-MM-DDTHH:MM:SS
                return xsdDateTime2Calendar(prov.getStringValue());
            } else if (this.typeID == DataTypeBase.XML_SCHEMAS_TIME) {
            	return xsdTime2Calendar(prov.getStringValue());
            } else if (this.typeID == DataTypeBase.XML_SCHEMAS_GYEARMONTH) {
                //CCYY-MM
                String timeMonthStr = prov.getStringValue().substring(0,7);
                String yearStr = timeMonthStr.substring(0,4);
                String monthStr = timeMonthStr.substring(5,7);
                setYear(cal, yearStr);
                setMonth(cal, monthStr);
            } else if (this.typeID == DataTypeBase.XML_SCHEMAS_GYEAR) {
                String yearStr = prov.getStringValue().substring(0, 4);
                setYear(cal, yearStr);
            } else if (this.typeID == DataTypeBase.XML_SCHEMAS_GMONTHDAY) {
                //--MM-DD
                String gMonthDayStr=prov.getStringValue();
                //String monthDayStr = prov.getStringValue().substring(2,7);
                String monthStr = gMonthDayStr.substring(2,4);
                String dayStr = gMonthDayStr.substring(6,7);
                setMonth(cal, monthStr);
                setDay(cal, dayStr);
            } else if (this.typeID == DataTypeBase.XML_SCHEMAS_GDAY) {
                //---DD
                String dayStr = prov.getStringValue().substring(3,5);
                setDay(cal, dayStr);
            } else if (this.typeID == DataTypeBase.XML_SCHEMAS_GMONTH) {
                //--MM--
                String monthStr = prov.getStringValue().substring(2,4);
                setMonth(cal, monthStr);
            }
            return cal;
        }
    }

    public boolean validate(ValueProvider prov) {
        String strValue = prov.getStringValue();
        // format: CCYY-MM-DD (plus timezone)
        if (strValue.length() < 10) {
            return false;
        }
        if (strValue.charAt(4) != '-') {
            return false;
        }
        if (strValue.charAt(7) != '-') {
            return false;
        }
        // TODO: validate date
        return true;
    }

    protected String getBaseTypeName() {
        return "date";
    }

    static final String ZEROS ="00000000000000000000";

    /**
     * Pad a value with zeroes on the left.
     *
     * @param length
     * @param val
     * @return
     */
    public static String getPadded(int length, int val) {
        String valStr = Integer.toString(val);
        int strLen = valStr.length();
        if (strLen < length) {
            return ZEROS.substring(0, (length-strLen)) + valStr;
        } else {
            return valStr;
        }
    }

    private static String getYear(Calendar cal) {
        return getPadded(4, cal.get(Calendar.YEAR));
    }

    private static String getMonth(Calendar cal) {
        int month = 1;

        switch (cal.get(Calendar.MONTH)) {
        case Calendar.JANUARY:
            month = 1;
            break;
        case Calendar.FEBRUARY:
            month = 2;
            break;
        case Calendar.MARCH:
            month = 3;
            break;
        case Calendar.APRIL:
            month = 4;
            break;
        case Calendar.MAY:
            month = 5;
            break;
        case Calendar.JUNE:
            month = 6;
            break;
        case Calendar.JULY:
            month = 7;
            break;
        case Calendar.AUGUST:
            month = 8;
            break;
        case Calendar.SEPTEMBER:
            month = 9;
            break;
        case Calendar.OCTOBER:
            month = 10;
            break;
        case Calendar.NOVEMBER:
            month = 11;
            break;
        case Calendar.DECEMBER:
            month = 12;
            break;
        }

        return getPadded(2, month);
    }

    private static String getHour(Calendar cal) {
        return getPadded(2, cal.get(Calendar.HOUR_OF_DAY));
    }

    private static String getMinute(Calendar cal) {
        return getPadded(2, cal.get(Calendar.MINUTE));
    }

    private static String getSecond(Calendar cal) {
        return getPadded(2, cal.get(Calendar.SECOND));
    }

    private static String getMillisecond(Calendar cal) {
        return getPadded(3, cal.get(Calendar.MILLISECOND));
    }

    private static String getDay(Calendar cal) {
        return getPadded(2, cal.get(Calendar.DAY_OF_MONTH));
    }
    public static String getWeekDayName(Calendar cal, String[] weekdays) {
        return weekdays[cal.get(Calendar.DAY_OF_WEEK)-1];
    }
    public static String getMonthName(Calendar cal, String[] months) {
        return months[cal.get(Calendar.MONTH)];
    }

    public static void setDateTime(Calendar cal, String stringVal) {
        // TODO: validate that stringVal is a legal datetime
        String dateStr = stringVal.substring(0, 10);
        String timeStr = stringVal.substring(11, stringVal.length());
        setDate(cal, dateStr);
        setTime(cal, timeStr);
    }

    // Time formats:
    // 19:20+01:00
    //
    public static void setTime(Calendar cal, String timeStr) {
        //#debug info
        System.out.println("timeStr: " + timeStr);

    	String hourStr = timeStr.substring(0,2);
        String minuteStr = timeStr.substring(3,5);
        boolean minusZone = false;
        boolean gmtZone = false;
        int zoneStart = -1;

        int len = timeStr.length();
        for(int i=0; i<len; i++) {
        	char c = timeStr.charAt(i);
        	if (c == 'Z') {
        		gmtZone = true;
        		zoneStart = i;
        		break;
        	} else if (c == '+') {
        		zoneStart = i;
        		break;
        	} else if (c == '-') {
        		minusZone = true;
        		zoneStart = i;
        		break;
        	}
        }
        TimeZone oldTz = cal.getTimeZone();
        boolean oldIsGmt = (oldTz.getRawOffset() == 0);
        //#debug info
        System.out.println("Old is GMT: " + oldIsGmt + " (offset: " + oldTz.getRawOffset() + ")");

        String secondStr = null;
        String tzStr = null;
        int hourOffset = 0;
        int minOffset = 0;
        if (zoneStart < 0) {
            secondStr = timeStr.substring(6);
        } else {
            secondStr = timeStr.substring(6, zoneStart);
            tzStr = timeStr.substring(zoneStart);
            if (!gmtZone) {
                String hourOffsetStr = tzStr.substring(1, 3);
                String minOffsetStr = tzStr.substring(4, 6);
                hourOffset = Integer.parseInt(hourOffsetStr);
                minOffset = Integer.parseInt(minOffsetStr);
                if (minusZone) {
                    hourOffset *= -1;
                    minOffset *= -1;
                }
            }
        }
        double seconds = Double.parseDouble(secondStr);
        int wholeSeconds = (int) Math.floor(seconds);
        int milliSeconds = (int) ((seconds - wholeSeconds) * 1000);

        if (!oldIsGmt) {
        	//#debug info
        	System.out.println("Setting timezone to GMT");
        	cal.setTimeZone(TimeZone.getTimeZone("GMT")); // +00:00
        }
        cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourStr));
    	//#debug info
    	System.out.println("Setting hours to " + Integer.parseInt(hourStr));
        cal.set(Calendar.MINUTE, Integer.parseInt(minuteStr));
    	//#debug info
    	System.out.println("Setting minutes to " + Integer.parseInt(minuteStr));
        cal.set(Calendar.SECOND, wholeSeconds);
    	//#debug info
    	System.out.println("Setting seconds to " + wholeSeconds);
        cal.set(Calendar.MILLISECOND, milliSeconds);
    	//#debug info
    	System.out.println("Setting milliseconds to " + milliSeconds);
        if (zoneStart >= 0) {
        	//#debug info
        	System.out.println("Modifying for timezone " + tzStr);
            long time = cal.getTime().getTime();
            time += hourOffset * 3600000 + minOffset * 60000;
            cal.setTime(new Date(time));
        } else { // Adjust for local time instead (default)
        	//#debug info
        	System.out.println("Adjusting for local time: " + oldTz.getRawOffset());
        	//#debug info
        	System.out.println("  Before: " + cal.getTime());
        	long time = cal.getTime().getTime();
            time -= oldTz.getRawOffset();
            cal.setTime(new Date(time));
        	//#debug info
        	System.out.println("  After: " + cal.getTime());
        }
        if (!oldIsGmt) {
        	//#debug info
        	System.out.println("Setting timezone back to " + oldTz.getID());
        	cal.setTimeZone(oldTz);
        }
    }

    public static void setDate(Calendar cal, String dateStr) {
        String yearStr = dateStr.substring(0,4);
        String monthStr = dateStr.substring(5,7);
        String dayStr = dateStr.substring(8,10);

        setYear(cal, yearStr);
        setMonth(cal, monthStr);
        setDay(cal, dayStr);
    }

    private static void setYear(Calendar cal, String yearStr) {
        cal.set(Calendar.YEAR, Integer.parseInt(yearStr));
    }

    private static void setMonth(Calendar cal, String monthStr) {
        switch (Integer.parseInt(monthStr)) {
        case 1:
            cal.set(Calendar.MONTH, Calendar.JANUARY);
            break;
        case 2:
            cal.set(Calendar.MONTH, Calendar.FEBRUARY);
            break;
        case 3:
            cal.set(Calendar.MONTH, Calendar.MARCH);
            break;
        case 4:
            cal.set(Calendar.MONTH, Calendar.APRIL);
            break;
        case 5:
            cal.set(Calendar.MONTH, Calendar.MAY);
            break;
        case 6:
            cal.set(Calendar.MONTH, Calendar.JUNE);
            break;
        case 7:
            cal.set(Calendar.MONTH, Calendar.JULY);
            break;
        case 8:
            cal.set(Calendar.MONTH, Calendar.AUGUST);
            break;
        case 9:
            cal.set(Calendar.MONTH, Calendar.SEPTEMBER);
            break;
        case 10:
            cal.set(Calendar.MONTH, Calendar.OCTOBER);
            break;
        case 11:
            cal.set(Calendar.MONTH, Calendar.NOVEMBER);
            break;
        case 12:
            cal.set(Calendar.MONTH, Calendar.DECEMBER);
            break;
        }
    }

    private static void setDay(Calendar cal, String dayStr) {
        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dayStr));
    }
}