text:
package org.jenkinsci.plugins.github.pullrequest;

import hudson.Extension;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.TaskListener;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.DataBoundConstructor;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Represents a comment for GitHub that can contain token macros.
 *
 * @author Kanstantsin Shautsou
 * @author Alina Karpovich
 */
public class GitHubPRMessage extends AbstractDescribableImpl<GitHubPRMessage> {
    private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRMessage.class);

    private String content;

    @DataBoundConstructor
    public GitHubPRMessage(String content) {
        this.content = content;
    }

    public String expandAll(AbstractBuild<?, ?> build, TaskListener listener) {
        String content = getContent();
        if (content == null || content.length() == 0) {
            return content; // Do nothing for an empty String
        }
//        // Expand environment variables
//        String s = build.getEnvironment(listener).expand(content);
        // Expand build variables
        content = Util.replaceMacro(content, build.getBuildVariableResolver());

        Jenkins jenkins = Jenkins.getInstance();
        try {
            ClassLoader uberClassLoader = Jenkins.getInstance().pluginManager.uberClassLoader;

            if (jenkins.getPlugin("token-macro") != null) {
                List macros = null;

                //get private macroses like groovy template ${SCRIPT} if available
                if (jenkins.getPlugin("email-ext") != null) {
                    Class<?> contentBuilderClazz = uberClassLoader.loadClass("hudson.plugins.emailext.plugins.ContentBuilder");
                    Method getPrivateMacrosMethod = contentBuilderClazz.getDeclaredMethod("getPrivateMacros");
                    macros = new ArrayList((Collection) getPrivateMacrosMethod.invoke(null));
                }

                //calls TokenMacro.expand(build, listener, content, false, macros)
                Class<?> tokenMacroClazz = uberClassLoader.loadClass("org.jenkinsci.plugins.tokenmacro.TokenMacro");
                Method tokenMacroExpand = tokenMacroClazz.getDeclaredMethod("expand", AbstractBuild.class,
                        TaskListener.class, String.class, boolean.class, List.class);

                content = (String) tokenMacroExpand.invoke(null, build, listener, content, false, macros);
            }
        } catch (ClassNotFoundException e) {
            LOGGER.error("Can't find class", e);
        } catch (NoSuchMethodException e) {
            LOGGER.error("Can't evaluate macro", e);
        } catch (InvocationTargetException e) {
            LOGGER.error("Can't evaluate macro", e);
        } catch (IllegalAccessException e) {
            LOGGER.error("Can't evaluate macro", e);
        }

        return content;
    }

    public String getContent() {
        return content;
    }

    @Override
    public DescriptorImpl getDescriptor() {
        return (DescriptorImpl) super.getDescriptor();
    }

    @Extension
    public static class DescriptorImpl extends Descriptor<GitHubPRMessage> {
        @Override
        public String getDisplayName() {
            return "Expandable comment field";
        }
    }
}


text:
@interface HASettingsViewController : UIViewController

@end

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package net.caiban.auth.dashboard.dto.hr;

import java.io.Serializable;
import java.util.Map;

import net.caiban.auth.dashboard.domain.hr.AttendanceSchedule;

/**
 * @author mays
 *
 */
public class AttendanceScheduleDto implements Serializable{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private AttendanceSchedule schedule;
	private Map<Integer, Integer> monthCount;

	public AttendanceSchedule getSchedule() {
		return schedule;
	}
	public void setSchedule(AttendanceSchedule schedule) {
		this.schedule = schedule;
	}
	public Map<Integer, Integer> getMonthCount() {
		return monthCount;
	}
	public void setMonthCount(Map<Integer, Integer> monthCount) {
		this.monthCount = monthCount;
	}

}


text:
<?php

global $_MODULE;
$_MODULE = array();

$_MODULE['<{blocklanguagesdropdown}prestashop>blocklanguagesdropdown_2575f2a453fd18a4e74e430a80eb3540'] = 'Añadir un bloque para seleccionar idioma';
$_MODULE['<{blocklanguagesdropdown}prestashop>blocklanguagesdropdown_d5988791c07fedc0e2fc77683b4e61f6'] = 'Bloque de idiomas';


text:
package org.wso2.developerstudio.codenvy.ext.runner.client.ui.wizard.page.runner;

import com.codenvy.ide.api.mvp.View;
import com.google.inject.ImplementedBy;

@ImplementedBy(CarbonRunnerSelectionPageViewImpl.class)
public interface CarbonRunnerSelectionPageView extends View<CarbonRunnerSelectionPageView.ActionDelegate> {

    public interface ActionDelegate{
        void onRunnerChanged();
    }

}


text:
import React from 'react';
import Router from 'react-routing/src/Router';
import fetch from './core/fetch';
import App from './components/App';
import ContentPage from './components/ContentPage';
import ContactPage from './components/ContactPage';
import BlogPage from './components/BlogPage';
import NotFoundPage from './components/NotFoundPage';
import ErrorPage from './components/ErrorPage';
import DataPage from './components/DataPage';

const router = new Router(on => {
  on('*', async (state, next) => {
    const component = await next();
    return component && <App context={state.context}>{component}</App>;
  });

  on('/contact', async () => <ContactPage />);

  on('/data', async(state) => {
    const res = await fetch(`/api/content?path=${state.path}`);
    const html = await res.json();
    return <DataPage {...html} />;
  });

  on('/blog', async(state) => {
    const res = await fetch(`/api/content?path=${state.path}`);
    const html = await res.json();
    return <BlogPage {...html} />;
  });

  on('*', async (state) => {
    const response = await fetch(`/api/content?path=${state.path}`);
    const content = await response.json();
    return content && <ContentPage {...content} />;
  });

  on('error', (state, error) => state.statusCode === 404 ?
    <App context={state.context} error={error}><NotFoundPage /></App> :
    <App context={state.context} error={error}><ErrorPage /></App>
  );
});

export default router;


text:
copyright:
  years: 2016
lastupdated:  "2016-10-14"

---

#	Utilisation du plan Developer Pro
{: #using_mobilefoundation_p3}

{{site.data.keyword.mobilefoundation_short}}: Developer
Pro convient aux opérations de développement et de tests en
équipe. Ce plan n'est pas destiné à une utilisation en production.

Une fois l'instance de service
{{site.data.keyword.mobilefoundation_short}}: Developer Pro
créée, au bout de quelques secondes, vous pouvez accéder à la
`Présentation` du site
{{site.data.keyword.Bluemix_notm}} qui fournit des tutoriels
et des vidéos facilitant vos premiers pas avec le service
{{site.data.keyword.mobilefoundation_short}}.

## Conditions prérequises
{: #prerequisites_p3}

Prenez connaissance des éléments suivants avant de configurer
l'instance de service {{site.data.keyword.mobilefoundation_short}}: Developer Pro.
* {{site.data.keyword.mobilefoundation_short}}:
Developer Pro est pris en charge uniquement avec les
plans {{site.data.keyword.Bluemix_notm}}
{{site.data.keyword.dashdbshort_notm}}: Enterprise
Transactional (prenant en charge OLTP).

* Vous devez avoir accès aux données d'identification de l'instance de service {{site.data.keyword.dashdbshort_notm}} avant de pouvoir configurer les paramètres de votre instance de service {{site.data.keyword.mobilefoundation_short}}.

**Remarque** : L'instance de service {{site.data.keyword.dashdbshort_notm}} peut exister dans n'importe quel `espace` de votre {{site.data.keyword.Bluemix_notm}} `organisation` ou de n'importe quelle autre `organisation` à laquelle vous avez accès. Assurez-vous que vous disposez des droits nécessaires pour accéder à l'`espace` dans lequel l'instance de service {{site.data.keyword.dashdbshort_notm}} service existe.

## Ajout de la connexion à la base de données
{: #configure_dashdb_p3}

###  Premières étapes
{: #firststeps_p3}

Une fois que vous avez créé l'instance de service
{{site.data.keyword.mobilefoundation_short}}: Developer Pro, lisez la procédure ci-après pour commencer à l'utiliser.

### Configuration de la connexion à l'instance de service {{site.data.keyword.dashdbshort_notm}}
{: #connect_dashdb_p3}

Une fois l'instance de service
{{site.data.keyword.mobilefoundation_short}}: Developer Pro créée, la page *Overview* s'affiche et vous
permet d'indiquer les informations de connexion à l'instance de
service {{site.data.keyword.dashdbshort_notm}}: Enterprise
Transactional.

1. Sélectionnez l'{{site.data.keyword.Bluemix_notm}} `organisation` dans laquelle l'instance de service {{site.data.keyword.dashdbshort_notm}} existe.

+ Depuis la liste des espaces disponibles dans `Organisation`, sélectionnez l'élément `Espace` {{site.data.keyword.Bluemix_notm}} dans lequel se trouve l'instance de service {{site.data.keyword.dashdbshort_notm}},

**Remarque :** Si l'`organisation` et l'`espace` dans lesquels réside votre instance de service {{site.data.keyword.dashdbshort_notm}} ne figurent pas dans la liste, vérifiez que vous êtes membre de cette `organisation` et de cet `espace`.

+ Sélectionnez également le nom du service (`Service
Name`) et les données d'identification
(`Credentials`) {{site.data.keyword.dashdbshort_notm}}
pour la connexion à l'instance de service
{{site.data.keyword.dashdbshort_notm}}.

+  Testez la connexion à l'instance de service
{{site.data.keyword.dashdbshort_notm}}: Enterprise Transactional
indiquée.

+  Cliquez sur **Ajouter**. Cela permet de créer les tables requises dans l'instance de service de base de
données {{site.data.keyword.dashdbshort_notm}} configurée.

**Remarque** : Vous ne pouvez pas modifier l'instance de service {{site.data.keyword.dashdbshort_notm}} configurée pour être utilisée par votre instance de service {{site.data.keyword.mobilefoundation_short}}. Vous pouvez toutefois utiliser la même instance de service {{site.data.keyword.dashdbshort_notm}} sur plusieurs instances de service {{site.data.keyword.mobilefoundation_short}}, car chaque instance de service {{site.data.keyword.mobilefoundation_short}} crée son propre schéma dans l'instance de service {{site.data.keyword.dashdbshort_notm}} sélectionnée.

* Après quelques secondes, vous pouvez accéder à la page `Overview` qui fournit des tutoriels et des vidéos facilitant vos premiers pas avec le service {{site.data.keyword.mobilefoundation_short}}.

## Démarrage du serveur {{site.data.keyword.mobilefirst}}
{: #start_mobilefoundation_p3}

* Pour démarrer {{site.data.keyword.mfserver_short_notm}} avec les paramètres par défaut, cliquez sur **Start Basic Server**.

* Cette option affecte les paramètres suivants à un serveur
{{site.data.keyword.mfserver_long_notm}} :
    - Noeud unique avec 1 Go de mémoire. Cette taille est
suffisante pour des activités de développement et des activités de
test sommaires et pour des charges de travail à faible échelle.

    -	Le `nom_d'utilisateur` et le
`mot_de_passe` sont générés automatiquement pour
vous. Vous pouvez y accéder une fois que le serveur est en opération.

L'implantation de votre serveur débute. Ce processus prend environ 10 minutes et une fenêtre de message indique la progression de l'opération. A son terme, un tableau de bord s'affiche et présente les éléments suivants :

  -	L'état du serveur que vous exécutez (état, taille).

  -	La route de serveur créée pour vous. Utilisez cette route dans votre application mobile pour vous connecter à {{site.data.keyword.mfserver_short_notm}}.

  -	Votre `nom_d'utilisateur` personnel et votre `mot_de_passe` pour accéder à la console {{site.data.keyword.mfp_oc_short_notm}}. Le `mot_de_passe` est masqué. Cliquez sur l'icône **Show Password** pour le visualiser.

*	Cliquez sur **Launch Console** pour ouvrir la console {{site.data.keyword.mfp_oc_short_notm}}.

<!--This console runs inside the container.--> Elle vous permet de gérer vos applications, adaptateurs et
périphériques mobiles, ainsi que l'utilisation de votre serveur en
tant que serveur dorsal mobile, l'envoi de notifications push, etc.

##  Ajout d'un serveur Mobile Analytics
{: #adding_analytics_server_p3}

 Vous pouvez maintenant surveiller votre application mobile sur un serveur {{site.data.keyword.mobilefirst}} en ajoutant un serveur Mobile Analytics à l'instance de service {{site.data.keyword.mobilefoundation_short}}.

 Le plan Developer Pro crée le serveur Mobile Analytics dans un
groupe de conteneurs, l'utilisateur peut personnaliser la
configuration en sélectionnant le nombre de noeuds de conteneur dans
le groupe de conteneurs.

 Les utilisateurs peuvent aussi connecter des volumes aux conteneurs pour conserver les données. Le volume une fois sélectionné ne peut être changé. L'espace de partage de fichiers par défaut disponible pour l'utilisateur est de 20 Go. Si l'utilisateur a besoin d'un espace de stockage supplémentaire pour conserver des données d'analyse, il est invité à acheter un partage de fichiers supplémentaire et à créer un volume en utilisant ce partage de fichier. Il peut ensuite sélectionner ce nouveau volume lors du déploiement du serveur d'analyse.

 Pour plus d'informations sur l'ajout de volumes dans {{site.data.keyword.containerlong}}, voir [Stockage de données persistantes dans un volume à l'aide du tableau de bord {{site.data.keyword.Bluemix_notm}} ](https://console.ng.bluemix.net/docs/containers/container_volumes_ui.html){: new_window}.

* Cliquez sur commande d'ajout d'analyse pour ajouter le serveur Mobile Analytics à l'instance de service {{site.data.keyword.mobilefoundation_short}}.

* Vous pouvez utiliser la configuration de serveur
Mobile Analytics, pour laquelle une mémoire de 1 Go au minimum et 2
Go au maximum est prise en charge. Le serveur d'analyse est pris
en charge uniquement sur un seul noeud de ce plan.

Le processus de mise à disposition commence. Ce processus prend environ 10 minutes et une fenêtre de
message indique la progression de l'opération.

* Lancez MobileFirst Analytics depuis {{site.data.keyword.mfp_oc_short_notm}}.

* La connexion unique est activée entre {{site.data.keyword.mfserver_short_notm}} et le serveur Mobile Analytics. Le serveur Mobile Analytics est configuré avec les mêmes clés LTPA et données d'identification de l'utilisateur que celles de {{site.data.keyword.mfserver_short_notm}}. Vous pouvez vous servir des mêmes
`nom_d'utilisateur` et
`mot_de_passe` pour vous connecter à la console
Mobile Analytics que ceux utilisés pour la connexion à
{{site.data.keyword.mfp_oc_short_notm}}.

Pour plus d'informations sur MobileFirst Analytics, voir
[MobileFirst
Foundation Operational Analytics](https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/analytics/).

**Remarque :** le serveur Mobile Analytics est retiré quand vous supprimez l'instance de service {{site.data.keyword.mobilefoundation_short}} ou si vous tentez de recréer le serveur {{site.data.keyword.mfserver_short_notm}}.

## Recréation du serveur
{{site.data.keyword.mobilefirst}}
{: #recreate_mobilefoundation_p3}

*	Cliquez sur **Recreate** pour recréer le
serveur.

* Cette action arrête votre serveur existant et supprime les données. Une nouvelle instance de serveur est créée avec une version mise à jour, si elle est disponible. Cette action prend quelques minutes avant de s'achever.

**Remarque** : Toutes les données provenant de votre instance de serveur précédente, y compris les informations sur les applications et les adaptateurs, sont conservées dans l'instance de service {{site.data.keyword.dashdbshort_notm}} configurée ; elles sont utilisées pour recréer le serveur.

##	Paramétrage d'une configuration avancée
{: #using_mfs_advanced_p3}

L'option **Start Server with Advanced Configuration** de la page `Overview` permet de créer le serveur avec des paramètres avancés ou personnalisés. Vous pouvez également mettre à jour les paramètres du serveur pour personnaliser sa configuration en cliquant sur l'onglet **Configuration**. {{site.data.keyword.mobilefoundation_short}} vous permet d'accéder à certains paramètres avancés.

*	Dans l'onglet **Topology**, vous pouvez
sélectionner la taille du serveur, ainsi que la mémoire dont vous avez besoin. Le
serveur par défaut est créé avec 1 Go de mémoire.
  - Vous pouvez modifier la mémoire de votre serveur en
fonction de vos besoins jusqu'à 2 Go au maximum.

  - **Nodes** affiche le nombre de noeuds créés. Cette zone n'est pas modifiable dans {{site.data.keyword.mobilefoundation_short}}: Developer Pro. Le nombre de noeuds
<!--in your {{site.data.keyword.IBM_notm}} container group-->
est par défaut de **1** dans le plan Developer Pro.

Pour plus de détails, voir la [documentation {{site.data.keyword.mobilefoundation_long}}](https://www.ibm.com/support/knowledgecenter/SSHS8R_8.0.0/wl_welcome.html){: new_window}.


text:
using Linq.Shadow.Common;

namespace JoinOperators
{
    public class Program
    {
        public static void Main(string[] args)
        {

            var joinOperators = new JoinOperators();

            /*
                This sample shows how to perform a simple inner equijoin of two sequences to produce
                a flat result set that consists of each element in suppliers that has a matching element in customers.
            */
            joinOperators.InnerJoinTwoSequencesLambda(DataProvider.GivenCustomers(), DataProvider.GivenSuppliers());
            joinOperators.InnerJoinTwoSequencesLinq(DataProvider.GivenCustomers(), DataProvider.GivenSuppliers());

            /*
                A group join produces a hierarchical sequence.
                The following query is an inner join that produces a sequence of objects,
                each of which has a key and an inner sequence of all matching elements.
            */
            joinOperators.GroupJoinTwoSequencesLambda(DataProvider.GivenCustomers(), DataProvider.GivenSuppliers());
            joinOperators.GroupJoinTwoSequencesLinq(DataProvider.GivenCustomers(), DataProvider.GivenSuppliers());

            /*
                The group join operator is more general than join, as this slightly more verbose
                version of the cross join sample shows.
            */
            joinOperators.CrossJoinByCategoriesLambda(DataProvider.GivenProducts());
            joinOperators.CrossJoinByCategoriesLinq(DataProvider.GivenProducts());

            /*
                A left outer join produces a result set that includes all the left hand side elements
                at least once, even if they don't match any right hand side elements.
            */
            joinOperators.LeftOuterJoinByCountryLambda(DataProvider.GivenCustomers(), DataProvider.GivenSuppliers());
            joinOperators.LeftOuterJoinByCountryLinq(DataProvider.GivenCustomers(), DataProvider.GivenSuppliers());

            /*
                For each customer in the table of customers, this query returns all the suppliers
                from that same country, or else a string indicating that no suppliers from that country were found.
            */
            joinOperators.LeftOuterJoinByCountryForEachCustomerLambda(DataProvider.GivenCustomers(), DataProvider.GivenSuppliers());
            joinOperators.LeftOuterJoinByCountryForEachCustomerLinq(DataProvider.GivenCustomers(), DataProvider.GivenSuppliers());

            /*
                For each supplier in the table of suppliers, this query returns all the customers
                from the same city and country, or else a string indicating that no customers from that city/country were found.
                Note the use of anonymous types to encapsulate the multiple key values.
            */
            joinOperators.LeftOuterJoinByCountryAndCityForEachCustomerLambda(DataProvider.GivenCustomers(), DataProvider.GivenSuppliers());
            joinOperators.LeftOuterJoinByCountryAndCityForEachCustomerLinq(DataProvider.GivenCustomers(), DataProvider.GivenSuppliers());
        }
    }
}


text:
v0.2 planned
============

* watching templates and resources
* highlight root chapters in main nav on child page

v0.1 released
=============

+ Chapters sorting
+ Basic docs
+ YAML config
+ Success messages, build time
+ Watch & rebuild
+ `init` command
+ Smarter scanning - look for index files in depth
+ **Top menu config**
+ **Multiple sources - sub-projects or sub-directories**
+ **Nice default theme with smart navigation**
+ **`serve` command**

Ideas
=====

* !! at start of line in .md may generate
...

* auto-add target="_blank" to all Markdown external links, internal domains should be whitelisted
* extract docstrings from .py
* extract JSDoc from .js
* built-in WYSIWYG editor for Markdown


text:
export interface ColorRgbJSON {
    red: number
    green: number
    blue: number
}

export default class ColorRGB {
    public static fromJSON(json: ColorRgbJSON) {
        return new ColorRGB(json.red, json.green, json.blue)
    }

    private _red: number
    private _green: number
    private _blue: number

    constructor(r: number = 0, g: number = 0, b: number = 0) {
        this._red = r
        this._green = g
        this._blue = b
    }

    get r(): number {
        return this._red
    }
    get g(): number {
        return this._green
    }
    get b(): number {
        return this._blue
    }

    get red(): number {
        return this._red
    }
    get green(): number {
        return this._green
    }
    get blue(): number {
        return this._blue
    }

    public clone(r: number | null = null, g: number | null = null, b: number | null = null): ColorRGB {
        return new ColorRGB(r || this.r, g || this.g, b || this.b)
    }

    public toJSON(): ColorRgbJSON {
        return {
            red: this.r,
            green: this.g,
            blue: this.b,
        }
    }

    public toCSSColor() {
        return `rgba(${this.r | 0}, ${this.g | 0}, ${this.b | 0}, 1)`
    }

    /**
     * @deprecated
     */
    public toString() {
        return `rgba(${this.r | 0}, ${this.g | 0}, ${this.b | 0}, 1)`
    }
}


text:
@interface BKProgressLabel : UILabel
@property (nonatomic, assign) double startValue;
@property (nonatomic, assign) double endValue;
@property (nonatomic, assign) double duration;
@property (nonatomic, assign) NSString *method;
@property (nonatomic, strong) NSString *format;
@property (nonatomic, strong) SuccessBlock completionHandler;
-(void)countFrom:(float)from to:(float)to duration:(NSTimeInterval)duration;
@end

@interface BKBar : UIView
@property (nonatomic, strong) CABasicAnimation *animation;
@property (nonatomic, strong) UIColor *fillColor;
@property (nonatomic, strong) CAShapeLayer *line;
@property (nonatomic, strong) UIBezierPath *path;
- (id)init:(CGRect)frame color:(UIColor*)color fillColor:(UIColor*)fillColor duration:(float)duration height:(float)height;
@end

@interface BKBarChart : UIView
@property (nonatomic) float barWidth;
@property (nonatomic) float duration;
@property (nonatomic) float shadow;
@property (nonatomic) float radius;
@property (strong, nonatomic) NSArray *xLabels;
@property (strong, nonatomic) NSArray *yValues;
@property (nonatomic, strong) UIColor *barColor;
@property (nonatomic, strong) UIColor *axisColor;
@property (nonatomic, strong) UIColor *fillColor;
@property (nonatomic, strong) UIFont *axisFont;
@property (nonatomic, strong) NSDictionary *colors;
@property (nonatomic, strong) SuccessBlock barHandler;
@property (nonatomic, strong) SuccessBlock completionHandler;
- (void)drawChart;
@end

@interface BKLineChart : UIView
@property (nonatomic) float lineWidth;
@property (nonatomic) float duration;
@property (strong, nonatomic) NSNumber *yMin;
@property (strong, nonatomic) NSNumber *yMax;
@property (strong, nonatomic) NSArray *xLabels;
@property (strong, nonatomic) NSArray *yValues;
@property (nonatomic, strong) UIColor *lineColor;
@property (nonatomic, strong) UIColor *axisColor;
@property (nonatomic, strong) SuccessBlock completionHandler;
- (void)drawChart;
@end

@interface BKRatioChart : UIView
@property (nonatomic, strong) UIColor *color1;
@property (nonatomic, strong) UIColor *color2;
@property (nonatomic, strong) UIColor *bgColor;
@property (nonatomic) float startValue;
@property (nonatomic) float endValue;
@property (nonatomic) float lineWidth;
@property (nonatomic, strong) BKProgressLabel* label;
@property (nonatomic, strong) SuccessBlock completionHandler;
- (void)drawChart;
@end


text:
var routes = require('../routes/index')
    , user = require('../routes/user')
    ;

module.exports = function(app,passport, auth) {
    var users = require('../app/controllers/users');
    // app.get('/', routes.index);
    //app.get('/users', user.list);
    //Setting the facebook oauth routes
    app.get('/signout', users.signOut);

    app.get('/auth/facebook', passport.authenticate('facebook', {
        scope: ['email'],
        failureRedirect: '/signin'
    }), users.signIn);

    app.get('/auth/facebook/callback', passport.authenticate('facebook', {
        failureRedirect: '/signin'
    }), users.authCallback);

    //Setting the github oauth routes
    app.get('/auth/github', passport.authenticate('github', {
        failureRedirect: '/signin'
    }), users.signIn);

    app.get('/auth/github/callback', passport.authenticate('github', {
        failureRedirect: '/signin'
    }), users.authCallback);

    //Setting the twitter oauth routes
    app.get('/auth/twitter', passport.authenticate('twitter', {
        failureRedirect: '/signin'
    }), users.signIn);

    app.get('/auth/twitter/callback', passport.authenticate('twitter', {
        failureRedirect: '/signin'
    }), users.authCallback);

    //Setting the google oauth routes
    app.get('/auth/google', passport.authenticate('google', {
        failureRedirect: '/signin',
        scope: [
            'https://www.googleapis.com/auth/userinfo.profile',
            'https://www.googleapis.com/auth/userinfo.email'
        ]
    }), users.signIn);

    app.get('/auth/google/callback', passport.authenticate('google', {
        failureRedirect: '/signin'
    }), users.authCallback);

    //Finish with setting up the userId param
    app.param('userId', users.user);

    //Thought routes
    var thoughts = require('../app/controllers/thoughts');
    app.get('/thoughts', thoughts.getPublic);
    app.post('/thoughts', thoughts.create);
    app.get('/thoughts/:thoughtId', thoughts.show);

    //Finish with setting up the articleId param
    app.param('thoughtId', thoughts.thought);

    //Home route
    var index = require('../app/controllers/index');
    app.get('/',index.render);
}


text:
<?php

namespace App\Http\Middleware;

use Closure;
use App\User;
use Illuminate\Support\Facades\Auth;

class VerifyVerified
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (! Auth::user() || ! Auth::user()->server || ! Auth::user()->verified){
            abort(403, 'Access denied');
        }
        return $next($request);
    }
}


text:
using namespace std;
#include<cmath>
class twoDshapes
{
private :
	double cx;
	const string name;
	double cy;
public:
	 virtual double getdistance(double x, double y)=0 ;
	 virtual double getcx()=0;
	 virtual double getcy()=0;
	 virtual string getname()=0;
	 virtual void setcenterx(double cx)=0;
	virtual void setcentery(double cy)=0;
	friend istream& operator >> (istream &in, twoDshapes&f);
	 virtual double area(double x) =0;

	twoDshapes();
	~twoDshapes();
};


text:
create or replace function setup_10_web()
returns setof text
as $test$
	begin
		perform web.clear_sessions();
	exception
		when invalid_schema_name then
			return;
		when undefined_function then
			return;
	end;
$test$ language plpgsql;

create or replace function new_session_id()
returns text as $test$
	declare
		sessionid		text;
		holder			text;
	begin
		loop
			select md5(random()::text) into sessionid;
			select sess_id into holder from web.session
				where sess_id = sessionid;
			if found then
				continue;
			else
				return sessionid;
			end if;
		end loop;
	end;
$test$ language plpgsql;

create or replace function create_test_session()
returns text as $test$
	declare
		sessionid		text;
	begin
		select into sessionid new_session_id();
		perform web.set_session_data(sessionid, md5(random()::text),
			now() + interval '1 day');
		return sessionid;
	end;
$test$ language plpgsql;

create or replace function test_web_schema()
returns setof text
as $$
	begin
		return next has_schema('web', 'There should be a web sessions schema.');
	end;
$$ language plpgsql;

create or replace function test_web_session_table()
returns setof text
as $$
	begin
		return next has_table('web', 'session', 'There should be a session table.');
	end;
$$ language plpgsql;

create or replace function test_web_session_id_exists()
returns setof text
as $$
	begin
		return next has_column('web', 'session', 'sess_id', 'Needs to have a session id column.');
	end;
$$ language plpgsql;

create or replace function test_web_session_id_type()
returns setof text
as $$
	begin
		return next col_type_is('web', 'session', 'sess_id', 'text', 'Session id is a string.');
	end;
$$ language plpgsql;

create or replace function test_web_session_id_is_pk()
returns setof text
as $$
	begin
		return next col_is_pk('web', 'session', 'sess_id', 'The session id is the primary key');
	end;
$$ language plpgsql;

create or replace function test_web_session_data_exists()
returns setof text
as $$
	begin
		return next has_column('web', 'session', 'sess_data', 'Needs to store the session data.');
	end;
$$ language plpgsql;

create or replace function test_web_session_data_type()
returns setof text
as $$
	begin
		return next col_type_is('web', 'session', 'sess_data', 'text', 'Session data is text.');
	end;
$$ language plpgsql;

create or replace function test_web_session_expiration_exists()
returns setof text
as $$
	begin
		return next has_column('web', 'session', 'expiration', 'Needs a time limit on the session.');
	end;
$$ language plpgsql;

create or replace function test_web_session_expiration_type()
returns setof text
as $$
	begin
		return next col_type_is('web', 'session', 'expiration', 'timestamp with time zone', 'expiration needs to be a timestamp.');
	end;
$$ language plpgsql;

create or replace function test_web_session_expiration_default()
returns setof text
as $$
	begin
		return next col_default_is('web', 'session', 'expiration', $a$(now() + '1 day'::interval)$a$, 'Default expiration is on day.');
	end;
$$ language plpgsql;

create or replace function test_web_session_expiration_has_index()
returns setof text
as $$
	begin
		return next has_index('web', 'session', 'expire_idx', array['expiration'], 'Needs an index for the expiration column.');
	end;
$$ language plpgsql;

create or replace function test_web_function_setsessiondata_exists()
returns setof text
as $$
	begin
		return next has_function('web', 'set_session_data', array['text', 'text', 'timestamp with time zone'], 'Needs a set session data function.');
		return next is_definer('web', 'set_session_data', array['text', 'text', 'timestamp with time zone'], 'Set session data should have definer security.');
		return next function_returns('web', 'set_session_data', array['text', 'text', 'timestamp with time zone'], 'void', 'Set session data should not return anything.');
	end;
$$ language plpgsql;

create or replace function test_web_function_setsessiondata_save_data()
returns setof text
as $test$
	declare
		sessionid		text;
		sessiondata		text;
	begin
		select into sessionid new_session_id();
		select md5(random()::text) into sessiondata;
		perform web.set_session_data(sessionid, sessiondata, null);
		return next results_eq(
			$$select web.get_session_data('$$ || sessionid || $$')$$,
			$$values ('$$ || sessiondata || $$')$$,
			'The set_session_data should create a new session.');
	end;
$test$ language plpgsql;

create or replace function test_web_function_setsessiondata_update_data()
returns setof text
as $test$
	declare
		sessionid			text;
	begin
		select create_test_session into sessionid from create_test_session();
		perform web.set_session_data(sessionid, 'new-data', now() + interval '1 day');
		return next results_eq(
			$$select web.get_session_data('$$ || sessionid || $$')$$,
			$$values ('new-data')$$,
			'The set_session_data should update a session.');
	end;
$test$ language plpgsql;

create or replace function test_web_function_destroysession_exists()
returns setof text
as $$
	begin
		return next has_function('web', 'destroy_session', array['text'], 'Needs to have a destroy function.');
		return next is_definer('web', 'destroy_session', array['text'], 'Session destroy should have definer security.');
		return next function_returns('web', 'destroy_session', array['text'], 'void', 'Session destroy should not return anything.');
	end;
$$ language plpgsql;

create or replace function test_web_function_destroysession_removes_data()
returns setof text
as $test$
	declare
		sessionid			text;
	begin
		select into sessionid create_test_session from create_test_session();
		perform web.destroy_session(sessionid);
		return next is_empty(
			$$select web.get_session_data('$$ || sessionid || $$')$$,
			'Session destroy should delete the session');
	end;
$test$ language plpgsql;

create or replace function test_web_function_getsessiondata_exists()
returns setof text
as $$
	begin
		return next has_function('web', 'get_session_data', array['text'], 'Needs a get_session_data function.');
		return next is_definer('web', 'get_session_data', array['text'], 'Get session data should have definer security.');
		return next function_returns('web', 'get_session_data', array['text'], 'setof text', 'Get session data should not return anything.');
	end;
$$ language plpgsql;

create or replace function test_web_function_getsessiondata_data()
returns setof text
as $test$
	declare
		sessionid			text;
		sessiondata			text:=md5(random()::text);
	begin
		select into sessionid create_test_session from create_test_session();
		perform web.set_session_data(sessionid, sessiondata, null);
		return next results_eq(
			$$select web.get_session_data('$$ || sessionid || $$')$$,
			$$values ('$$ || sessiondata || $$')$$,
			'Get session data should retrieve the data from the session.');
	end;
$test$ language plpgsql;

create or replace function test_web_function_getsessiondata_ignores_expired()
returns setof text
as $test$
	declare
		sessionid			text;
		sessiondata			text:=md5(random()::text);
	begin
		select into sessionid create_test_session
			from create_test_session();
		perform web.set_session_data(sessionid, sessiondata, now() - interval '1 day');
		return next is_empty(
			$$select web.get_session_data('$$ || sessionid || $$')$$,
			'Get session data ignores expired sessions.');
	end;
$test$ language plpgsql;

create or replace function test_web_function_clearsessions_exists()
returns setof text
as $$
	begin
		return next has_function('web', 'clear_sessions', 'Needs a clear function.');
		return next is_definer('web', 'clear_sessions', 'Clear sessions should have definer security.');
		return next function_returns('web', 'clear_sessions', 'void', 'Clear sessions data should not return anything.');
	end;
$$ language plpgsql;

create or replace function test_web_function_clearsessions_removes_data()
returns setof text
as $test$
	begin
		perform create_test_session();
		perform create_test_session();
		perform web.clear_sessions();
		return next is_empty(
			$$select * from web.session$$,
			'Clear sessions should remove all sessions.');
	end;
$test$ language plpgsql;

create or replace function test_web_function_countsessions_exists()
returns setof text
as $$
	begin
		return next has_function('web', 'count_sessions', 'Needs a count for the length function.');
		return next is_definer('web', 'count_sessions', 'Count sessions should have definer security.');
		return next function_returns('web', 'count_sessions', 'integer', 'Should return the number of active sessions.');
	end;
$$ language plpgsql;

create or replace function test_web_function_countsessions_returns_count()
returns setof text
as $$
	begin
		perform create_test_session();
		perform create_test_session();
		perform create_test_session();
		perform create_test_session();
		return next results_eq(
			'select web.count_sessions()',
			'values (4)',
			'Count should return the number of sessions open.');
	end;
$$ language plpgsql;

create or replace function test_web_function_countsessions_ignores_expired()
returns setof text
as $$
	declare
		sessionid			text;
		sessiondata			text:=md5(random()::text);
	begin
		select into sessionid create_test_session
			from create_test_session();
		perform web.set_session_data(sessionid, sessiondata, now() - interval '1 day');
		perform create_test_session();
		perform create_test_session();
		perform create_test_session();
		return next results_eq(
			'select web.count_sessions()',
			'values (3)',
			'Count should ignore expired sessions.');
	end;
$$ language plpgsql;

create or replace function test_web_function_countsessions_counts_nulls()
returns setof text
as $$
	declare
		sessionid			text;
		sessiondata			text:=md5(random()::text);
	begin
		select into sessionid create_test_session
			from create_test_session();
		perform web.set_session_data(sessionid, sessiondata, null);
		perform create_test_session();
		perform create_test_session();
		perform create_test_session();
		return next results_eq(
			'select web.count_sessions()',
			'values (4)',
			'Count should include expire set to null.');
	end;
$$ language plpgsql;

create or replace function test_web_trigger_deleteexpired_exists()
returns setof text
as $$
	begin
		return next trigger_is(
			'web',
			'session',
			'delete_expired_trig',
			'web',
			'remove_expired',
			'Needs a delete expired trigger.');
	end;
$$ language plpgsql;

create or replace function test_web_function_deleteexpired_exists()
returns setof text
as $$
	begin
		return next has_function('web', 'remove_expired', 'Needs a function to delete expired records.');
		return next is_definer('web', 'remove_expired', 'Delete expired should have definer security.');
		return next function_returns('web', 'remove_expired', 'trigger', 'Delete expired data should return a trigger.');
	end;
$$ language plpgsql;

create or replace function test_web_function_deleteexpired_after_insert()
returns setof text
as $test$
	declare
		sessionid		text;
		sessiondata		text;
	begin
		select into sessionid new_session_id();
		select md5(random()::text) into sessiondata;
		perform web.set_session_data(sessionid, sessiondata, now() - interval '1 day');
		return next is_empty(
			$$select * from web.session
				where sess_id = '$$ || sessionid || $$'$$,
				'Expired sessions should be deleted after insert.');
	end;
$test$ language plpgsql;

create or replace function test_web_function_deleteexpired_after_update()
returns setof text
as $test$
	declare
		sessionid			text;
		sessiondata			text:=md5(random()::text);
	begin
		select into sessionid create_test_session
			from create_test_session();
		perform web.set_session_data(sessionid, sessiondata, now() - interval '1 day');
		return next is_empty(
			$$select * from web.session
				where sess_id = '$$ || sessionid || $$'$$,
				'Expired sessions should be deleted after update.');
	end;
$test$ language plpgsql;

create or replace function test_web_function_allids_is_removed()
returns setof text
as $$
	begin
		return next hasnt_function('web', 'all_session_ids', 'All ids is removed for security reasons.');
	end;
$$ language plpgsql;

create or replace function test_web_user_exists()
returns setof text
as $$
	begin
		return next has_user('nodepg', 'Needs to have the nodepg user.');
	end;
$$ language plpgsql;

create or replace function failed_test( thetest text )
returns boolean
as $$
	declare
		error_holder		text;
	begin
		select
			runtests into error_holder
		from
			runtests(thetest)
		where
			runtests ~* '^not ok';
		return found;
	end;
$$ language plpgsql;

create or replace function correct_web()
returns setof text
as $funct$
	declare
		error_holder		text;
	begin
		if failed_test('test_web_schema') then
			create schema web;
			return next 'Created a schema';
		end if;
		if failed_test('test_web_session_table') then
			create table web.session();
			return next 'Created the session table.';
		end if;
		if failed_test('test_web_session_id_exists') then
			alter table web.session
				add column sess_id text;
			return next 'Added sess_id column.';
		end if;
		if failed_test('test_web_session_id_type') then
			alter table web.session
				alter column sess_id type text;
			return next 'Changed sess_id to type text.';
		end if;
		if failed_test('test_web_session_id_is_pk') then
			alter table web.session
				add primary key (sess_id);
			return next 'Made sess_id the primary key.';
		end if;
		if failed_test('test_web_session_data_exists') then
			alter table web.session
				add column sess_data text;
			return next 'Added sess_data column.';
		end if;
		if failed_test('test_web_session_data_type') then
			alter table web.session
				alter column sess_data type text;
			return next 'Changed sess_data to type text.';
		end if;
		if failed_test('test_web_session_expiration_exists') then
			alter table web.session
				add column expiration timestamp with time zone;
			return next 'Added expiration column.';
		end if;
		if failed_test('test_web_session_data_type') then
			alter table web.session
				alter column expiration type timestamp with time zone;
			return next 'Changed expiration to type timestamp.';
		end if;
		if failed_test('test_web_session_expiration_default') then
			alter table web.session
				alter column expiration set default now() + interval '1 day';
			return next 'Added expiration default.';
		end if;
		if failed_test('test_web_session_expiration_has_index') then
			create index expire_idx on web.session (expiration);
			return next 'Created expiration index.';
		end if;

		if failed_test('test_web_function_allids_is_removed') then
			drop function web.all_session_ids();
			return next 'Removed all ids for security reasons.';
		end if;

		create or replace function web.valid_sessions()
		returns setof web.session as $$
			begin
				return query select * from web.session
					where expiration > now()
						or expiration is null;
			end;
		$$ language plpgsql security definer
		set search_path = web, pg_temp;

		create or replace function web.set_session_data(
			sessid text,
			sessdata text,
			expire timestamp with time zone)
		returns void as $$
			begin
				loop
					update web.session
						set sess_data = sessdata,
							expiration = expire
						where sess_id = sessid;
					if found then
						return;
					end if;
					begin
						insert into web.session (sess_id, sess_data, expiration)
							values (sessid, sessdata, expire);
						return;
					exception
						when unique_violation then
							-- do nothing.
					end;
				end loop;
			end;
		$$ language plpgsql security definer
		set search_path = web, pg_temp;
		return next 'Created function web.set_session_data';

		create or replace function web.destroy_session(sessid text)
		returns void as $$
			begin
				delete from web.session where sess_id = sessid;
			end;
		$$ language plpgsql security definer
		set search_path = web, pg_temp;
		return next 'Created function web.destroy_session.';

		create or replace function web.get_session_data(sessid text)
		returns setof text as $$
			begin
				return query select sess_data
					from web.valid_sessions()
					where sess_id = sessid;
			end;
		$$ language plpgsql security definer
		set search_path = web, pg_temp;
		return next 'Created function web.get_session.';

		create or replace function web.clear_sessions()
		returns void as $$
			begin
				delete from web.session;
			end;
		$$ language plpgsql security definer
		set search_path = web, pg_temp;
		return next 'Created function web.clear_sessions.';

		create or replace function web.count_sessions()
		returns int as $$
			declare
				thecount int := 0;
			begin
				select count(*) into thecount
					from web.valid_sessions();
				return thecount;
			end;
		$$ language plpgsql security definer
		set search_path = web, pg_temp;
		return next 'Created function web.count_sessions.';

		drop trigger if exists delete_expired_trig on web.session;

		create or replace function web.remove_expired()
		returns trigger as $$
			begin
				delete from web.session where expiration < now();
				return null;
			end;
		$$ language plpgsql security definer
		set search_path = web, pg_temp;
		return next 'Created trigger function web.delete_expired.';

		create trigger delete_expired_trig
			after insert or update
			on web.session
			execute procedure web.remove_expired();
		return next 'Created trigger delete_expired on web.session.';

		if failed_test('test_web_user_exists') then
			create user nodepg with password 'password';
			return next 'Created user nodepg';
		end if;

		revoke all on function
			web.valid_sessions(),
			web.set_session_data(
				sessid text,
				sessdata text,
				expire timestamp with time zone),
			web.destroy_session(sessid text),
			web.get_session_data(sessid text),
			web.clear_sessions(),
			web.count_sessions(),
			web.remove_expired()
		from public;

		grant execute on function
			web.set_session_data(
				sessid text,
				sessdata text,
				expire timestamp with time zone),
			web.destroy_session(sessid text),
			web.get_session_data(sessid text),
			web.clear_sessions(),
			web.count_sessions()
		to nodepg;

		grant usage on schema web to nodepg;

		return next 'Permissions set.';
	end;
$funct$ language plpgsql;


text:
@implementation QKDataManager

+ (void)loadLocalExcelFilesWithBlock:(void (^)(NSArray *))block {
    NSMutableArray *excelArr = [[NSMutableArray alloc] init];
    for (NSString *tmpFile in [self allFilesInDocumentDirectory]) {
        NSString *extStr = [tmpFile pathExtension];
        if ([extStr isEqualToString:@"xls"]) {
            [excelArr addObject:tmpFile];
        }
    }
    block(excelArr);
}

+ (void)loadLocalRealmDatabasesWithBlock:(void (^)(NSArray *))block {
    NSMutableArray *realmArr = [[NSMutableArray alloc] init];
    for (NSString *tmpFile in [self allFilesInDocumentDirectory]) {
        NSString *extStr = [tmpFile pathExtension];
        if ([extStr isEqualToString:@"realm"]) {
            if ([tmpFile isEqualToString:QKSavedControlCharts]) {
                continue;
            } else {
                [realmArr addObject:tmpFile];
            }
        }
    }
    block(realmArr);
}

+ (NSArray *)allFilesInDocumentDirectory {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSLog(@"%@", path);
    NSArray *fileArr = [[NSFileManager defaultManager] subpathsAtPath:path];
    return fileArr;
}

+ (NSString *)fullPathOfFile:(NSString *)file {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    return [path stringByAppendingPathComponent:file];
}

+ (void)removeLocalFile:(NSString *)filePath {
    NSString *path = [self fullPathOfFile:filePath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        [fileManager removeItemAtPath:path error:nil];
    }

    if ([[filePath pathExtension] isEqualToString:@"realm"]) {
        NSArray *allFiles = [self allFilesInDocumentDirectory];
        for (NSString *tmpPath in allFiles) {
            if ([tmpPath hasPrefix:filePath]) {
                [fileManager removeItemAtPath:tmpPath error:nil];
            }
        }
    }
}

+ (void)createLocalFile:(NSString *)fileName extension:(NSString *)extension {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:[fileName stringByAppendingPathExtension:extension]];
    if ([extension isEqualToString:@"xls"]) {

        JXLSCell *cell;
        JXLSWorkBook *workBook = [JXLSWorkBook new];
        JXLSWorkSheet *workSheet = [workBook workSheetWithName:@"SHEET1"];

        [workSheet setWidth:2500 forColumn:0 defaultFormat:NULL];

        for(uint32_t idx = 0; idx < 1; idx ++) {
            cell = [workSheet setCellAtRow:idx column:0 toDoubleValue:0];
        }

        [workBook writeToFile:filePath];

    } else {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    }

}

+ (void)createLocalXLSFile:(NSString *)fileName columnNumber:(NSInteger)num {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];

    JXLSCell *cell;
    JXLSWorkBook *workBook = [JXLSWorkBook new];
    JXLSWorkSheet *workSheet = [workBook workSheetWithName:@"SHEET1"];

    for(uint32_t idx = 0; idx < num; idx ++) {
        [workSheet setWidth:2500 forColumn:idx defaultFormat:NULL];
        cell = [workSheet setCellAtRow:0 column:idx toDoubleValue:0];
    }

    [workBook writeToFile:filePath];
}

+ (void)saveLocalXLSFile:(NSString *)fileName withDataArray:(NSArray *)dataArr {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];

    JXLSCell *cell;
    JXLSWorkBook *workBook = [JXLSWorkBook new];
    JXLSWorkSheet *workSheet = [workBook workSheetWithName:@"SHEET1"];

    for (uint32_t i = 0; i < dataArr.count; i ++) {
        NSArray *rowArr = dataArr[i];
        for (uint32_t j = 0; j < rowArr.count; j ++) {
            if (i == 0) {
                [workSheet setWidth:2500 forColumn:j defaultFormat:NULL];
            }
            cell = [workSheet setCellAtRow:i column:j toDoubleValue:[rowArr[j] doubleValue]];
        }
    }

    [workBook writeToFile:filePath];
}

+ (void)createLocalRealm:(NSString *)fileName dataModel:(RLMObject *)data finishBlock:(void (^)())block {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        RLMRealm *realm = [RLMRealm realmWithPath:[self fullPathOfFile:[fileName stringByAppendingPathExtension:@"realm"]]];
        [realm beginWriteTransaction];
        [realm addObject:data];
        [realm commitWriteTransaction];

        dispatch_async(dispatch_get_main_queue(), ^{
            block();
        });

    });
}

+ (void)addData:(RLMObject *)data ToRealm:(NSString *)realmName {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        RLMRealm *realm = [RLMRealm realmWithPath:[self fullPathOfFile:realmName]];
        [realm beginWriteTransaction];
        [realm addObject:data];
        [realm commitWriteTransaction];
    });
}

// 有个 bug 关于传值和传引用的问题

+ (void)removeData:(RLMObject *)data InRealm:(NSString *)realmName {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        RLMRealm *realm = [RLMRealm realmWithPath:[self fullPathOfFile:realmName]];
        [realm beginWriteTransaction];
        [realm deleteObject:data];
        [realm commitWriteTransaction];
    });
}

+ (RLMRealm *)realmByName:(NSString *)name {
    RLMRealm *realm = [RLMRealm realmWithPath:[self fullPathOfFile:name]];
    return realm;
}

@end


text:
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { CheckStausPage } from './check-staus';

@NgModule({
  declarations: [
    CheckStausPage,
  ],
  imports: [
    IonicPageModule.forChild(CheckStausPage),
  ],
})
export class CheckStausPageModule {}


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using Duende.IdentityServer.Models;
using Rsk.Samples.IdentityServer4.AdminUiIntegration.Models;

namespace Rsk.Samples.IdentityServer4.AdminUiIntegration.Services
{
    public class ProcessConsentResult
    {
        public bool IsRedirect => RedirectUri != null;
        public string RedirectUri { get; set; }
        public Client Client { get; set; }

        public bool ShowView => ViewModel != null;
        public ConsentViewModel ViewModel { get; set; }

        public bool HasValidationError => ValidationError != null;
        public string ValidationError { get; set; }
    }
}


text:
import cPickle
import numpy as np
import numpy.random as npr
from collections import OrderedDict
import numexpr as ne

# theano business
import theano
import theano.tensor as T
#from theano.tensor.shared_randomstreams import RandomStreams as RandStream
from theano.sandbox.cuda.rng_curand import CURAND_RandomStreams as RandStream

# phil's sweetness
from DKCode import get_adam_updates, get_adadelta_updates
from LogPDFs import log_prob_bernoulli, log_prob_gaussian2, gaussian_kld
from HelperFuncs import to_fX

##############################################
# IMPLEMENTATION FOR A THING THAT DOES STUFF #
##############################################
#                                            #
# This thing does cool stuff, very deeply!   #
##############################################

class SRRModel(object):
    """
    Controller for training a sequential revelation and refinement model.

    Parameters:
        rng: numpy.random.RandomState (for reproducibility)
        x_out: the goal state for iterative refinement
        p_zi_given_xi: InfNet for stochastic part of step
        p_sip1_given_zi: HydraNet for deterministic part of step
        p_x_given_si: HydraNet for transform from s-space to x-space
        q_zi_given_xi: InfNet for the guide policy
        params: REQUIRED PARAMS SHOWN BELOW
                x_dim: dimension of observations to construct
                z_dim: dimension of latent space for policy wobble
                s_dim: dimension of space in which to perform construction
                use_p_x_given_si: boolean for whether to use p_x_given_si
                rev_sched: list of "revelation" blocks. each block is described
                           by the number of steps prior to revelation, and the
                           percentage of remaining pixels to reveal.
                rev_masks: matrix of revelation masks. the row i provides the
                           mask for iteration i of the srr loop. when this
                           argument is passed, rev_sched is ignored and the
                           revelation schedule is determined by rev_masks.
                step_type: either "add" or "jump"
                x_type: can be "bernoulli" or "gaussian"
                obs_transform: can be 'none' or 'sigmoid'
    """
    def __init__(self, rng=None,
            x_out=None, \
            p_zi_given_xi=None, \
            p_sip1_given_zi=None, \
            p_x_given_si=None, \
            q_zi_given_xi=None, \
            params=None, \
            shared_param_dicts=None):
        # setup a rng for this SRRModel
        self.rng = RandStream(rng.randint(100000))

        # grab the user-provided parameters
        self.params = params
        self.x_dim = self.params['x_dim']
        self.z_dim = self.params['z_dim']
        self.s_dim = self.params['s_dim']
        self.use_p_x_given_si = self.params['use_p_x_given_si']
        self.step_type = self.params['step_type']
        self.x_type = self.params['x_type']
        if self.use_p_x_given_si:
            print("Constructing hypotheses indirectly in s-space...")
        else:
            print("Constructing hypotheses directly in x-space...")
            assert(self.s_dim == self.x_dim)
        if 'obs_transform' in self.params:
            assert((self.params['obs_transform'] == 'sigmoid') or \
                    (self.params['obs_transform'] == 'none'))
            if self.params['obs_transform'] == 'sigmoid':
                self.obs_transform = lambda x: T.nnet.sigmoid(x)
            else:
                self.obs_transform = lambda x: x
        else:
            self.obs_transform = lambda x: T.nnet.sigmoid(x)
        if self.x_type == 'bernoulli':
            self.obs_transform = lambda x: T.nnet.sigmoid(x)
        self.shared_param_dicts = shared_param_dicts
        # Deal with revelation scheduling
        if ('rev_masks' in self.params) and (self.params['rev_masks'] is not None):
            rmp = self.params['rev_masks'][0].astype(theano.config.floatX)
            rmq = self.params['rev_masks'][1].astype(theano.config.floatX)
            self.rev_masks_p = theano.shared(value=rmp, name='srrm_rev_masks_p')
            self.rev_masks_q = theano.shared(value=rmq, name='srrm_rev_masks_q')
            self.rev_sched = None
            self.use_rev_masks = True
        else:
            self.rev_sched = self.params['rev_sched']
            self.rev_masks_p = None
            self.rev_masks_q = None
            self.use_rev_masks = False
            nice_nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
            # "validate" the set of revelation block descriptions
            for rev_block in self.rev_sched:
                assert(rev_block[0] in nice_nums)
                assert((rev_block[1] >= 0.0) and (rev_block[1] <= 1.01))
        assert((self.x_type == 'bernoulli') or (self.x_type == 'gaussian'))
        assert((self.step_type == 'add') or (self.step_type == 'jump'))

        # grab handles to the relevant networks
        self.p_zi_given_xi = p_zi_given_xi
        self.p_sip1_given_zi = p_sip1_given_zi
        self.p_x_given_si = p_x_given_si
        self.q_zi_given_xi = q_zi_given_xi

        # record the symbolic variables that will provide inputs to the
        # computation graph created for this SRRModel
        self.x_out = x_out           # target output for generation
        self.zi_zmuv = T.tensor3()   # ZMUV gauss noise for policy wobble
        self.p_masks = T.tensor3()   # revelation masks for primary policy
        self.q_masks = T.tensor3()   # revelation masks for guide policy
        if self.use_rev_masks:
            self.total_steps = self.params['rev_masks'][0].shape[0]
        else:
            self.total_steps = sum([rb[0] for rb in self.rev_sched])

        # setup switching variable for changing between sampling/training
        zero_ary = to_fX( np.zeros((1,)) )
        self.train_switch = theano.shared(value=zero_ary, name='srrm_train_switch')
        self.set_train_switch(1.0)

        if self.shared_param_dicts is None:
            # initialize the parameters "owned" by this model
            s0_init = to_fX( np.zeros((self.s_dim,)) )
            ss_init = to_fX( 0.5 * np.ones((self.total_steps,)) )
            self.s0 = theano.shared(value=s0_init, name='srrm_s0')
            self.obs_logvar = theano.shared(value=zero_ary, name='srrm_obs_logvar')
            self.bounded_logvar = 8.0 * T.tanh((1.0/8.0) * self.obs_logvar[0])
            self.step_scales = theano.shared(value=ss_init, name='srrm_step_scales')
            self.shared_param_dicts = {}
            self.shared_param_dicts['s0'] = self.s0
            self.shared_param_dicts['obs_logvar'] = self.obs_logvar
            self.shared_param_dicts['step_scales'] = self.step_scales
        else:
            # grab the parameters required by this model from a given dict
            self.s0 = self.shared_param_dicts['s0']
            self.obs_logvar = self.shared_param_dicts['obs_logvar']
            self.bounded_logvar = 8.0 * T.tanh((1.0/8.0) * self.obs_logvar[0])
            self.step_scales = self.shared_param_dicts['step_scales']

        ##################################################################
        # Setup the sequential revelation and refinement loop using scan #
        ##################################################################
        # ss: This is a sequence of scalars that will be used to rescale the
        #     "gradient" input to the primary and guide policies.
        #
        # zi_zmuv: This is a sequence of ZMUV gaussian samples that will be
        #          reparametrized to sample actions from the policies.
        #
        # p_masks: This is a sequence of "unmasking" masks. When one of these
        #          masking variables is 1, the corresponding value in self.x_out
        #          will be "revealed" to the primary policy. Prediction error
        #          is measured for a value only the first time it is revealed.
        #          Once revealed, a value remains "visible" to the policy.
        #          The final step should reveal all values.
        #
        # q_masks: This is a sequence of "unmasking" masks. These are similar
        #          to p_masks, but control which values are revealed to the
        #          guide policy. The guide policy masking sequence should be
        #          constructed to stay "ahead of" the primary policy's masking
        #          sequence. The guide policy needs to know which values will
        #          be revealed to the primary policy so that it can focus its
        #          reconstruction efforts on those values. Otherwise, the guide
        #          policy will immediately reconstruct the entire target.
        #
        # si: This is the current "belief state" for each trial in the training
        #     batch. The belief state is updated in each iteration, and passed
        #     forward through the recurrence.
        #
        # mi_p: This is the current revelation mask for the primary policy.
        #
        # mi_q: This is the current revelation mask for the guide policy.
        #
        def srr_step_func(ss, zi_zmuv, p_masks, q_masks, si, mi_p, mi_q):
            # transform the current belief state into an observation
            si_as_x = self._from_si_to_x(si)
            full_grad = T.log(1.0 + T.exp(ss)) * (self.x_out - si_as_x)

            # get the masked belief state and gradient for primary policy
            xi_for_p = (mi_p * self.x_out) + ((1.0 - mi_p) * si_as_x)
            grad_for_p = mi_p * full_grad

            # update the guide policy's revelation mask
            new_to_q = (1.0 - mi_q) * q_masks
            mip1_q = mi_q + new_to_q
            # get the masked belief state and gradient for guide policy
            #xi_for_q = (mip1_q * self.x_out) + ((1.0 - mip1_q) * si_as_x)
            xi_for_q = xi_for_p
            grad_for_q = mip1_q * full_grad

            # get samples of next zi, according to the primary policy
            zi_p_mean, zi_p_logvar = self.p_zi_given_xi.apply( \
                    T.horizontal_stack(xi_for_p, grad_for_p), \
                    do_samples=False)
            zi_p = zi_p_mean + (T.exp(0.5 * zi_p_logvar) * zi_zmuv)
            # get samples of next zi, according to the guide policy
            zi_q_mean, zi_q_logvar = self.q_zi_given_xi.apply( \
                    T.horizontal_stack(xi_for_q, grad_for_q), \
                    do_samples=False)
            zi_q = zi_q_mean + (T.exp(0.5 * zi_q_logvar) * zi_zmuv)
            # make zi samples that can be switched between zi_p and zi_q
            zi = ((self.train_switch[0] * zi_q) + \
                 ((1.0 - self.train_switch[0]) * zi_p))

            # compute relevant KLds for this step
            kldi_q2p = gaussian_kld(zi_q_mean, zi_q_logvar, \
                                    zi_p_mean, zi_p_logvar) # KL(q || p)
            kldi_p2q = gaussian_kld(zi_p_mean, zi_p_logvar, \
                                    zi_q_mean, zi_q_logvar) # KL(p || q)
            kldi_p2g = gaussian_kld(zi_p_mean, zi_p_logvar, \
                                    0.0, 0.0) # KL(p || N(0, I))

            # compute next si, given sampled zi (i.e. update the belief state)
            hydra_out = self.p_sip1_given_zi.apply(zi)
            si_step = hydra_out[0]
            if (self.step_type == 'jump'):
                # jump steps always do a full swap of belief state
                sip1 = si_step
            else:
                # additive steps adjust the belief state like an LSTM
                write_gate = T.nnet.sigmoid(2.0 + hydra_out[1])
                erase_gate = T.nnet.sigmoid(2.0 + hydra_out[2])
                sip1 = (erase_gate * si) + (write_gate * si_step)
            # update the primary policy's revelation mask
            new_to_p = (1.0 - mi_p) * p_masks
            mip1_p = mi_p + new_to_p
            # compute NLL only for the newly revealed values
            nlli = self._construct_nll_costs(sip1, self.x_out, new_to_p)
            # each loop iteration produces the following values:
            #   sip1: belief state at end of current step
            #   mip1_p: revealed values mask to use in next step (primary)
            #   mip1_q: revealed values mask to use in next step (guide)
            #   nlli: NLL for values revealed at end of current step
            #   kldi_q2p: KL(q || p) for the current step
            #   kldi_p2q: KL(p || q) for the current step
            #   kldi_p2g: KL(p || N(0,I)) for the current step
            return sip1, mip1_p, mip1_q, nlli, kldi_q2p, kldi_p2q, kldi_p2g

        # initialize belief state to self.s0
        self.s0_full = T.alloc(0.0, self.x_out.shape[0], self.s_dim) + self.s0
        # initialize revelation masks to 0 for all values in all trials
        self.m0_full = T.zeros_like(self.x_out)
        # setup initial values to pass to scan op
        outputs_init = [self.s0_full, self.m0_full, self.m0_full, \
                        None, None, None, None]
        sequences_init = [self.step_scales, self.zi_zmuv, self.p_masks, self.q_masks]
        # apply scan op for the sequential imputation loop
        self.scan_results, self.scan_updates = theano.scan(srr_step_func, \
                    outputs_info=outputs_init, \
                    sequences=sequences_init)

        # grab results of the scan op. all values are computed for each step
        self.si = self.scan_results[0]       # belief states
        self.mi_p = self.scan_results[1]     # primary revelation masks
        self.mi_q = self.scan_results[2]     # guide revelation masks
        self.nlli = self.scan_results[3]     # NLL on newly revealed values
        self.kldi_q2p = self.scan_results[4] # KL(q || p)
        self.kldi_p2q = self.scan_results[5] # KL(p || q)
        self.kldi_p2g = self.scan_results[6] # KL(p || N(0,I))

        ######################################################################
        # ALL SYMBOLIC VARS NEEDED FOR THE OBJECTIVE SHOULD NOW BE AVAILABLE #
        ######################################################################

        # shared var learning rate for generator and inferencer
        zero_ary = to_fX( np.zeros((1,)) )
        self.lr = theano.shared(value=zero_ary, name='srr_lr')
        # shared var momentum parameters for ADAM optimization
        self.mom_1 = theano.shared(value=zero_ary, name='srr_mom_1')
        self.mom_2 = theano.shared(value=zero_ary, name='srr_mom_2')
        # init parameters for controlling learning dynamics
        self.set_sgd_params()
        # init shared vars for weighting prior kld against reconstruction
        self.lam_kld_p = theano.shared(value=zero_ary, name='srr_lam_kld_p')
        self.lam_kld_q = theano.shared(value=zero_ary, name='srr_lam_kld_q')
        self.lam_kld_g = theano.shared(value=zero_ary, name='srr_lam_kld_g')
        self.lam_kld_s = theano.shared(value=zero_ary, name='srr_lam_kld_s')
        self.set_lam_kld(lam_kld_p=0.0, lam_kld_q=1.0, lam_kld_g=0.0, lam_kld_s=0.0)
        # init shared var for controlling l2 regularization on params
        self.lam_l2w = theano.shared(value=zero_ary, name='srr_lam_l2w')
        self.set_lam_l2w(1e-5)

        # grab all of the "optimizable" parameters from the base networks
        self.joint_params = [self.s0, self.obs_logvar, self.step_scales]
        self.joint_params.extend(self.p_zi_given_xi.mlp_params)
        self.joint_params.extend(self.p_sip1_given_zi.mlp_params)
        self.joint_params.extend(self.p_x_given_si.mlp_params)
        self.joint_params.extend(self.q_zi_given_xi.mlp_params)

        #################################
        # CONSTRUCT THE KLD-BASED COSTS #
        #################################
        self.kld_p, self.kld_q, self.kld_g, self.kld_s = self._construct_kld_costs(p=1.0)
        self.kld_costs = (self.lam_kld_p[0] * self.kld_p) + \
                         (self.lam_kld_q[0] * self.kld_q) + \
                         (self.lam_kld_g[0] * self.kld_g) + \
                         (self.lam_kld_s[0] * self.kld_s)
        self.kld_cost = T.mean(self.kld_costs)
        #################################
        # CONSTRUCT THE NLL-BASED COSTS #
        #################################
        self.nll_costs = T.sum(self.nlli, axis=0) # sum the per-step NLLs
        self.nll_cost = T.mean(self.nll_costs)
        self.nll_bounds = self.nll_costs.ravel() + self.kld_q.ravel()
        self.nll_bound = T.mean(self.nll_bounds)
        ########################################
        # CONSTRUCT THE REST OF THE JOINT COST #
        ########################################
        param_reg_cost = self._construct_reg_costs()
        self.reg_cost = self.lam_l2w[0] * param_reg_cost
        self.joint_cost = self.nll_cost + self.kld_cost + self.reg_cost
        ##############################
        # CONSTRUCT A PER-TRIAL COST #
        ##############################
        self.obs_costs = self.nll_costs + self.kld_costs

        # Get the gradient of the joint cost for all optimizable parameters
        print("Computing gradients of self.joint_cost...")
        self.joint_grads = OrderedDict()
        grad_list = T.grad(self.joint_cost, self.joint_params)
        for i, p in enumerate(self.joint_params):
            self.joint_grads[p] = grad_list[i]

        # Construct the updates for the generator and inferencer networks
        self.joint_updates = get_adam_updates(params=self.joint_params, \
                grads=self.joint_grads, alpha=self.lr, \
                beta1=self.mom_1, beta2=self.mom_2, \
                mom2_init=1e-3, smoothing=1e-5, max_grad_norm=10.0)
        for k, v in self.scan_updates.items():
            self.joint_updates[k] = v

        # Construct theano functions for training and diagnostic computations
        print("Compiling cost computer...")
        self.compute_raw_costs = self._construct_raw_costs()
        print("Compiling training function...")
        self.train_joint = self._construct_train_joint()
        print("Compiling free-energy sampler...")
        self.compute_fe_terms = self._construct_compute_fe_terms()
        print("Compiling sequence sampler...")
        self.sequence_sampler = self._construct_sequence_sampler()
        # make easy access points for some interesting parameters
        #self.gen_inf_weights = self.p_zi_given_xi.shared_layers[0].W
        return

    def _from_si_to_x(self, si):
        """
        Convert the given si from s-space to x-space.
        """
        if self.use_p_x_given_si:
            x_pre_trans, _ = self.p_x_given_si.apply(si)
        else:
            x_pre_trans = si
        x_post_trans = self.obs_transform(x_pre_trans)
        return x_post_trans

    def set_sgd_params(self, lr=0.01, mom_1=0.9, mom_2=0.999):
        """
        Set learning rate and momentum parameter for all updates.
        """
        zero_ary = np.zeros((1,))
        # set learning rate
        new_lr = zero_ary + lr
        self.lr.set_value(to_fX(new_lr))
        # set momentums (use first and second order "momentum")
        new_mom_1 = zero_ary + mom_1
        self.mom_1.set_value(to_fX(new_mom_1))
        new_mom_2 = zero_ary + mom_2
        self.mom_2.set_value(to_fX(new_mom_2))
        return

    def set_lam_kld(self, lam_kld_p=0.0, lam_kld_q=1.0, lam_kld_g=0.0, lam_kld_s=0.0):
        """
        Set the relative weight of prior KL-divergence vs. data likelihood.
        """
        zero_ary = np.zeros((1,))
        new_lam = zero_ary + lam_kld_p
        self.lam_kld_p.set_value(to_fX(new_lam))
        new_lam = zero_ary + lam_kld_q
        self.lam_kld_q.set_value(to_fX(new_lam))
        new_lam = zero_ary + lam_kld_g
        self.lam_kld_g.set_value(to_fX(new_lam))
        new_lam = zero_ary + lam_kld_s
        self.lam_kld_s.set_value(to_fX(new_lam))
        return

    def set_lam_l2w(self, lam_l2w=1e-3):
        """
        Set the relative strength of l2 regularization on network params.
        """
        zero_ary = np.zeros((1,))
        new_lam = zero_ary + lam_l2w
        self.lam_l2w.set_value(to_fX(new_lam))
        return

    def set_train_switch(self, switch_val=0.0):
        """
        Set the switch for changing between training and sampling behavior.
        """
        if (switch_val < 0.5):
            switch_val = 0.0
        else:
            switch_val = 1.0
        zero_ary = np.zeros((1,))
        new_val = zero_ary + switch_val
        self.train_switch.set_value(to_fX(new_val))
        return

    def _construct_zi_zmuv(self, xo):
        """
        Construct the necessary ZMUV gaussian samples for generating
        trajectories from this SRRModel, for input matrix xo.
        """
        zi_zmuv = self.rng.normal( \
                size=(self.total_steps, xo.shape[0], self.z_dim), \
                avg=0.0, std=1.0, dtype=theano.config.floatX)
        return zi_zmuv

    def _construct_rev_masks(self, xo):
        """
        Compute the sequential revelation masks for the input batch in xo.
        -- We need to construct mask sequences for both p and q.
        """
        if self.use_rev_masks:
            # make batch copies of self.rev_masks_p and self.rev_masks_q
            pmasks = self.rev_masks_p.dimshuffle(0,'x',1).repeat(xo.shape[0], axis=1)
            qmasks = self.rev_masks_q.dimshuffle(0,'x',1).repeat(xo.shape[0], axis=1)
        else:
            pm_list = []
            qm_list = []
            # make a zero mask that does nothing
            zero_mask = T.alloc(0.0, 1, xo.shape[0], xo.shape[1])
            # generate independently sampled masks for each revelation block
            for rb in self.rev_sched:
                # make a random binary mask with ones at rate rb[1]
                rand_vals = self.rng.uniform( \
                        size=(1, xo.shape[0], xo.shape[1]), \
                        low=0.0, high=1.0, dtype=theano.config.floatX)
                rand_mask = rand_vals < rb[1]
                # append the masks for this revleation block to the mask lists
                #
                # the guide policy (in q) gets to peek at the values that will be
                # revealed to the primary policy (in p) for the entire block. The
                # primary policy only gets to see these values at end of the final
                # step of the block. Within a given step, values are revealed to q
                # at the beginning of the step, and to p at the end.
                #
                # e.g. in a revelation block with only a single step, the guide
                # policy sees the values at the beginning of the step, which allows
                # it to guide the step. the primary policy only gets to see the
                # values at the end of the step.
                #
                # i.e. a standard variational auto-encoder is equivalent to a
                # sequential revelation and refinement model with only one
                # revelation block, which has one step and a reveal rate of 1.0.
                #
                for refine_step in range(rb[0]-1):
                    pm_list.append(zero_mask)
                    qm_list.append(rand_mask)
                pm_list.append(rand_mask)
                qm_list.append(rand_mask)
            # concatenate each mask list into a 3-tensor
            pmasks = T.cast(T.concatenate(pm_list, axis=0), 'floatX')
            qmasks = T.cast(T.concatenate(qm_list, axis=0), 'floatX')
        return [pmasks, qmasks]

    def _construct_nll_costs(self, si, xo, nll_mask):
        """
        Construct the negative log-likelihood part of free energy.
        -- only check NLL where nll_mask == 1
        """
        xh = self._from_si_to_x( si )
        if self.x_type == 'bernoulli':
            ll_costs = log_prob_bernoulli(xo, xh, mask=nll_mask)
        else:
            ll_costs = log_prob_gaussian2(xo, xh, \
                    log_vars=self.bounded_logvar, mask=nll_mask)
        nll_costs = -ll_costs.flatten()
        return nll_costs

    def _construct_kld_s(self, s_i, s_j):
        """
        Compute KL(s_i || s_j) -- assuming bernoullish outputs
        """
        x_i = self._from_si_to_x( s_i )
        x_j = self._from_si_to_x( s_j )
        kld_s = (x_i * (T.log(x_i)  - T.log(x_j))) + \
                ((1.0 - x_i) * (T.log(1.0-x_i) - T.log(1.0-x_j)))
        sum_kld = T.sum(kld_s, axis=1)
        return sum_kld

    def _construct_kld_costs(self, p=1.0):
        """
        Construct the policy KL-divergence part of cost to minimize.
        """
        kld_pis = []
        kld_qis = []
        kld_gis = []
        kld_sis = []
        s0 = 0.0*self.si[0] + self.s0
        for i in range(self.total_steps):
            kld_pis.append(T.sum(self.kldi_p2q[i]**p, axis=1))
            kld_qis.append(T.sum(self.kldi_q2p[i]**p, axis=1))
            kld_gis.append(T.sum(self.kldi_p2g[i]**p, axis=1))
            if i == 0:
                kld_sis.append(self._construct_kld_s(self.si[i], s0))
            else:
                kld_sis.append(self._construct_kld_s(self.si[i], self.si[i-1]))
        # compute the batch-wise costs
        kld_pi = sum(kld_pis)
        kld_qi = sum(kld_qis)
        kld_gi = sum(kld_gis)
        kld_si = sum(kld_sis)
        return [kld_pi, kld_qi, kld_gi, kld_si]

    def _construct_reg_costs(self):
        """
        Construct the cost for low-level basic regularization. E.g. for
        applying l2 regularization to the network activations and parameters.
        """
        param_reg_cost = sum([T.sum(p**2.0) for p in self.joint_params])
        return param_reg_cost

    def _construct_compute_fe_terms(self):
        """
        Construct a function for computing terms in variational free energy.
        """
        # setup some symbolic variables for theano to deal with
        xo = T.matrix()
        zizmuv = self._construct_zi_zmuv(xo)
        pmasks, qmasks = self._construct_rev_masks(xo)
        # construct values to output
        nll = self.nll_costs.flatten()
        kld = self.kld_q.flatten()
        # compile theano function for a one-sample free-energy estimate
        fe_term_sample = theano.function(inputs=[ xo ], \
                outputs=[nll, kld], \
                givens={self.x_out: xo, \
                        self.zi_zmuv: zizmuv, \
                        self.p_masks: pmasks, \
                        self.q_masks: qmasks}, \
                updates=self.scan_updates, \
                on_unused_input='ignore')
        # construct a wrapper function for multi-sample free-energy estimate
        def fe_term_estimator(XO, sample_count=20, use_guide_policy=True):
            # set model to desired generation mode
            old_switch = self.train_switch.get_value(borrow=False)
            if use_guide_policy:
                # take samples from the guide policy
                self.set_train_switch(switch_val=1.0)
            else:
                # take samples from the primary policy
                self.set_train_switch(switch_val=0.0)
            # compute a multi-sample estimate of variational free-energy
            nll_sum = np.zeros((XO.shape[0],))
            kld_sum = np.zeros((XO.shape[0],))
            for i in range(sample_count):
                result = fe_term_sample(XO)
                nll_sum += result[0].ravel()
                kld_sum += result[1].ravel()
            mean_nll = nll_sum / float(sample_count)
            mean_kld = kld_sum / float(sample_count)
            # set model back to either training or generation mode
            self.set_train_switch(switch_val=old_switch)
            if not use_guide_policy:
                # no KLd if samples are from the primary policy...
                mean_kld = 0.0 * mean_kld
            return [mean_nll, mean_kld]
        return fe_term_estimator

    def _construct_raw_costs(self):
        """
        Construct all the raw, i.e. not weighted by any lambdas, costs.
        """
        # setup some symbolic variables for theano to deal with
        xo = T.matrix()
        zizmuv = self._construct_zi_zmuv(xo)
        pmasks, qmasks = self._construct_rev_masks(xo)
        # compile theano function for computing the costs
        all_step_costs = [self.nlli, self.kldi_q2p, self.kldi_p2q, self.kldi_p2g]
        cost_func = theano.function(inputs=[ xo ], \
                    outputs=all_step_costs, \
                    givens={self.x_out: xo, \
                            self.zi_zmuv: zizmuv, \
                            self.p_masks: pmasks, \
                            self.q_masks: qmasks}, \
                    updates=self.scan_updates, \
                    on_unused_input='ignore')
        # make a function for computing batch-based estimates of costs.
        #   _step_nlls: the expected NLL cost for each step
        #   _step_klds: the expected KL(q||p) cost for each step
        #   _kld_q2p: the expected KL(q||p) cost for each latent dim
        #   _kld_p2q: the expected KL(p||q) cost for each latent dim
        #   _kld_p2g: the expected KL(p||N(0,I)) cost for each latent dim
        def raw_cost_computer(XO):
            _all_costs = cost_func(to_fX(XO))
            _kld_q2p = np.sum(np.mean(_all_costs[1], axis=1, keepdims=True), axis=0)
            _kld_p2q = np.sum(np.mean(_all_costs[2], axis=1, keepdims=True), axis=0)
            _kld_p2g = np.sum(np.mean(_all_costs[3], axis=1, keepdims=True), axis=0)
            _step_klds = np.mean(np.sum(_all_costs[1], axis=2, keepdims=True), axis=1)
            _step_klds = to_fX( np.asarray([k for k in _step_klds]) )
            _step_nlls = np.mean(_all_costs[0], axis=1)
            _step_nlls = to_fX( np.asarray([k for k in _step_nlls]) )
            results = [_step_nlls, _step_klds, _kld_q2p, _kld_p2q, _kld_p2g]
            return results
        return raw_cost_computer

    def _construct_train_joint(self):
        """
        Construct theano function to train all networks jointly.
        """
        # setup some symbolic variables for theano to deal with
        xo = T.matrix()
        zizmuv = self._construct_zi_zmuv(xo)
        pmasks, qmasks = self._construct_rev_masks(xo)
        # collect the outputs to return from this function
        outputs = [self.joint_cost, self.nll_bound, self.nll_cost, \
                   self.kld_cost, self.reg_cost, self.obs_costs]
        # compile the theano function
        func = theano.function(inputs=[ xo ], \
                outputs=outputs, \
                givens={self.x_out: xo, \
                        self.zi_zmuv: zizmuv, \
                        self.p_masks: pmasks, \
                        self.q_masks: qmasks}, \
                updates=self.joint_updates, \
                on_unused_input='ignore')
        return func

    def _construct_sequence_sampler(self):
        """
        Construct theano function to train all networks jointly.
        """
        # setup some symbolic variables for theano to deal with
        xo = T.matrix()
        zizmuv = self._construct_zi_zmuv(xo)
        pmasks, qmasks = self._construct_rev_masks(xo)
        # collect the outputs to return from this function
        states = [self._from_si_to_x(self.s0_full)] + \
                 [self._from_si_to_x(self.si[i]) for i in range(self.total_steps)]
        masks = [self.m0_full] + [self.mi_p[i] for i in range(self.total_steps)]
        outputs = states + masks
        # compile the theano function
        func = theano.function(inputs=[ xo ], \
                outputs=outputs, \
                givens={self.x_out: xo, \
                        self.zi_zmuv: zizmuv, \
                        self.p_masks: pmasks, \
                        self.q_masks: qmasks}, \
                updates=self.joint_updates, \
                on_unused_input='ignore')
        # visualize trajectories generated by the model
        def sample_func(XO, use_guide_policy=False):
            # set model to desired generation mode
            old_switch = self.train_switch.get_value(borrow=False)
            if use_guide_policy:
                # take samples from the guide policy
                self.set_train_switch(switch_val=1.0)
            else:
                # take samples from the primary policy
                self.set_train_switch(switch_val=0.0)
            # get belief states and masks generated by the scan loop
            scan_vals = func(to_fX(XO))
            step_count = self.total_steps + 1
            seq_shape = (step_count, XO.shape[0], XO.shape[1])
            xm_seq = np.zeros(seq_shape).astype(theano.config.floatX)
            xi_seq = np.zeros(seq_shape).astype(theano.config.floatX)
            mi_seq = np.zeros(seq_shape).astype(theano.config.floatX)
            for i in range(step_count):
                _xi = scan_vals[i]
                _mi = scan_vals[i + step_count]
                _xm = (_mi * XO) + ((1.0 - _mi) * _xi)
                xm_seq[i,:,:] = _xm
                xi_seq[i,:,:] = _xi
                mi_seq[i,:,:] = _mi
            # set model back to either training or generation mode
            self.set_train_switch(switch_val=old_switch)
            return [xm_seq, xi_seq, mi_seq]
        return sample_func

    def save_to_file(self, f_name=None):
        """
        Dump important stuff to a Python pickle, so that we can reload this
        model later.
        """
        assert(not (f_name is None))
        f_handle = file(f_name, 'wb')
        # dump the dict self.params, which just holds "simple" python values
        cPickle.dump(self.params, f_handle, protocol=-1)
        # make a copy of self.shared_param_dicts, with numpy arrays in place
        # of the theano shared variables
        numpy_param_dicts = {}
        for key in self.shared_param_dicts:
            numpy_ary = self.shared_param_dicts[key].get_value(borrow=False)
            numpy_param_dicts[key] = numpy_ary
        # dump the numpy version of self.shared_param_dicts to pickle file
        cPickle.dump(numpy_param_dicts, f_handle, protocol=-1)
        # get numpy dicts for each of the "child" models that we must save
        child_model_dicts = {}
        child_model_dicts['p_zi_given_xi'] = self.p_zi_given_xi.save_to_dict()
        child_model_dicts['p_sip1_given_zi'] = self.p_sip1_given_zi.save_to_dict()
        child_model_dicts['p_x_given_si'] = self.p_x_given_si.save_to_dict()
        child_model_dicts['q_zi_given_xi'] = self.q_zi_given_xi.save_to_dict()
        # dump the numpy child model dicts to the pickle file
        cPickle.dump(child_model_dicts, f_handle, protocol=-1)
        f_handle.close()
        return

def load_srrmodel_from_file(f_name=None, rng=None):
    """
    Load a clone of some previously trained model.
    """
    from InfNet import load_infnet_from_dict
    from HydraNet import load_hydranet_from_dict
    assert(not (f_name is None))
    pickle_file = open(f_name)
    # reload the basic python parameters
    self_dot_params = cPickle.load(pickle_file)
    # reload the theano shared parameters
    self_dot_numpy_param_dicts = cPickle.load(pickle_file)
    self_dot_shared_param_dicts = {}
    for key in self_dot_numpy_param_dicts:
        val = to_fX(self_dot_numpy_param_dicts[key])
        self_dot_shared_param_dicts[key] = theano.shared(val)
    # reload the child models
    child_model_dicts = cPickle.load(pickle_file)
    xd = T.matrix()
    p_zi_given_xi = load_infnet_from_dict( \
            child_model_dicts['p_zi_given_xi'], rng=rng, Xd=xd)
    p_sip1_given_zi = load_hydranet_from_dict( \
            child_model_dicts['p_sip1_given_zi'], rng=rng, Xd=xd)
    p_x_given_si = load_hydranet_from_dict( \
            child_model_dicts['p_x_given_si'], rng=rng, Xd=xd)
    q_zi_given_xi = load_infnet_from_dict( \
            child_model_dicts['q_zi_given_xi'], rng=rng, Xd=xd)
    # now, create a new SRRModel based on the loaded data
    xo = T.matrix()
    clone_net = SRRModel(rng=rng, \
                         x_out=xo, \
                         p_zi_given_xi=p_zi_given_xi, \
                         p_sip1_given_zi=p_sip1_given_zi, \
                         p_x_given_si=p_x_given_si, \
                         q_zi_given_xi=q_zi_given_xi, \
                         params=self_dot_params, \
                         shared_param_dicts=self_dot_shared_param_dicts)
    # helpful output
    print("==================================================")
    print("LOADED SRRModel WITH PARAMS:")
    for k in self_dot_params:
        print("    {0:s}: {1:s}".format(str(k), str(self_dot_params[k])))
    print("==================================================")
    return clone_net

if __name__=="__main__":
    print("Hello world!")

##############
# EYE BUFFER #
##############


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using KryBot.CommonResources.Localization;
using KryBot.Core;

namespace KryBot.Gui.WinFormsGui.Forms
{
    public partial class FormCookie : Form
    {
        private readonly Bot _bot;
        private readonly List<string> _names;
        private readonly string _site;

        public FormCookie(string site, List<string> names, Bot bot)
        {
            _site = site;
            _names = names;
            _bot = bot;
            InitializeComponent();
        }

        private void formCookie_Load(object sender, EventArgs e)
        {
            Text = _site;

            foreach (var name in _names)
            {
                var label = new Label
                {
                    Location = new Point(6, Controls.Count == 0 ? 6 : Controls[Controls.Count - 1].Location.Y + 26),
                    Text = name.Split(':')[0] + ':',
                    Width = 68
                };
                Controls.Add(label);

                var textbox = new TextBox
                {
                    Location =
                        new Point(10 + label.Size.Width,
                            Controls.Count == 1 ? 3 : Controls[Controls.Count - 2].Location.Y + 26),
                    Name = name.Split(':')[0],
                    Text = name.Split(':')[1],
                    Width = 194
                };
                Controls.Add(textbox);
            }

            var button = new Button
            {
                Location = new Point(6, Controls[Controls.Count - 1].Location.Y + 28),
                Width = 272,
                Text = strings.CookieForm_Save
            };
            button.Click += ButtonOnClick;
            Controls.Add(button);

            Height = Controls[Controls.Count - 1].Location.Y + 68;
        }

        private void ButtonOnClick(object sender, EventArgs eventArgs)
        {
            switch (_site)
            {
                case "GameMiner":
                    _bot.GameMiner.Cookies.Token = (Controls["token"] as TextBox)?.Text;
                    _bot.GameMiner.Cookies.Xsrf = (Controls["_xsrf"] as TextBox)?.Text;
                    _bot.GameMiner.UserAgent = (Controls["UserAgent"] as TextBox)?.Text;
                    _bot.GameMiner.Enabled = true;
                    _bot.Save();
                    ShowMessage();
                    break;

                case "SteamGifts":
                    _bot.SteamGifts.Cookies.PhpSessId = (Controls["PHPSESSID"] as TextBox)?.Text;
                    _bot.SteamGifts.UserAgent = (Controls["UserAgent"] as TextBox)?.Text;
                    _bot.SteamGifts.Enabled = true;
                    _bot.Save();
                    ShowMessage();
                    break;

                case "SteamCompanion":
                    _bot.SteamCompanion.Cookies.PhpSessId = (Controls["PHPSESSID"] as TextBox)?.Text;
                    _bot.SteamCompanion.Cookies.UserId = (Controls["userid"] as TextBox)?.Text;
                    _bot.SteamCompanion.Cookies.UserC = (Controls["userc"] as TextBox)?.Text;
                    _bot.SteamCompanion.Cookies.UserT = (Controls["usert"] as TextBox)?.Text;
                    _bot.SteamCompanion.Enabled = true;
                    _bot.Save();
                    ShowMessage();
                    break;

                case "SteamPortal":
                    _bot.SteamPortal.Cookies.PhpSessId = (Controls["PHPSESSID"] as TextBox)?.Text;
                    _bot.SteamPortal.Enabled = true;
                    _bot.Save();
                    ShowMessage();
                    break;

                case "Steamtrade":
                    _bot.SteamTrade.Cookies.PhpSessId = (Controls["PHPSESSID"] as TextBox)?.Text;
                    _bot.SteamTrade.Cookies.DlePassword = (Controls["dle_password"] as TextBox)?.Text;
                    _bot.SteamTrade.Cookies.DleUserId = (Controls["dle_user_id"] as TextBox)?.Text;
                    _bot.SteamTrade.Cookies.PassHash = (Controls["passhash"] as TextBox)?.Text;
                    _bot.SteamTrade.Enabled = true;
                    _bot.Save();
                    ShowMessage();
                    break;

                case "Steam":
                    _bot.Steam.Cookies.Login = (Controls["steamLogin"] as TextBox)?.Text;
                    _bot.Steam.Cookies.Sessid = (Controls["sessionid"] as TextBox)?.Text;
                    _bot.Steam.Enabled = true;
                    _bot.Save();
                    ShowMessage();
                    break;

                case "PlayBlink":
                    _bot.PlayBlink.Cookies.PhpSessId = (Controls["PHPSESSID"] as TextBox)?.Text;
                    _bot.PlayBlink.Enabled = true;
                    _bot.Save();
                    ShowMessage();
                    break;
            }

            Close();
        }

        private void ShowMessage()
        {
            MessageBox.Show(strings.CookieForm_MustRestart, strings.Information,
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}


text:
#ifndef __GOBEX_H
#define __GOBEX_H

#include <stdarg.h>
#include <glib.h>

#include <gobex/gobex-defs.h>
#include <gobex/gobex-packet.h>

typedef enum {
	G_OBEX_TRANSPORT_STREAM,
	G_OBEX_TRANSPORT_PACKET,
} GObexTransportType;

typedef struct _GObex GObex;

typedef void (*GObexFunc) (GObex *obex, GError *err, gpointer user_data);
typedef void (*GObexRequestFunc) (GObex *obex, GObexPacket *req,
							gpointer user_data);
typedef void (*GObexResponseFunc) (GObex *obex, GError *err, GObexPacket *rsp,
							gpointer user_data);

gboolean g_obex_send(GObex *obex, GObexPacket *pkt, GError **err);

guint g_obex_send_req(GObex *obex, GObexPacket *req, int timeout,
			GObexResponseFunc func, gpointer user_data,
			GError **err);
gboolean g_obex_cancel_req(GObex *obex, guint req_id,
						gboolean remove_callback);

gboolean g_obex_send_rsp(GObex *obex, guint8 rspcode, GError **err,
						guint8 first_hdr_type, ...);

void g_obex_set_disconnect_function(GObex *obex, GObexFunc func,
							gpointer user_data);
guint g_obex_add_request_function(GObex *obex, guint8 opcode,
						GObexRequestFunc func,
						gpointer user_data);
gboolean g_obex_remove_request_function(GObex *obex, guint id);

void g_obex_suspend(GObex *obex);
void g_obex_resume(GObex *obex);
gboolean g_obex_srm_active(GObex *obex);

GObex *g_obex_new(GIOChannel *io, GObexTransportType transport_type,
						gssize rx_mtu, gssize tx_mtu);

GObex *g_obex_ref(GObex *obex);
void g_obex_unref(GObex *obex);

/* High level client functions */

guint g_obex_connect(GObex *obex, GObexResponseFunc func, gpointer user_data,
				GError **err, guint8 first_hdr_id, ...);

guint g_obex_setpath(GObex *obex, const char *path, GObexResponseFunc func,
					gpointer user_data, GError **err);

guint g_obex_mkdir(GObex *obex, const char *path, GObexResponseFunc func,
					gpointer user_data, GError **err);

guint g_obex_delete(GObex *obex, const char *name, GObexResponseFunc func,
					gpointer user_data, GError **err);

guint g_obex_copy(GObex *obex, const char *name, const char *dest,
			GObexResponseFunc func, gpointer user_data,
			GError **err);

guint g_obex_move(GObex *obex, const char *name, const char *dest,
			GObexResponseFunc func, gpointer user_data,
			GError **err);

/* Transfer related high-level functions */

guint g_obex_put_req(GObex *obex, GObexDataProducer data_func,
			GObexFunc complete_func, gpointer user_data,
			GError **err, guint8 first_hdr_id, ...);

guint g_obex_put_req_pkt(GObex *obex, GObexPacket *req,
			GObexDataProducer data_func, GObexFunc complete_func,
			gpointer user_data, GError **err);

guint g_obex_get_req(GObex *obex, GObexDataConsumer data_func,
			GObexFunc complete_func, gpointer user_data,
			GError **err, guint8 first_hdr_id, ...);

guint g_obex_get_req_pkt(GObex *obex, GObexPacket *req,
			GObexDataConsumer data_func, GObexFunc complete_func,
			gpointer user_data, GError **err);

guint g_obex_put_rsp(GObex *obex, GObexPacket *req,
			GObexDataConsumer data_func, GObexFunc complete_func,
			gpointer user_data, GError **err,
			guint8 first_hdr_id, ...);

guint g_obex_get_rsp(GObex *obex, GObexDataProducer data_func,
			GObexFunc complete_func, gpointer user_data,
			GError **err, guint8 first_hdr_id, ...);

guint g_obex_get_rsp_pkt(GObex *obex, GObexPacket *rsp,
			GObexDataProducer data_func, GObexFunc complete_func,
			gpointer user_data, GError **err);

gboolean g_obex_cancel_transfer(guint id, GObexFunc complete_func,
							gpointer user_data);

const char *g_obex_strerror(guint8 err_code);
guint8 g_obex_errno_to_rsp(int err);

#endif /* __GOBEX_H */


text:
package org.jvnet.zephyr.continuation;

final class ThreadContinuation extends Continuation {

    private static final long serialVersionUID = 1L;

    private final ContinuationThread thread;

    ThreadContinuation(Runnable target) {
        thread = new ContinuationThread(target);
        thread.setName(toString());
        thread.setDaemon(true);
        thread.start();
    }

    @Override
    public boolean resume() {
        return thread.resumeContinuation();
    }
}


text:
namespace GLib {

	using System;
	using System.Runtime.InteropServices;

#region Autogenerated code
	[GLib.GType (typeof (GLib.PasswordSaveGType))]
	public enum PasswordSave {

		Never,
		ForSession,
		Permanently,
	}

	internal class PasswordSaveGType {
		[DllImport ("libgio-2.0-0.dll")]
		static extern IntPtr g_password_save_get_type ();

		public static GLib.GType GType {
			get {
				return new GLib.GType (g_password_save_get_type ());
			}
		}
	}
#endregion
}


text:
/**
 * @namespace Phaser.Types.Core
 */