text:
<?php
/**
 * Created by PhpStorm.
 * User: stas
 * Date: 17.01.16
 * Time: 18:55
 */

namespace CoreBundle\Model\Request\Call;

use CoreBundle\Model\Request\SecurityRequestAwareTrait;
use CoreBundle\Model\Request\SecurityRequestInterface;
use JMS\Serializer\Annotation as JMS;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class CallDeleteRemoveRequest
 * @package CoreBundle\Model\Request\Call
 */
class CallDeleteRemoveRequest extends CallRequest implements SecurityRequestInterface
{
    use SecurityRequestAwareTrait;

    /**
     * @var string
     *
     * @JMS\Expose()
     * @JMS\Type("string")
     *
     * @Assert\NotBlank(
     *     message = "Call id is required for this request"
     * )
     */
    private $callId;

    /**
     * @return string
     */
    public function getCallId()
    {
        return $this->callId;
    }

    /**
     * @param string $callId
     */
    public function setCallId($callId)
    {
        $this->callId = $callId;
    }
}


text:
define([
  'files/ImportOBJ',
  'files/ImportSGL',
  'files/ImportPLY',
  'files/ImportSTL'
], function (ImportOBJ, ImportSGL, ImportPLY, ImportSTL) {

  'use strict';

  var Import = {
    importOBJ: ImportOBJ.importOBJ,
    importSGL: ImportSGL.importSGL,
    importPLY: ImportPLY.importPLY,
    importSTL: ImportSTL.importSTL
  };

  return Import;
});

redpajama_set_name: RedPajamaGithub


text:
package fsm.dao.impl;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import fsm.dao.EmployeeDao;
import fsm.model.domain.Employee;

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public Integer addEmployee(Employee employee) {

		Session session = sessionFactory.getCurrentSession();
		Integer employeeID = (Integer) session.save(employee);
		return employeeID;

	}

	@Override
	public void removeEmployee(int employeeId) {

		Session session = sessionFactory.getCurrentSession();
		Employee employee = getEmployeeById(employeeId);

		if (employee != null) {
			session.delete(employee);
		}

	}

	@Override
	public void updateEmployee(Employee employee) {

		Session session = sessionFactory.getCurrentSession();
		session.update(employee);

	}

	@Override
	public Employee getEmployeeById(int employeeId) {

		Session session = sessionFactory.getCurrentSession();
		Employee employee = (Employee) session.get(Employee.class, employeeId);
		return employee;

	}

	@Override
	public Employee getEmployeeByBrid(String brid) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Employee.class);
		criteria.add(Restrictions.eq("brid", brid));
		Employee employee = (Employee) criteria.uniqueResult();
		return employee;
	}

	@Override
	public List<Employee> getAllEmployees() {

		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Employee.class);
		return criteria.list();

	}

}


text:
格式说明:

;lt ;lgt html

[] 属性

. class

## 排版 ##

{% highlight html %}

..

.text-left .text-right .text-center

.text-muted .text-primary .text-success
.text-info .text-warning .text-danger

 [title] .initialism

<adree>

<blokcquote>   .pull-right .blockquote-reverse

 .list-unstyled .list-inline

 .dl-horizontal

更多排版类:
	.small
	.text-justify
	.text-lowercase
	.text-uppercase
	.text-capitalize

 .pre-scrolllable
{% endhighlight%}

## Bootstrap 网格系统 ##

{% highlight html %}
.col-xs-*
.col-sm-*  .col-lg-*
{% endhighlight%}

## Bootstrap 代码 ##

{% highlight html %}
 单行

  多行
{% endhighlight%}

## Bootstrap 表格 ##

{% highlight html %}

	.table .table-striped
	.table-bordered
	.table-hover
	.table-condensed

 .active .success .warning .danger
	 .table-responsive
{% endhighlight%}

## Bootstrap 表单 ##

{% highlight html %}
<form> [role="form"]
	.form-group
	.form-control -- 单行输入框
	.form-inline

<lable> .sr-only 隐藏

<form> .form-horizontal
 .control-label
	.checkbox-inline
	.radio-inline

<select> [mutiple] .form-control

<form> .form-control-static 静态文本

<input [disabled] :has()>
.has-success .has-warning .has-error

<fieldset [disabled]>

<input [placeholder('')]>

.input-lg .input-sm .col-lg-*

<input>
{% endhighlight%}

## Bootstrap 按钮 ##

{% highlight html %}
<.btn>

.btn-primary .btn-success .btn-info
.btn-warning .btn-danger .btn-link

.btn-lg .btn-sm .btn-xs .btn-block

.active  .disabled( need js)

{% endhighlight%}

## Bootstrap 图像 ##

{% highlight html %}
.img-rounded .img-circle .img-thumbnail
{% endhighlight%}

## Bootstrap 帮助器类 ##

{% highlight html %}
.close  关闭图标
.caret  插入图标

.pull-left     快速浮动
.pull-right

.center-block
.clear-fix      清除浮动

.show
.hidden

.sr-only  屏幕阅读器-only
{% endhighlight%}

## Bootstrap响应式工具 ##

{% highlight html %}
.visible-xs .visible-sm ...

.hidden-xs  .hidden-sm ...

.visible-print
.hidden-print
{% endhighlight%}

## .divider 分隔线 ##

# 布局组件 #

## 字形图标 ##
.glyphicon

## 下拉菜单 ##

{% highlight html %}

 .dropdown-menu
.dropdown  .dropdown-header
[data-toggle= "dropdown"]

{% endhighlight%}

## 按钮组 ##
.btn-toolbar
.btn-group(-lg)
.btn-group-vertical

## 按钮下拉菜单 ##

[data-toggle] .dropdown-menu
.btn-(lg)

上拉  .btn-group  .dropup

## 输入框组 ##

{% highlight html %}
.input-group
.input-gorup-lg

.input-group
	div
{% endhighlight%}

## 导航元素 ##

{% highlight html %}

 .nav-tabs .active .nav-pills .nav-stacked
	.nav-justified 两端对齐

<li .dropdown

>
{% endhighlight%}

## 导航栏 ##

{% highlight html %}

<.navbar-header >

.collapse .navbar-collapse #..
.navbar-toggle [data-toggle(collapse)]
	[date-target(#example)]

表单:
<form .navbar-form>

.navbor-btn

.navbar-left  .navbar-right
.navbar .navbar-fixed-right>

<navbar .navbar-fixedtop>
	    .navbar-fixed-bottom
	.navbar-static-top
	.navbar-inverse
{% endhighlight%}

## 面包屑导航 ##

.breadcrumb

## 分页 ##
.pagination .disabled .active
.pagination-lg(sm)

翻页

.pager .previous .next

.disabled

## 标签 ##
.label
.label-default .label-primary .label-success
.label-info .label-warning
.label-danger

## 微章 ##

{% highlight html %}

{% endhighlight%}

## 超大屏幕 ##
.jumbotron
.container

## 网页标题 ##
.page-header

## 缩略图 ##
.thumbnail

## 警告Alerts ##
.alert

.alert-success .alert-info
.alert-warning .alert-danger

.alert-dismissable
[data-miss(alert)]

## 进度条 ##
.progress-bar-(success|info|warning|danger)

.progress ;lt .progress-bar ;lt [style(60%)]
.progress-striped .active 可堆叠

## 多媒体对象Media Object ##
.media

.midia ;lt a

.media-body ;lt .media-header

## 列表组 ##
ul .list-group ;li list-group-item
li .badge

div a .list-group-item
;lt .list-group-item-heading .list-group-item-text

## 面板Panels ##
.panel

.panel-default ;lt .panel-heading ;lt h1-h6 .panel-text
	               .panel-body
				   .panel-fotter

.panel-primary .panel-success .panel-info
.panel-warning .panel-danger

.table .list-group

## Well ##
.well

.well-lg .well-sm

# Bootstrap插件 #
[data]
	$(document).off('.data-api')
	$(documnet).off('.alert .data-api')

## 模态框 ##
[data-toggle]='modol' [data-target]="#"(or href="#")
	.modol .fade [aria-hidden(true)]
[area-labelleedby('myModolLabel')]

.modol-header # .modol-body .modol-footer
.close [data-dismiss(modal)]

$(function(){$('#').modol({show;false})});

{% highlight html %}
[data-backdrop] [data-keyboard]
[data-show] [data-remote]

事件:
 show.bs.modol shown.bs.modol
 hide.bs.modol hidden.bs.modol
{% endhighlight%}

## 下拉菜单Dropdown ##
[data-toggle(dropdown)]

$('x').dropdown('toggle')

## 滚动监听 Scrollspy ##

{% highlight html %}
[data-spy(scroll)]
[data-target()]
[data-offset(number)]
方法: scrollspy('refresh')
事件: active.bs.scrollspy
{% endhighlight%}

## 标签页Tab ##

{% highlight html %}
[data-toggle='tab'] or [data-toggle(pill)]
ul (.nav nav-tabs)(.nav .nav-pills)
.tab-pane .fade .in(第一个必须)
$('#myTab li:eq(1) a').tab('show')

事件 show.bs.tab shown.bs.tab
{% endhighlight%}

## 工具提示Tooltip ## 必须激活
选项:

{% highlight html %}
[data-toggle(tooltip)]
$('#x').tooltip(*options);

[data-placement]
[data-html]
[data-animation]
[data-selector]
[data-title]
[data-trigger]
[data-content]
[data-delay]
[data-container]

方法:
options toggle show hide destroy
	$('.x').tooltip({html:true});

事件:
show.bs.tooltip
shown.bs.tooltip
hide.bs.tooltip
hidden.bs.tooltip
{% endhighlight%}

## 弹出框 ##
[data-toggle(popover)]
$('#x').popover(option);

选项:[data-*]:
animation html placement selector titel trigger delay container

方法:
  $().popover(options)
toggle show hide destroy
  $().popover('toggle')

事件: ().bs.popover
show.bs.popover
shown.bs.popover
hide.bs.popover
hidden.bs.popover

## 警告框Alert ##
.alert(.alert-success) [data-dismiss(alert)]
(.fade)(.in)

方法:

> .alert() 带关闭功能

> .alert('close')

事件 *-bs-alert:
close closed

## 按钮Button ##
加载状态
[data-loading-text('Loading')]

[data-toggle('button')]

.data-group [data-toggle('buttons')]

用法:$('.btn').button()

方法:button():

'toggle' 'loading' 'reset' 'string' 'complete'

[data-complete-texed('....')]

## 折叠Collapse ##

[data-toggle(collpse)]

href or [data-target]

[data-parent]

用法:

.collapse | .collapse .in | .collapsing

选项:[data-*]:

parent toggle

方法:collapse(option):

toggle show hide

.collapse-*(success|info|warning|dange|primary)

事件: *.bs.collapse:

show shown hide hidden

## 轮播Carousel ##

* carousel .slide
	* ol .carsel-indications
		* li
[data-target] [data-slide-to]

	* .carouse(-inner ;lt .item (;lt .carousel-caption))
	* a .carousel(-control .left|.light [href])

用法: [data-slide (prev/next)]
[data-slide-to(n)]
[data-ride('carousel')]

选项 [data-*] interval @n/false
pause @hover
wrap @boolen

方法 .carousel(options): 'cycle' 'pause' @n
'prev' 'next'

事件 *bs.carousel slide slid

## Bootstrap 附加导航 Affix ##
{% highlight html %}
[data-spy('affix')] [data-offset-top'n']

	$().affix({
		offset:{
			top:100,
			bottom: function(){
				}
			}
	});

CSS定位:offset [data-offset] @ n

offset:{top:10}

offset:{top:10,bottom:5}
{% endhighlight%}


text:
define({
  "serviceURL": "adresa URL služby",
  "defaultTitle": "Výchozí název",
  "defaultAuthor": "Výchozí autor",
  "defaultCopyright": "Výchozí autorská práva",
  "defaultFormat": "Výchozí formát",
  "defaultLayout": "Výchozí rozvržení",
  "warning": "Nesprávný vstup",
  "ok": "OK"
});


text:
  <?php
    require_once '../Assets/estilo.php';

    require_once '../Controllers/UsersController.class.php';

    require_once '../Controllers/AdvertenciasController.class.php';

    session_start();

    if(!isset($_SESSION["auth"])) {
        header("location:../view/login.php");
    }

  ?>

    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

    </button>
    PCD EcompJr

Editar Advertência

 <form action="../routes/routes.php" method = "POST" >

      <?php
        $warningID = $_GET['idWarning'];

        $atributos = AdvertenciasController::searchForWarning($warningID);
        $warning =  new Warning($atributos['data'], $atributos['reason'], $atributos['points'], $atributos['responsible'],
                        $atributos['dismissed'], $atributos['memberId'], $atributos['id']);

        $date = $warning->getDate();
        $reason = $warning->getReason();
        $points = $warning->getPoints();
        $responsible = $warning->getResponsible();
        $dismissed = $warning->getDismissed();
        $memberID = $warning->getMemberId();

      echo "

        Data:
        <input type='date' class='form-control' id='date' name='date' placeholder = $date value = $date required='required'>

";

      echo "

        Motivo:
        <input type='text' class='form-control' id='reason' name='reason' placeholder = $reason value = $reason required='required'>

";

      echo "

        Pontos:
        <input type='number' class='form-control' id='points' name='points'  max ='20' min ='0' placeholder = $points value = $points required='required'>

";

      echo "

        Responsável:
        <input type='text' class='form-control' id='responsible' name='responsible' placeholder = $responsible value=$responsible required='required'>

";

      echo "

        Indeferida:
        <select name='dismissed' class='form-control' placeholder='indeferida' id='dismised' required data-validation-required-message='Por favor, selecione uma das opções.' required='required'>
          if($dismissed == true){
              <option value='true' selected>Sim</option>
              <option value='false'>Não</option>
          }else{
            <option value='true' >Sim</option>
            <option value='false' selected >Não</option>
          }
        </select>";

      echo "

        <input type='hidden' class='form-control' id='memberID' name='memberID' placeholder = $memberID value=$memberID>
        <input type='hidden' class='form-control' id='warningID' name='warningID' placeholder = $warningID value=$warningID>

";

      echo "
";

echo "
";

  echo "
";
  echo "

      <button type='submit' class='btn btn-primary' name = 'editWarningAttempt' id ='editWarningAttempt'>Editar</button>
      <button type='submit' class='btn btn-danger' name = 'deleteWarningAttempt' id ='deleteWarningAttempt'>Deletar</button>
      Cancelar

";
?>
</form>

  <?php
     // require_once 'footer.php';
    ?>


text:
require "guild"

function post()
    if not session:isLogged() then
        http:redirect("/")
        return
    end

    local guild = db:singleQuery("SELECT id, name, ownerid, id FROM guilds WHERE name = ?", http.postValues["guild-name"])

    if guild == nil then
        http:redirect("/")
        return
    end

    if not isGuildOwner(session:loggedAccount().ID, guild) then
        http:redirect("/")
        return
    end

    local character = db:singleQuery("SELECT c.id as rankId, c.level, a.id FROM players a, guild_membership b, guild_ranks c WHERE c.id = b.rank_id AND b.player_id = a.id AND b.guild_id = ? AND a.name = ?", guild.id, http.postValues["character-name"])

    if character == nil then
        http:redirect("/")
        return
    end

    if tonumber(character.level) ~= 1 then
        http:redirect("/")
        return
    end

    local nextRank = db:singleQuery("SELECT id FROM guild_ranks WHERE level = 2 AND guild_id = ?", guild.id)

    if nextRank == nil then
        http:redirect("/")
        return
    end

    db:execute("UPDATE guild_membership SET rank_id = ? WHERE player_id = ? AND guild_id = ?", nextRank.id, character.id, guild.id)

    session:setFlash("success", "Member promoted")
    http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name))
end


text:
import config from '../universal/config';

import createMainRoutes from '../universal/routes/mainRoutes';
import createAppRoutes from '../universal/routes/appRoutes';
import createEventRoutes from '../universal/routes/eventRoutes';
import createUserRoutes from '../universal/routes/userRoutes';

import createHome from './components/home/home';
import createSelectApp from './components/selectApp/selectApp';
import createHeader from './components/header/header';
import createEvents from './components/events/events';
import createEventDetail from './components/eventDetail/eventDetail';
import createEventAttendance from './components/eventAttendance/eventAttendance';
import createAppHeader from './components/appHeader/appHeader';
import createUserDetail from './components/userDetail/userDetail';

createMainRoutes(FlowRouter);
createAppRoutes(FlowRouter);
createEventRoutes(FlowRouter);
createUserRoutes(FlowRouter);

createHome(Template);
createHeader(Template);
createSelectApp(Template);
createEvents(Template);
createEventDetail(Template);
createEventAttendance(Template);
createAppHeader(Template);
createUserDetail(Template);


text:
A Simple Syntax Tree Library for SalesForce Apex.

This library is experimental and in development.

DO NOT USE IN PRODUCTION SOFTWARE


text:
package validatedInputII;

import java.util.ArrayList;

public class Tester
{
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void main(String[] args)
	{
		ArrayList<String> keys = new ArrayList();
		keys.add("Hello");
		keys.add("Goodbye");
		keys.add("P@ssw0rd");
		keys.add("Sriram123");
		ValidatedInput vi = new ValidatedInput();
		SimplePasswordValidator pass = new SimplePasswordValidator(keys);
		if(vi.getMatch(pass, 5))
			System.out.println("Password is Correct");
		else
			System.out.println("Out of Attempts");
	}
}


text:
import { Injectable } from '@angular/core';
import { StateNode } from '@skyux/list-builder-common';

import { ListFiltersOrchestrator } from './filters/filters.orchestrator';
import { ListItemsOrchestrator } from './items/items.orchestrator';
import { ListStateModel } from './list-state.model';
import { ListStateDispatcher } from './list-state.rxstate';
import { ListPagingOrchestrator } from './paging/paging.orchestrator';
import { ListSearchOrchestrator } from './search/search.orchestrator';
import { ListSelectedOrchestrator } from './selected/selected.orchestrator';
import { ListSortOrchestrator } from './sort/sort.orchestrator';
import { ListToolbarOrchestrator } from './toolbar/toolbar.orchestrator';
import { ListViewsOrchestrator } from './views/views.orchestrator';

/**
 * @internal
 * @deprecated
 */
@Injectable()
export class ListState extends StateNode<ListStateModel> {
  constructor(dispatcher: ListStateDispatcher) {
    super(new ListStateModel(), dispatcher);

    this.register('filters', ListFiltersOrchestrator)
      .register('items', ListItemsOrchestrator)
      .register('paging', ListPagingOrchestrator)
      .register('search', ListSearchOrchestrator)
      .register('sort', ListSortOrchestrator)
      .register('toolbar', ListToolbarOrchestrator)
      .register('views', ListViewsOrchestrator)
      .register('selected', ListSelectedOrchestrator)
      .begin();
  }
}


text:
import { PropTypes } from 'react';

/* IconList & IconListItem */
const iconListItem = PropTypes.shape({ // eslint-disable-line import/prefer-default-export
  key: PropTypes.string.isRequired,
  title: PropTypes.string.isRequired,
  group: PropTypes.string.isRequired,
  image: PropTypes.string.isRequired,
  ref: PropTypes.string,
  withVersion: PropTypes.bool,
});

export const IconListPropTypes = {
  items: PropTypes.arrayOf(iconListItem).isRequired,
};

export const IconListItemPropTypes = {
  item: iconListItem,
};


text:
package com.thebluealliance.androidclient.gcm;

import android.content.SharedPreferences;

import com.thebluealliance.androidclient.config.AppConfig;

import javax.inject.Singleton;

@Singleton
public class GcmController {

    public static final String OS_ANDROID = "android";
    public static final String PROPERTY_GCM_REG_ID = "gcm_registration_id";
    public static final String PREF_SENDER_ID = "gcm_senderId";

    private final AppConfig mAppConfig;
    private final SharedPreferences mSharedPreferences;

    public GcmController(AppConfig appConfig, SharedPreferences sharedPreferences) {
        mAppConfig = appConfig;
        mSharedPreferences = sharedPreferences;
    }

    public String getSenderId() {
        return mAppConfig.getString(PREF_SENDER_ID);
    }

    public String getRegistrationId() {
        return mSharedPreferences.getString(PROPERTY_GCM_REG_ID, "");
    }

    public void storeRegistrationId(String id) {
        mSharedPreferences.edit().putString(PROPERTY_GCM_REG_ID, id).apply();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;

namespace Vita.Data.Linq.Translation.Expressions
{
    public abstract class OperandsMutableSqlExpression : SqlExpression
    {
        protected OperandsMutableSqlExpression(SqlExpressionType sqlExpressionType, Type type, IList<Expression> operands)
            : base(sqlExpressionType, type)
        {
            if(operands !=null)
              this.Operands.AddRange(operands);
        }

        /// <summary>
        /// Must be implemented by inheritors. I had no better name. Suggestions welcome
        /// </summary>
        /// <param name="operands"></param>
        /// <returns></returns>
        protected abstract Expression Mutate2(IList<Expression> operands);

        public override Expression Mutate(IList<Expression> newOperands)
        {
            return Mutate2(newOperands);
        }
    }
}


text:
{% load i18n %}{% load staticfiles %}

  {% trans "Set your favorite style!" %}

    {% include "lasana/style.html" with name="Original" %}
    {% include "lasana/style.html" with name="Cute" %}
    {% include "lasana/style.html" with name="Dark" %}


text:
using System;
using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal static partial class Advapi32
    {
        [DllImport(Interop.Libraries.Advapi32)]
        internal static extern unsafe int EventWriteTransfer(
                ulong registrationHandle,
                void* eventDescriptor,
                Guid* activityId,
                Guid* relatedActivityId,
                int userDataCount,
                void* userData
                );
    }
}


text:
package com.openxc.units;

/**
 * A quantitative type of {@link Unit}.
 *
 * All quantitative children of {@link Unit} extend from this abstract class,
 * which encapsulates common logic for converting among different numerical
 * values.
 */
public abstract class Quantity<T extends Number> extends Unit {
    private T mValue;

    /**
     * Construct an instance of Quantity with the value.
     *
     * @param value a quantitative Unit value.
     */
    public Quantity(T value) {
        mValue = value;
    }

    @Override
    public boolean equals(Object obj) {
        if(!super.equals(obj)) {
            return false;
        }

        @SuppressWarnings("unchecked")
        final Quantity<T> other = (Quantity<T>) obj;
        return mValue.equals(other.mValue);
    }

    public double doubleValue() {
        return mValue.doubleValue();
    }

    @Override
    public Object getSerializedValue() {
        return doubleValue();
    }

    public int intValue() {
        return mValue.intValue();
    }

    public String getTypeString() {
        return "";
    }

    @Override
    public String toString() {
        return mValue.toString() + " " + getTypeString();
    }
}


text:
var _ = require('underscore');
var assert = require('assert');
var fs = require('fs');
var util = require('util');

var AuthenticationTestUtil = require('oae-authentication/lib/test/util');
var AuthzInvitationsDAO = require('oae-authz/lib/invitations/dao');
var ConfigTestUtil = require('oae-config/lib/test/util');
var EmailTestsUtil = require('oae-email/lib/test/util');
var RestAPI = require('oae-rest');
var TenantsTestUtil = require('oae-tenants/lib/test/util');
var TestsUtil = require('oae-tests');

var PrincipalsAPI = require('oae-principals');
var PrincipalsTestUtil = require('oae-principals/lib/test/util');

describe('User emails', function() {

    // REST contexts we can use to do REST requests
    var camAdminRestContext = null;
    var gtAdminRestContext = null;
    var anonymousRestContext = null;
    var globalAdminRestContext = null;

    beforeEach(function(callback) {
        anonymousRestContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
        camAdminRestContext = TestsUtil.createTenantAdminRestContext(global.oaeTests.tenants.cam.host);
        gtAdminRestContext = TestsUtil.createTenantAdminRestContext(global.oaeTests.tenants.gt.host);
        globalAdminRestContext = TestsUtil.createGlobalAdminRestContext();

        // Disable reCaptcha so anonymous users can create accounts
        ConfigTestUtil.updateConfigAndWait(camAdminRestContext, null, {'oae-principals/recaptcha/enabled': false}, function(err) {
            assert.ok(!err);

            // Drain the email queue
            return EmailTestsUtil.clearEmailCollections(callback);
        });
    });

    after(function(callback) {
        // Re-enable reCaptcha
        ConfigTestUtil.updateConfigAndWait(camAdminRestContext, null, {'oae-principals/recaptcha/enabled': true}, function(err) {
            assert.ok(!err);
            return callback();
        });
    });

    describe('Verification', function() {

        /**
         * Test that verifies validation when verifying an email address
         */
        it('verify validation when verifying an email address', function(callback) {
            // We can't use TestsUtil.generateTestUsers as that would do the verification process for us
            var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
            var params = {
                'username': TestsUtil.generateTestUserId(),
                'password': 'password',
                'displayName': TestsUtil.generateRandomText(1),
                'email': email
            };
            var restContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
            PrincipalsTestUtil.assertCreateUserSucceeds(restContext, params, function(user, token) {
                AuthenticationTestUtil.assertLocalLoginSucceeds(restContext, params.username, params.password, function() {
                    // Invalid user id
                    PrincipalsTestUtil.assertVerifyEmailFails(restContext, 'not a user id', token, 400, function() {
                        // Missing token
                        PrincipalsTestUtil.assertVerifyEmailFails(restContext, user.id, null, 400, function() {
                            // Invalid token
                            PrincipalsTestUtil.assertVerifyEmailFails(restContext, user.id, 'more than [7-14] characters', 400, function() {
                                // Incorrect token
                                PrincipalsTestUtil.assertVerifyEmailFails(restContext, user.id, '123456789', 401, function() {
                                    // Sanity-check
                                    PrincipalsTestUtil.assertVerifyEmailSucceeds(restContext, user.id, token, function() {
                                        // A token can only be verified once
                                        PrincipalsTestUtil.assertVerifyEmailFails(restContext, user.id, token, 404, function() {
                                            return callback();
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies authorization when verifying an email address
         */
        it('verify authorization when verifying an email address', function(callback) {
            // We can't use TestsUtil.generateTestUsers as that would do the verification process for us
            var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
            var params = {
                'username': TestsUtil.generateTestUserId(),
                'password': 'password',
                'displayName': TestsUtil.generateRandomText(1),
                'email': email
            };
            var restContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
            PrincipalsTestUtil.assertCreateUserSucceeds(restContext, params, function(user, token) {

                // Anonymous users cannot verify an email address
                PrincipalsTestUtil.assertVerifyEmailFails(anonymousRestContext, user.id, token, 401, function() {

                    // Other users cannot verify an email address
                    TestsUtil.generateTestUsers(camAdminRestContext, 1, function(err, users, badGuy) {
                        assert.ok(!err);
                        PrincipalsTestUtil.assertVerifyEmailFails(badGuy.restContext, user.id, token, 401, function() {

                            // Tenant admins from other tenants cannot verify an email address
                            PrincipalsTestUtil.assertVerifyEmailFails(gtAdminRestContext, user.id, token, 401, function() {

                                // The user can verify their email address if they've signed in
                                AuthenticationTestUtil.assertLocalLoginSucceeds(restContext, params.username, params.password, function() {
                                    PrincipalsTestUtil.assertVerifyEmailSucceeds(restContext, user.id, token, function() {
                                        return callback();
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that a token from another user cannot be used
         */
        it('verify a token from another user cannot be used', function(callback) {
            // We can't use TestsUtil.generateTestUsers as that would do the verification process for us
            var paramsUser1 = {
                'username': TestsUtil.generateTestUserId(),
                'password': 'password',
                'displayName': TestsUtil.generateRandomText(1),
                'email': TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0])
            };
            var restContextUser1 = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
            PrincipalsTestUtil.assertCreateUserSucceeds(restContextUser1, paramsUser1, function(user1, tokenUser1) {
                AuthenticationTestUtil.assertLocalLoginSucceeds(restContextUser1, paramsUser1.username, 'password', function() {
                    var paramsUser2 = {
                        'username': TestsUtil.generateTestUserId(),
                        'password': 'password',
                        'displayName': TestsUtil.generateRandomText(1),
                        'email': TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0])
                    };
                    var restContextUser2 = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
                    PrincipalsTestUtil.assertCreateUserSucceeds(restContextUser2, paramsUser2, function(user2, tokenUser2) {
                        AuthenticationTestUtil.assertLocalLoginSucceeds(restContextUser2, paramsUser2.username, 'password', function() {

                            // Assert we cannot user the token from the first user
                            PrincipalsTestUtil.assertVerifyEmailFails(restContextUser2, user2.id, tokenUser1, 401, function() {
                                return callback();
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that an email address can be re-used by other users
         */
        it('verify an email address can be re-used by other users', function(callback) {
            var tenantAlias = TenantsTestUtil.generateTestTenantAlias();
            var tenantHost = TenantsTestUtil.generateTestTenantHost();
            TestsUtil.createTenantWithAdmin(tenantAlias, tenantHost, function(err, tenant, tenantAdminRestContext, tenantAdmin) {
                assert.ok(!err);

                // Disable reCaptcha for this tenant
                ConfigTestUtil.updateConfigAndWait(globalAdminRestContext, tenantAlias, {'oae-principals/recaptcha/enabled': false}, function(err) {
                    assert.ok(!err);

                    var username1 = TestsUtil.generateTestUserId();
                    var username2 = TestsUtil.generateTestUserId();
                    var email = TestsUtil.generateTestEmailAddress(null, tenantHost);
                    var paramsUser1 = {
                        'displayName': 'Test user 1',
                        'email': email,
                        'password': 'password',
                        'username': TestsUtil.generateTestUserId()
                    };
                    var paramsUser2 = {
                        'displayName': 'Test user 2',
                        'email': email,
                        'password': 'password',
                        'username': TestsUtil.generateTestUserId()
                    };

                    // Create the first user as a tenant admin so the email address is considered verified
                    PrincipalsTestUtil.assertCreateUserSucceeds(tenantAdminRestContext, paramsUser1, function(user1) {

                        // Verify there's a mapping for the first user
                        PrincipalsTestUtil.assertUserEmailMappingEquals(email, [user1.id], function() {

                            // Create the second user as an anonymous user so the email address is not verified
                            var restContext = TestsUtil.createTenantRestContext(tenantHost);
                            PrincipalsTestUtil.assertCreateUserSucceeds(restContext, paramsUser2, function(user2, token) {

                                // Verify there's no mapping yet for the second user as the email address
                                // hasn't been verified yet
                                PrincipalsTestUtil.assertUserEmailMappingEquals(email, [user1.id], function() {

                                    // Verify the email address
                                    AuthenticationTestUtil.assertLocalLoginSucceeds(restContext, paramsUser2.username, paramsUser2.password, function() {
                                        PrincipalsTestUtil.assertVerifyEmailSucceeds(restContext, user2.id, token, function() {

                                            // The second user should now also be mapped to the email address
                                            PrincipalsTestUtil.assertUserEmailMappingEquals(email, [user1.id, user2.id], function() {
                                                return callback();
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that local accounts need to verify their email address
         */
        it('verify local user accounts need to verify their email address', function(callback) {
            // We can't use TestsUtil.generateTestUsers as that would do the verification process for us
            var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
            var params = {
                'username': TestsUtil.generateTestUserId(),
                'password': 'password',
                'displayName': TestsUtil.generateRandomText(1),
                'email': email
            };
            PrincipalsTestUtil.assertCreateUserSucceeds(anonymousRestContext, params, function(user, token) {

                // Sanity check the user has no `email` property yet
                RestAPI.User.getUser(camAdminRestContext, user.id, function(err, user) {
                    assert.ok(!err);
                    assert.ok(!user.email);

                    // Assert that there's no mapping yet for the email address
                    PrincipalsTestUtil.assertUserEmailMappingEquals(email, [], function() {

                        // Verify the email address
                        var restContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
                        AuthenticationTestUtil.assertLocalLoginSucceeds(restContext, params.username, params.password, function() {
                            PrincipalsTestUtil.assertVerifyEmailSucceeds(restContext, user.id, token, function() {

                                // Assert the mapping has been created
                                PrincipalsTestUtil.assertUserEmailMappingEquals(email, [user.id], function() {
                                    return callback();
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that activity emails are not sent to unverified email addresses
         */
        it('verify activity emails are not sent to unverified email addresses', function(callback) {
            // We can't use TestsUtil.generateTestUsers as that would do the verification process for us
            var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
            var params = {
                'username': TestsUtil.generateTestUserId(),
                'password': 'password',
                'displayName': TestsUtil.generateRandomText(1),
                'email': email
            };
            PrincipalsTestUtil.assertCreateUserSucceeds(anonymousRestContext, params, function(user, token) {

                // Generate some more users who will be part of the activity
                TestsUtil.generateTestUsers(camAdminRestContext, 2, function(err, users, simong, mrvisser) {
                    assert.ok(!err);

                    RestAPI.Content.createLink(simong.restContext, 'Google', 'Google', 'public', 'http://www.google.ca', [], [user.id, mrvisser.user.id], [], function(err, link) {
                        assert.ok(!err);

                        // Mrvisser should've received an email, but not the user with the unverified email address
                        EmailTestsUtil.collectAndFetchAllEmails(function(messages) {
                            assert.equal(messages.length, 1);
                            assert.strictEqual(messages[0].to.length, 1);
                            assert.equal(messages[0].to[0].address, mrvisser.user.email);
                            return callback();
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that local users accounts created by a tenant administrator do not need to verify their email address
         */
        it('verify local user accounts created by a tenant administrator do not need to verify their email address', function(callback) {
            // We can't use TestsUtil.generateTestUsers as that would do the verification process for us
            var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
            var params = {
                'username': TestsUtil.generateTestUserId(),
                'password': 'password',
                'displayName': TestsUtil.generateRandomText(1),
                'email': email
            };
            PrincipalsTestUtil.assertCreateUserSucceeds(camAdminRestContext, params, function(user) {

                // Verify the user doesn't need to verify their email address
                RestAPI.User.getUser(camAdminRestContext, user.id, function(err, user) {
                    assert.ok(!err);
                    assert.strictEqual(user.email, email.toLowerCase());

                    // Assert that there's a mapping for the email address
                    PrincipalsTestUtil.assertUserEmailMappingEquals(email, [user.id], function() {
                        return callback();
                    });
                });
            });
        });

        /**
         * Test that verifies when a user follows an invitation into creating
         * an external account, where the external provider does not provide an
         * email address (e.g., Facebook), that they receive the email associated
         * with the invitation as a pre-verified email
         */
        it('verify user accounts created following invitation with external login do not require email verification', function(callback) {
            // Create a tenant and enable Facebook authentication on it
            var tenantAlias = TenantsTestUtil.generateTestTenantAlias();
            var tenantHost = TenantsTestUtil.generateTestTenantHost();
            TestsUtil.createTenantWithAdmin(tenantAlias, tenantHost, function(err, tenant, tenantAdminRestContext) {
                assert.ok(!err);
                AuthenticationTestUtil.assertUpdateAuthConfigSucceeds(tenantAdminRestContext, null, {'oae-authentication/facebook/enabled': true}, function() {

                    // Remove the tenant's email domain so we can sign in through Facebook
                    TenantsTestUtil.updateTenantAndWait(globalAdminRestContext, tenant.alias, {'emailDomains': ''}, function() {

                        // First make sure authenticating without email and no
                        // invitation results in a user without an email
                        AuthenticationTestUtil.assertFacebookLoginSucceeds(tenant.host, null, function(restContext, me) {
                            assert.ok(!me.email);

                            // Create an invitation
                            var email = TestsUtil.generateTestEmailAddress(null, tenant.emailDomains[0]);
                            PrincipalsTestUtil.assertCreateGroupSucceeds(tenantAdminRestContext, 'My Group', 'My description', 'public', 'yes', [email], null, function(group) {
                                email = email.toLowerCase();

                                // Get the invitation info so we can make a redirect url
                                AuthzInvitationsDAO.getTokensByEmails([email], function(err, tokensByEmail) {
                                    assert.ok(!err);
                                    var token = tokensByEmail[email];

                                    // Authenticate without an email while following the redirect url
                                    var redirectUrl = util.format('/signup?invitationToken=%s&invitationEmail=%s', encodeURIComponent(token), encodeURIComponent(email));
                                    AuthenticationTestUtil.assertFacebookLoginSucceeds(tenant.host, {'redirectUrl': redirectUrl}, function(restContext, me) {
                                        assert.strictEqual(me.email, email);
                                        return callback();
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that user accounts created through trusted external SSO sources do not need to verify their email address
         */
        it('verify user accounts created through trusted external SSO sources do not need to verify their email address', function(callback) {
            // Create a tenant and enable google authentication on it
            var tenantAlias = TenantsTestUtil.generateTestTenantAlias();
            var tenantHost = TenantsTestUtil.generateTestTenantHost();
            TestsUtil.createTenantWithAdmin(tenantAlias, tenantHost, function(err, tenant, tenantAdminRestContext) {
                assert.ok(!err);
                AuthenticationTestUtil.assertUpdateAuthConfigSucceeds(tenantAdminRestContext, null, {'oae-authentication/google/enabled': true}, function() {

                    // Sign in through google
                    var email = TestsUtil.generateTestEmailAddress(null, tenant.emailDomains[0]);
                    AuthenticationTestUtil.assertGoogleLoginSucceeds(tenant.host, email, function(restContext, response) {

                        // As google is considered an authoritative source, the user shouldn't have
                        // to verify their email address
                        RestAPI.User.getMe(restContext, function(err, me) {
                            assert.ok(!err);
                            assert.ok(!me.anon);
                            assert.strictEqual(me.email, email.toLowerCase());

                            // Assert that there's a mapping for the email address
                            PrincipalsTestUtil.assertUserEmailMappingEquals(email, [me.id], function() {
                                return callback();
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that user accounts created with a valid invitation token whose email
         * matches the specified email do not need to verify their email address
         */
        it('verify user accounts created with a valid invitation token are automatically verified', function(callback) {
            // Create a tenant in which to create a user, and ensure there are no pending emails
            var tenantAlias = TenantsTestUtil.generateTestTenantAlias();
            var tenantHost = TenantsTestUtil.generateTestTenantHost();
            TestsUtil.createTenantWithAdmin(tenantAlias, tenantHost, function(err, tenant, tenantAdminRestContext) {
                assert.ok(!err);

                // Create 2 email addresses that have tokens associated to them
                var email1 = TestsUtil.generateTestEmailAddress(null, tenant.emailDomains[0]);
                var email2 = TestsUtil.generateTestEmailAddress(null, tenant.emailDomains[0]);
                AuthzInvitationsDAO.getOrCreateTokensByEmails([email1, email2], function(err, emailTokens) {
                    assert.ok(!err);

                    // Try to create a profile with email1, using email2's token. It should
                    // work, but it shouldn't auto-verify the email address
                    var profile = {
                        'username': TestsUtil.generateTestUserId(),
                        'password': 'password',
                        'displayName': TestsUtil.generateRandomText(),
                        'email': email1,
                        'invitationToken': emailTokens[email2]
                    };

                    // Ensure we get a user with an unverified email, as well as one email which
                    // is a verification email for email1
                    EmailTestsUtil.startCollectingEmail(function(stopCollectingEmail) {
                        PrincipalsTestUtil.assertCreateUserSucceeds(TestsUtil.createTenantRestContext(tenantHost), profile, function(user) {
                            assert.ok(!user.email);

                            stopCollectingEmail(function(messages) {
                                assert.strictEqual(_.size(messages), 1);

                                // Now create a profile with the matching email1 token and ensure
                                // email is automatically verified
                                _.extend(profile, {
                                    'username': TestsUtil.generateTestUserId(),
                                    'invitationToken': emailTokens[email1]
                                });

                                EmailTestsUtil.startCollectingEmail(function(stopCollectingEmail) {
                                    // We should get a profile with a verified email and no verification
                                    // email
                                    PrincipalsTestUtil.assertCreateUserSucceeds(TestsUtil.createTenantRestContext(tenantHost), profile, function(user) {
                                        assert.strictEqual(user.email, email1.toLowerCase());
                                        stopCollectingEmail(function(messages) {
                                            assert.ok(_.isEmpty(messages));
                                            return callback();
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Return a function that gets a stream to a file in the 'data' directory of the current test directory
         *
         * @param  {String}     filename    The name of the file in the test data directory to be loaded
         * @return {Function}               A function that, when executed without parameters, returns a stream to the file in the test data directory with the provided filename
         */
        var getDataFileStream = function(filename) {
            return function() {
                return fs.createReadStream(util.format('%s/data/%s', __dirname, filename));
            };
        };

        /**
         * Test that verifies that user accounts created or updated through a CSV import do not need to verify their email address
         */
        it('verify user accounts created or updated through a CSV import do not need to verify their email address', function(callback) {
            var tenantAlias = TenantsTestUtil.generateTestTenantAlias();
            var tenantHost = 'users.emails.com';
            TestsUtil.createTenantWithAdmin(tenantAlias, tenantHost, function(err, tenant, tenantAdminRestContext) {
                assert.ok(!err);

                // Import users as a global admin using a local authentication strategy
                PrincipalsTestUtil.importUsers(globalAdminRestContext, tenant.alias, getDataFileStream('users-emails.csv'), 'local', null, function(err) {
                    assert.ok(!err);

                    // Verify the user's email address is verified
                    var restContext = TestsUtil.createTenantRestContext(tenant.host, 'users-emails-abc123', 'password');
                    RestAPI.User.getMe(restContext, function(err, user) {
                        assert.ok(!err);
                        assert.strictEqual(user.email, 'foo@users.emails.com');

                        // Assert there's a mapping for the email address
                        PrincipalsTestUtil.assertUserEmailMappingEquals('foo@users.emails.com', [user.id], function() {

                            // Update the email address through a CSV import
                            PrincipalsTestUtil.importUsers(globalAdminRestContext, tenant.alias, getDataFileStream('users-emails-updated.csv'), 'local', true, function(err) {
                                assert.ok(!err);

                                RestAPI.User.getMe(restContext, function(err, user) {
                                    assert.ok(!err);
                                    assert.strictEqual(user.email, 'bar@users.emails.com');

                                    // Assert there's a mapping for the new email address
                                    PrincipalsTestUtil.assertUserEmailMappingEquals('bar@users.emails.com', [user.id], function() {

                                        // Assert there's no mapping for the old email address
                                        PrincipalsTestUtil.assertUserEmailMappingEquals('foo@users.emails.com', [], function() {
                                            return callback();
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that users updating their email address need to verify it
         */
        it('verify users updating their email address need to verify it', function(callback) {
            TestsUtil.generateTestUsers(camAdminRestContext, 1, function(err, users, simong) {
                assert.ok(!err);
                var oldEmailAddress = simong.user.email;

                // Sanity-check the email address is verified
                RestAPI.User.getMe(simong.restContext, function(err, me) {
                    assert.ok(!err);
                    assert.strictEqual(me.email, oldEmailAddress);

                    // Sanity-check there's a mapping for it
                    PrincipalsTestUtil.assertUserEmailMappingEquals(me.email, [me.id], function() {

                        // Update the email address
                        var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
                        PrincipalsTestUtil.assertUpdateUserSucceeds(simong.restContext, simong.user.id, {'email': email}, function(user, token) {

                            // Assert the old mapping is still in place
                            PrincipalsTestUtil.assertUserEmailMappingEquals(oldEmailAddress, [me.id], function() {

                                // Assert there's no mapping for the new email address as it hasn't been verified yet
                                PrincipalsTestUtil.assertUserEmailMappingEquals(email, [], function() {

                                    // The old email address should still be in place as the new one hasn't been verified yet
                                    RestAPI.User.getMe(simong.restContext, function(err, me) {
                                        assert.ok(!err);
                                        assert.strictEqual(me.email, oldEmailAddress);

                                        // Assert we can verify the email address
                                        PrincipalsTestUtil.assertVerifyEmailSucceeds(simong.restContext, simong.user.id, token, function() {

                                            // Assert the old mapping is gone
                                            PrincipalsTestUtil.assertUserEmailMappingEquals(oldEmailAddress, [], function() {

                                                // Assert the new mapping is there
                                                PrincipalsTestUtil.assertUserEmailMappingEquals(email, [me.id], function() {

                                                    // The new email address should be confirmed
                                                    RestAPI.User.getMe(simong.restContext, function(err, me) {
                                                        assert.ok(!err);
                                                        assert.strictEqual(me.email, email.toLowerCase());
                                                        return callback();
                                                    });
                                                });
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that admin updates to a user's email address trigger a different email message
         */
        it('verify admin updates to a user\'s email address trigger a different email message', function(callback) {
            TestsUtil.generateTestUsers(camAdminRestContext, 1, function(err, users, simong) {
                assert.ok(!err);
                var oldEmailAddress = simong.user.email;

                // Let an administrator update the email address
                var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
                PrincipalsTestUtil.assertUpdateUserSucceeds(camAdminRestContext, simong.user.id, {'email': email}, function(user, token) {

                    // The email address still has to be verified
                    assert.strictEqual(user.email, oldEmailAddress);
                    return callback();
                });
            });
        });

        /**
         * Test that verifies that users can only verify their last updated email address
         */
        it('verify users can only verify their last updated email address', function(callback) {
            TestsUtil.generateTestUsers(camAdminRestContext, 1, function(err, users, simong) {
                assert.ok(!err);
                var oldEmailAddress = simong.user.email;

                // Update the email address for the first time
                var email1 = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
                PrincipalsTestUtil.assertUpdateUserSucceeds(simong.restContext, simong.user.id, {'email': email1}, function(user, token1) {

                    // Update the email address again (with a second email address)
                    var email2 = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
                    PrincipalsTestUtil.assertUpdateUserSucceeds(simong.restContext, simong.user.id, {'email': email2}, function(user, token2) {

                        // Using the first token to verify the email address should fail
                        PrincipalsTestUtil.assertVerifyEmailFails(simong.restContext, simong.user.id, token1, 401, function() {

                            // Using the second token we can verify the email address
                            PrincipalsTestUtil.assertVerifyEmailSucceeds(simong.restContext, simong.user.id, token2, function() {

                                // Assert the old mapping is gone
                                PrincipalsTestUtil.assertUserEmailMappingEquals(oldEmailAddress, [], function() {

                                    // Assert no mapping was created for the first email address
                                    PrincipalsTestUtil.assertUserEmailMappingEquals(email1, [], function() {

                                        // Assert a mapping for the second email address is created
                                        PrincipalsTestUtil.assertUserEmailMappingEquals(email2, [simong.user.id], function() {

                                            // The second email address should be confirmed
                                            RestAPI.User.getMe(simong.restContext, function(err, me) {
                                                assert.ok(!err);
                                                assert.strictEqual(me.email, email2.toLowerCase());
                                                return callback();
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    });

    describe('Resending an email verification token', function() {

        /**
         * Test that verifies that an email verification token can be resent
         */
        it('verify an email verification token can be resent', function(callback) {
            // We can't use TestsUtil.generateTestUsers as that would do the verification process for us
            var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
            var params = {
                'username': TestsUtil.generateTestUserId(),
                'password': 'password',
                'displayName': TestsUtil.generateRandomText(1),
                'email': email
            };
            var restContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
            PrincipalsTestUtil.assertCreateUserSucceeds(restContext, params, function(user, token) {
                RestAPI.Authentication.login(restContext, params.username, 'password', function(err) {
                    assert.ok(!err);

                    // Verify we can resend the email verification token
                    PrincipalsTestUtil.assertResendEmailTokenSucceeds(restContext, user.id, function(newToken) {
                        // Assert we've sent the same token
                        assert.strictEqual(newToken, token);

                        // Sanity-check we can use this new token to verify the email address
                        PrincipalsTestUtil.assertVerifyEmailSucceeds(restContext, user.id, newToken, function() {
                            return callback();
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies validation when resending an email verification token
         */
        it('verify validation when resending an email verification token', function(callback) {
            // We can't use TestsUtil.generateTestUsers as that would do the verification process for us
            var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
            var params = {
                'username': TestsUtil.generateTestUserId(),
                'password': 'password',
                'displayName': TestsUtil.generateRandomText(1),
                'email': email
            };
            var restContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
            PrincipalsTestUtil.assertCreateUserSucceeds(restContext, params, function(user, token) {
                RestAPI.Authentication.login(restContext, params.username, 'password', function(err) {
                    assert.ok(!err);

                    // Invalid user id
                    PrincipalsTestUtil.assertResendEmailTokenFails(restContext, 'not a user id', 400, function() {
                        return callback();
                    });
                });
            });
        });

        /**
         * Test that verifies authorization when resending an email verification token
         */
        it('verify authorization when resending an email verification token', function(callback) {
            // We can't use TestsUtil.generateTestUsers as that would do the verification process for us
            var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
            var params = {
                'username': TestsUtil.generateTestUserId(),
                'password': 'password',
                'displayName': TestsUtil.generateRandomText(1),
                'email': email
            };
            var restContext = TestsUtil.createTenantRestContext(global.oaeTests.tenants.cam.host);
            PrincipalsTestUtil.assertCreateUserSucceeds(restContext, params, function(user, token) {
                RestAPI.Authentication.login(restContext, params.username, 'password', function(err) {
                    assert.ok(!err);

                    // Anonymous users can't resend a token
                    PrincipalsTestUtil.assertResendEmailTokenFails(anonymousRestContext, user.id, 401, function() {

                        // Users cannot resend a token for someone else
                        TestsUtil.generateTestUsers(camAdminRestContext, 1, function(err, users, otherUser) {
                            assert.ok(!err);
                            PrincipalsTestUtil.assertResendEmailTokenFails(otherUser.restContext, user.id, 401, function() {

                                // Tenant administrators from another tenant cannot resend a token
                                PrincipalsTestUtil.assertResendEmailTokenFails(gtAdminRestContext, user.id, 401, function() {

                                    // Tenant administrators from the same tenant as the user can resend a token
                                    PrincipalsTestUtil.assertResendEmailTokenSucceeds(camAdminRestContext, user.id, function(newToken) {

                                        // Global administrators can resend a token
                                        PrincipalsTestUtil.assertResendEmailTokenSucceeds(globalAdminRestContext, user.id, function(newToken) {
                                            return callback();
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies that a token can only be resent when there is a pending verification
         */
        it('verify that a token can only be resent when there is a pending verification', function(callback) {
            // Create a user who has no pending email verification token
            TestsUtil.generateTestUsers(camAdminRestContext, 1, function(err, users, simong) {
                assert.ok(!err);

                // Resending a token should fail as there is no token to resend
                PrincipalsTestUtil.assertResendEmailTokenFails(simong.restContext, simong.user.id, 404, function() {

                    // Update the email address so we get a token
                    var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
                    PrincipalsTestUtil.assertUpdateUserSucceeds(simong.restContext, simong.user.id, {'email': email}, function(user, token) {

                        // Resending a token now should be OK
                        PrincipalsTestUtil.assertResendEmailTokenSucceeds(simong.restContext, simong.user.id, function(newToken) {

                            // Use the token to verify the new email address
                            PrincipalsTestUtil.assertVerifyEmailSucceeds(simong.restContext, simong.user.id, newToken, function() {

                                // Resending a token should now fail as the token has been used and should be removed
                                PrincipalsTestUtil.assertResendEmailTokenFails(simong.restContext, simong.user.id, 404, function() {
                                    return callback();
                                });
                            });
                        });
                    });
                });
            });
        });
    });

    describe('Has pending email verification token', function() {

        /**
         * Test that verifies the has pending email verification token functionality
         */
        it('verify has pending email verification token functionality', function(callback) {
            TestsUtil.generateTestUsers(camAdminRestContext, 1, function(err, users, simong) {
                assert.ok(!err);

                // Verify no email is returned when the user has no pending verification
                PrincipalsTestUtil.assertGetEmailTokenSucceeds(simong.restContext, simong.user.id, function(email) {
                    assert.ok(!email);

                    // Update the user's email address
                    email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
                    PrincipalsTestUtil.assertUpdateUserSucceeds(simong.restContext, simong.user.id, {'email': email}, function() {

                        // Verify the user as a token
                        PrincipalsTestUtil.assertGetEmailTokenSucceeds(simong.restContext, simong.user.id, function(emailForToken) {
                            assert.strictEqual(emailForToken, email.toLowerCase());

                            return callback();
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies validation when checking for a pending email verification token
         */
        it('verify validation when checking for a pending email verification token', function(callback) {
            TestsUtil.generateTestUsers(camAdminRestContext, 1, function(err, users, simong) {
                assert.ok(!err);

                // Invalid user id
                PrincipalsTestUtil.assertGetEmailTokenFails(simong.restContext, 'not a user id', 400, function() {
                    PrincipalsTestUtil.assertGetEmailTokenFails(simong.restContext, 'g:camtest:1234234', 400, function() {
                        return callback();
                    });
                });
            });
        });

        /**
         * Test that verifies authorization when checking for a pending email verification token
         */
        it('verify authorization when checking for a pending email verification token', function(callback) {
            TestsUtil.generateTestUsers(camAdminRestContext, 2, function(err, users, simong, mrvisser) {
                assert.ok(!err);

                // Update simon's email address so he has a verification token
                var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
                PrincipalsTestUtil.assertUpdateUserSucceeds(simong.restContext, simong.user.id, {'email': email}, function() {

                    // Anonymous users cannot check anything
                    PrincipalsTestUtil.assertGetEmailTokenFails(anonymousRestContext, simong.user.id, 401, function() {

                        // Users cannot check other users their email tokens
                        PrincipalsTestUtil.assertGetEmailTokenFails(mrvisser.restContext, simong.user.id, 401, function() {

                            // Tenant administrator cannot check users from another tenant their email token
                            PrincipalsTestUtil.assertGetEmailTokenFails(gtAdminRestContext, simong.user.id, 401, function() {

                                // A user can check his own pending email verification token
                                PrincipalsTestUtil.assertGetEmailTokenSucceeds(simong.restContext, simong.user.id, function(emailForToken) {

                                    // A tenant admin can check the pending email verification token for users of their tenant
                                    PrincipalsTestUtil.assertGetEmailTokenSucceeds(camAdminRestContext, simong.user.id, function(emailForToken) {
                                        return callback();
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    });

    describe('Delete an email verification token', function() {

        /**
         * Test that verifies the delete email verification functionality
         */
        it('verify delete email verification token functionality', function(callback) {
            TestsUtil.generateTestUsers(camAdminRestContext, 1, function(err, users, simong) {
                assert.ok(!err);

                // Update the email address
                var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
                PrincipalsTestUtil.assertUpdateUserSucceeds(simong.restContext, simong.user.id, {'email': email}, function() {

                    // Delete the token
                    PrincipalsTestUtil.assertDeleteEmailTokenSucceeds(simong.restContext, simong.user.id, function() {

                        // Verify a token can't be deleted twice
                        PrincipalsTestUtil.assertDeleteEmailTokenFails(simong.restContext, simong.user.id, 404, function() {
                            return callback();
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies validation when deleting a pending email verification token
         */
        it('verify validation when deleting a pending email verification token', function(callback) {
            TestsUtil.generateTestUsers(camAdminRestContext, 1, function(err, users, simong) {
                assert.ok(!err);

                // Invalid user id
                PrincipalsTestUtil.assertDeleteEmailTokenFails(simong.restContext, 'not a user id', 400, function() {
                    PrincipalsTestUtil.assertDeleteEmailTokenFails(simong.restContext, 'g:camtest:1234234', 400, function() {

                        // No token should return a 404
                        PrincipalsTestUtil.assertDeleteEmailTokenFails(simong.restContext, simong.user.id, 404, function() {
                            return callback();
                        });
                    });
                });
            });
        });

        /**
         * Test that verifies authorization when deleting a pending email verification token
         */
        it('verify authorization when deleting a pending email verification token', function(callback) {
            TestsUtil.generateTestUsers(camAdminRestContext, 2, function(err, users, simong, mrvisser) {
                assert.ok(!err);

                // Update simon's email address so he has a verification token
                var email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
                PrincipalsTestUtil.assertUpdateUserSucceeds(simong.restContext, simong.user.id, {'email': email}, function() {

                    // Anonymous users cannot delete anything
                    PrincipalsTestUtil.assertDeleteEmailTokenFails(anonymousRestContext, simong.user.id, 401, function() {

                        // Users cannot delete other users their email tokens
                        PrincipalsTestUtil.assertDeleteEmailTokenFails(mrvisser.restContext, simong.user.id, 401, function() {

                            // Tenant administrator cannot delete users from another tenant their email token
                            PrincipalsTestUtil.assertDeleteEmailTokenFails(gtAdminRestContext, simong.user.id, 401, function() {

                                // A user can delete his own pending email verification token
                                PrincipalsTestUtil.assertDeleteEmailTokenSucceeds(simong.restContext, simong.user.id, function(emailForToken) {

                                    email = TestsUtil.generateTestEmailAddress(null, global.oaeTests.tenants.cam.emailDomains[0]);
                                    PrincipalsTestUtil.assertUpdateUserSucceeds(simong.restContext, simong.user.id, {'email': email}, function() {
                                        // A tenant admin can delete the pending email verification token for users of their tenant
                                        PrincipalsTestUtil.assertDeleteEmailTokenSucceeds(camAdminRestContext, simong.user.id, function(emailForToken) {
                                            return callback();
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    });
});


text:
![alt text](http://i.imgur.com/75ocTrv.gif)

# Eesmärk
Mängu eesmärk on lahendada TLÜ Astra maja 4. korrusel DTI õppejõudude poolt antavaid ülesandeid ja teenida ainepunkte (EAP). Lõppeesmärk on lõpetada semester, ehk teenida 30EAP.
Mängu raskendamiseks on ka erinevad takistused (minigamed), mis kaotavad EAP-e vastavalt sellele, kui hästi või halvasti minigame läbimine õnnestus.

# Õpime Tallinna Ülikooli Digitehnoloogia instituudis. Projekt on tehtud õppetöö suvepraktika raames.

# Kasutatud tehnoloogiad
Unity 5.6
Adobe Photoshop CS6
GitHub desktop

# Grupi liikmed
Uku Põder, Cleven Lehispuu, Henri Vajak, Tanel Maasalu

# Paigaldusjuhised
Mängimiseks:
1. Lae alla repositooriumist Game.rar fail
2. Paki see lahti
3. Käivita mäng game.exe failist

Arenduskeskkonna tööle saamiseks:
1. Lae alla Unity 5.6
2. Lae alla repositoorium
3. Ava repositoorium Unity'ga

# Viide litsentsile
https://github.com/ClevenL/Game-design-project/blob/master/LICENSE.txt


text:
using Lombiq.TrainingDemo.Models;
using OrchardCore.ContentManagement;
using System;
using YesSql.Indexes;

namespace Lombiq.TrainingDemo.Indexes;

// This is also very similar to the one we've seen in BookIndex.cs. The difference is that we have ContentItems now
// instead of simple objects.
public class PersonPartIndex : MapIndex
{
    // Here we will reference the ContentItem ID.
    public string ContentItemId { get; set; }

    // Store the birth date only for demonstration purposes so we can run queries on it.
    public DateTime? BirthDateUtc { get; set; }

    // Store the handedness only for demonstration purposes so we can show off enum filtering in GraphQL.
    public Handedness Handedness { get; set; }
}

// Don't forget to register this class with the service provider (see: Startup.cs).
public class PersonPartIndexProvider : IndexProvider<ContentItem>
{
    // Notice that ContentItem is what we are describing the provider for not the part.
    public override void Describe(DescribeContext<ContentItem> context) =>
        context.For<PersonPartIndex>()
            // Note that we can write any logic in here to determine when an index record should be created for a
            // content item. Here we'll have a record for every content item possessing a PersonPart. However, we could
            // e.g. only have an index for only published items (if you don't want to query on drafts; you can check
            // contentItem.Published), or only on the latest ones (regardless of it being a draft or published version
            // contentItem.Latest shows this). Not cluttering up the index table with unnecessary rows can help with
            // performance and makes managing the database easier overall.
            .When(contentItem => contentItem.Has<PersonPart>())
            // Note that there is a lot more to index providers than just Map() and When() (although these are what you
            // need to use the most), see the YesSQL documentation:
            // https://github.com/sebastienros/yessql/wiki/Tutorial
            .Map(contentItem =>
            {
                var personPart = contentItem.As<PersonPart>();

                return new PersonPartIndex
                {
                    ContentItemId = contentItem.ContentItemId,
                    BirthDateUtc = personPart.BirthDateUtc,
                    Handedness = personPart.Handedness,
                };
            });
}

// END OF TRAINING SECTION: Content Item and Content Part development

// NEXT STATION: Controllers/PersonListController


text:
import time

import music21
import sys
import os

import inspect
from os.path import dirname
# Add parent directory to sys.path so we find OpenFL.
sys.path.append(dirname(dirname(dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))))
from OpenFL import Printer as P

def midi_live(midifilename,
              quarternote_s=0.5,
              frequency_factor=1.0,
              skip_leading_rests=True):
    """ Given a MIDI file, play it live on the printer
    """
    p = P.Printer()
    if p.state() != P.State.MACHINE_READY_TO_PRINT:
        p.initialize()
    else:
        # We still want to ensure we start in a known state, with z at the limit:
        import OpenFL.FLP as FLP
        # Move z up by more than the z height at 15 mm/s.
        p.move_z(FLP.ZMove.usteps_up_per_mm * 200.0,
                 feedrate=FLP.ZMove.usteps_up_per_mm * 15.0)

    # Use a class as a local namespace to capture variables
    p.move_z(FLP.ZMove.usteps_up_per_mm * -10.0,
             feedrate=FLP.ZMove.usteps_up_per_mm * 15.0)
    class Position:
        zbounds_mm = (-10, -150)
        zbounds_ustep = (zbounds_mm[0] * FLP.ZMove.usteps_up_per_mm,
                         zbounds_mm[1] * FLP.ZMove.usteps_up_per_mm)
        # This is our current Z position in microsteps:
        z_ustep = FLP.ZMove.usteps_up_per_mm * -10.0
        direction = -1  # This is the direction of travel (negative = down)

    # Local function that handles note direction and timing
    def play_note(freq, time_s):
        # Turn around if we're about to hit the top or bottom
        steps = freq * time_s
        next_z_would_be = Position.z_ustep + Position.direction * freq * time_s
        if Position.direction < 0:
            if next_z_would_be < min(Position.zbounds_ustep):
                Position.direction = 1
        else:
            if next_z_would_be > max(Position.zbounds_ustep):
                Position.direction = -1

        # Send a blocking motor move
        p.move_z(Position.direction * freq * time_s, freq, 80)

        # Update the dead-reckoning Z position
        Position.z_ustep += Position.direction * steps

    print 'Reading MIDI file...'
    mf = music21.midi.MidiFile()
    mf.open(midifilename)
    mf.read()
    soundstream = music21.midi.translate.midiFileToStream(mf)
    print 'read {} streams'.format(len(soundstream.elements))
    for track in soundstream.elements:
        for i in track.flat.elements:
            # Play a note on the printer (and clear the skip rests flag)
            if isinstance(i, music21.note.Note):
                play_note(i.pitch.frequency * frequency_factor,
                          i.duration.quarterLength * quarternote_s)
                skip_leading_rests = False
            # Pause the correct amount of time for a rest
            elif isinstance(i, music21.note.Rest):
                if not skip_leading_rests:
                    time.sleep(i.duration.quarterLength * quarternote_s)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='Play a midi file on your Form 1 or Form 1+.')
    parser.add_argument('midifile', type=str,
                        help='A midi file to play')
    parser.add_argument('--quarternote_s',
                        type=float,
                        default=0.5,
                        help='Duration for a quarternote.')
    parser.add_argument('--frequency_factor', type=float, default=1.0,
                        help='Scale frequency by this factor.')
    args = parser.parse_args()
    midi_live(args.midifile,
              quarternote_s=args.quarternote_s,
              frequency_factor=args.frequency_factor)


text:
title: Rencontre avec Anne
description: >-
  La cuisine comme moyen d'expression ! Et il n'y a pas d'âge pour commencer !
  Rencontre avec Anne et découverte de ses ateliers pour des cuisiniers en herbe
  !
image: /images/anne.jpg
categories:
  - cuistots
date: 2017-07-18T22:00:00.000Z
---
**Cuisiner est pour nous une passion. Et toi, quelle est ton histoire avec la cuisine ?**

Je m'appelle Anne, je suis maman de 2 ados. Après 20 années passées dans le commercial et les ressources humaines, je me suis orientée dans l'accompagnement et l'épanouissement des enfants par la cuisine.

J'ai à cœur de mettre mes connaissances et mes compétences au service des enfants afin de leur permettre de se développer pleinement dans la bienveillance, l'écoute et le dialogue.

Entre des grands-parents restaurateurs et une maman qui cuisine beaucoup : j'ai vite été mise dans le bain !

Adolescente, quand mes parents travaillaient je préparais les repas : à l'époque je ne faisais pas la différence entre un oignon, une échalote et une gousse d'ail !! Malgré des débuts hésitants : le gâteau pas cuit ou qui déborde dans le four et enfume la cuisine, j'ai persévéré. !! J'aime cuisiner, tester, faire découvrir de nouveaux aliments ou de nouvelles recettes à mes amis. Cuisiner m'apporte : détente, joie, satisfaction du travail réussi et stimule ma créativité.

En devenant maman, je me suis intéressée à l'impact de l'enfance sur nos vies d'adultes. La lecture d « au cœur des émotions de l'enfant » d'Isabelle FILLIOZAT fut une vraie révélation. En parallèle de mes lectures, je me suis formée à la communication bienveillante. Ces stages m'ont permis d'identifier mes blocages et ce qui m'empêchait de communiquer avec bienveillance avec les enfants, et plus particulièrement avec les miens.

Il y a un an nous nous sommes aperçus que nos 2 ados étaient intolérants à plusieurs aliments, surtout les plus utilisés dans notre société occidentale : le lait, les œufs, le gluten. J'ai considéré cette nouvelle non comme un handicap mais comme une opportunité de découvrir de nouveaux aliments et de nouvelles recettes.

C'est donc tout naturellement que mon projet a pris forme : proposer des cours de cuisine aux enfants, découvrir les règles, les contraintes..., des aliments. Tout en profitant de ce moment pour les aider à prendre confiance en eux, à connaitre les potentiels et leur forces.

J'ai à cœur d'allier la cuisine et la communication bienveillante en proposant des outils pour apprendre à gérer les conflits dans les fratries, les problèmes scolaires…

**Quelles sont tes influences culinaires ?**

Pour cuisiner, je puise mon inspiration dans tout un tas de revues, livres et sites culinaires. Je pars à la découverte d'un produit en cherchant de nouvelles recettes et je crée au final ma propre recette ! J'aime inventer, innover, tester. On ne mange jamais 2 fois la même chose avec moi !

Quand je reçois des invités, je ne leur présente jamais le plat qu'ils vont déguster. Je les laisse découvrir en goûtant. J'aime les surprendre et leur faire manger des choses qu'ils n'auraient pas soupçonnées !

**Quels sont les ingrédients les plus étranges que l'on retrouve dans ta cuisine ?**

Je dirais les algues, les légumes oubliés, les graines en tout genre et le tofu soyeux !

**Quelle est ton plat préféré ?**

Ce serait un plat avec des épices et du lait de coco. Pour en citer un, je dirais un Cari !

**Si l'on partait dans le Finistère Sud, d'où tu es originaire, que nous conseillerais-tu de visiter ?**

Sans hésitation, ce serait le sentier côtier Pont-Aven – Port Manac'h.

**Si tu avais une recette à nous partager, ce serait ?**

Voici ma recette de curry pour 4 personnes

Ingrédients :

100 g d'épinards équeutés

250 g de pois chiches déjà cuits

1 oignon rouge moyen

1 patate douce

1 gousse d'ail

40 cl de lait de coco

1 cuil. à soupe de concentré de tomates

2 cuil. à soupe de jus de citron

1 cuil. à café de pâte de crevettes, à défaut du nuoc mam

1 cuil. à café de sucre roux

2 cuil. à soupe d'huile végétale

Les épices :

1 cuil. à café rase de garam massala

½ cuil. à café de coriandre moulue

½ cuil. à café de cumin moulu

¼ cuil. à café de curcuma

3 pincées de piment de Cayenne

Graines de sésame pour servir

Rincez les pois chiches et réservez.

Préparation :

Lavez les feuilles d'épinard, après les avoir équeutées, puis coupez-les en lanières.

Pelez puis émincez l'oignon et la gousse d'ail.

Faites chauffer l'huile dans une cocotte ou dans une sauteuse.

Ajoutez l'oignon puis faites-le revenir sur feu moyen pendant 5 minutes.

Ajoutez les épices, l'ail et mélangez bien.

Ajoutez les pois chiches, la patate douce coupée en cubes, le lait de coco, la pâte de crevettes (ou le

nuoc mam), le concentré de tomates, le sucre, le jus de citron et mélangez bien.

Portez à ébullition, baissez le feu et laissez mijoter pendant 10 minutes, sur feu doux.

Goutez et rectifiez éventuellement l'assaisonnement. Il doit y avoir un équilibre à la fois sucré, épicé,

acide et salé.

Ajoutez les lanières de feuilles d'épinard, mélangez puis couvrez.

Augmentez le feu à feu moyen puis laissez cuire pendant 5 minutes environ, jusqu'à ce que les

épinards soient « fondus ».

Servez et parsemez de graines de sésame.


text:
@protocol ViewControllerRootHomeProtocol;
@class ViewControllerRootHomeCenter;
IB_DESIGNABLE

@interface ViewControllerRootHome : UIViewController <UITabBarDelegate, UITextFieldDelegate, returnToRootHome> {

    UIButton *nuke;
    UITextField *tfEmail;
    UIButton *btnEmailSave;
    UITabBar *tbRoot;
}

@property (nonatomic, weak) id<ViewControllerRootHomeProtocol> delegate;

@property (weak, nonatomic) IBOutlet UIScrollView *rootHomeScroller;
@property (weak, nonatomic) IBOutlet UITextField *tfDeleteAccount;
@property (weak, nonatomic) IBOutlet UIButton *btnDeleteAccount;
@property (weak, nonatomic) IBOutlet UIButton *btnDisplayAccount;
@property (weak, nonatomic) IBOutlet UIButton *btnDisplayEmail;
@property (weak, nonatomic) IBOutlet UITextView *tvDisplayAccount;
@property (weak, nonatomic) IBOutlet UISwitch *switchRfid;
@property (weak, nonatomic) IBOutlet UITextField *tfCreditUsername;
@property (weak, nonatomic) IBOutlet UITextField *tfCredit;
@property (weak, nonatomic) IBOutlet UIButton *btnAddCredit;
@property (weak, nonatomic) IBOutlet UILabel *lblCredit;
@property (weak, nonatomic) IBOutlet UILabel *lblRootCredit;
@property (weak, nonatomic) IBOutlet UIButton *btnLogout;
@property (weak, nonatomic) IBOutlet UIButton *btnCheckFlow;
@property (weak, nonatomic) IBOutlet UIButton *btnSerialConsole;
@property (weak, nonatomic) IBOutlet UIButton *btnLogs;
@property (weak, nonatomic) IBOutlet UIButton *btndev;

@property (nonatomic, strong) ViewControllerRootHomeCenter *viewControllerRootHomeCenter;

// added button to get to flow indicator scene
@property (weak, nonatomic) IBOutlet UIButton *btnFlowIndicator;

// added first tabbaritem
@property (weak, nonatomic) IBOutlet UITabBarItem *tbiUsers;
@property (weak, nonatomic) IBOutlet UITabBarItem *tbiMisc;
@property (weak, nonatomic) IBOutlet UITabBarItem *tbiDev;

// added dev3 btn for CoreBluetooth testing.
@property (weak, nonatomic) IBOutlet UIButton *btnDev4;

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

- (IBAction)displayAccount:(id)sender;
- (IBAction)displayEmail:(id)sender;
- (IBAction)deleteAccount:(id)sender;

//dismiss keyboard
- (IBAction)dismissKeyboard:(id)sender;
- (IBAction)saveMasterEmail;
- (IBAction)rfidOnOff;
- (IBAction)addCredit:(id)sender;
- (IBAction)logout:(id)sender;

@end

@protocol ViewControllerRootHomeProtocol <NSObject>
@optional
-(void)movePanelToOriginalPosition;
@end // end of delegate protocol


text:
<?php

declare(strict_types=1);

namespace Brain\Hierarchy\Branch;

/**
 * @author  Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
 * @license http://opensource.org/licenses/MIT MIT
 */
final class BranchCategory implements Branch
{
    /**
     * @return string
     */
    public function name(): string
    {
        return 'category';
    }

    /**
     * @param \WP_Query $query
     * @return bool
     */
    public function is(\WP_Query $query): bool
    {
        return $query->is_category();
    }

    /**
     * @param \WP_Query $query
     * @return list<string>
     */
    public function leaves(\WP_Query $query): array
    {
        /** @var \stdClass $term */
        $term = $query->get_queried_object();
        if (!isset($term->slug) || !isset($term->term_id)) {
            return ['category'];
        }

        return [
            "category-{$term->slug}",
            "category-{$term->term_id}",
            'category',
        ];
    }
}


text:
"""
Decorator functions

Created by: Rui Carmo
"""

from bottle import request, response, abort
import time
import binascii
import hashlib
import email.utils
import functools
import json
import logging
from base64 import b64encode, b64decode

from google.appengine.api import memcache

log = logging.getLogger()

gmt_format_string = "%a, %d %b %Y %H:%M:%S GMT"

def cache_memory(ns='url', ttl=3600):
    """Cache route results in Memcache"""

    def decorator(callback):
        @functools.wraps(callback)
        def wrapper(*args, **kwargs):
            try:
                item = json.loads(memcache.get(request.urlparts.path, namespace=ns))
                if 'image' in item['content-type']:
                    body = b64decode(item['body'])
                else:
                    body = item['body']
                for h in item['headers']:
                    response.set_header(str(h), item['headers'][h])
                response.set_header('X-Source', 'Memcache')
            except Exception as e:
                log.debug("Cache miss for %s: %s" % (request.urlparts.path, e))
                body = callback(*args, **kwargs)
                item = {
                    'body': b64encode(body) if 'image' in response.content_type else body,
                    'headers': dict(response.headers),
                    'mtime': int(time.time()),
                    'content-type': response.content_type
                }
                try:
                    memcache.set(request.urlparts.path, json.dumps(item), time=ttl, namespace=ns)
                except Exception as e:
                    log.debug("Could not cache %s: %s" % (request.urlparts.path, e))
            return body
        return wrapper
    return decorator

def cache_results(timeout=0):
    """Cache route results for a given period of time"""

    def decorator(callback):
        _cache = {}
        _times = {}

        @functools.wraps(callback)
        def wrapper(*args, **kwargs):

            def expire(when):
                for t in [k for k in _times.keys()]:
                    if (when - t) > timeout:
                        del(_cache[_times[t]])
                        del(_times[t])

            now = time.time()
            try:
                item = _cache[request.urlparts]
                if 'If-Modified-Since'  in request.headers:
                    try:
                        since = time.mktime(email.utils.parsedate(request.headers['If-Modified-Since']))
                    except:
                        since = now
                    if item['mtime'] >= since:
                        expire(now)
                        abort(304,'Not modified')
                for h in item['headers']:
                    response.set_header(str(h), item['headers'][h])
                body = item['body']
                response.set_header('X-Source', 'Worker Cache')
            except KeyError:
                body = callback(*args, **kwargs)
                item = {
                    'body': body,
                    'headers': response.headers,
                    'mtime': int(now)
                }
                _cache[request.urlparts] = item
                _times[now] = request.urlparts

            expire(now)
            return body
        return wrapper
    return decorator

def cache_control(seconds = 0):
    """Insert HTTP caching headers"""

    def decorator(callback):
        @functools.wraps(callback)
        def wrapper(*args, **kwargs):
            expires = int(time.time() + seconds)
            expires = time.strftime(gmt_format_string, time.gmtime(expires))
            response.set_header('Expires', expires)
            if seconds:
                pragma = 'public'
            else:
                pragma = 'no-cache, must-revalidate'
            response.set_header('Cache-Control', "%s, max-age=%s" % (pragma, seconds))
            response.set_header('Pragma', pragma)
            return callback(*args, **kwargs)
        return wrapper
    return decorator

def timed(callback):
    """Decorator for timing route processing"""

    @functools.wraps(callback)
    def wrapper(*args, **kwargs):
        start = time.time()
        body = callback(*args, **kwargs)
        end = time.time()
        response.set_header('X-Processing-Time', str(end - start))
        return body
    return wrapper

def jsonp(callback):
    """Decorator for JSONP handling"""

    @functools.wraps(callback)
    def wrapper(*args, **kwargs):
        body = callback(*args, **kwargs)
        try:
            body = json.dumps(body)
            # Set content type only if serialization successful
            response.content_type = 'application/json'
        except Exception, e:
            return body

        callback_function = request.query.get('callback')
        if callback_function:
            body = ''.join([callback_function, '(', body, ')'])
            response.content_type = 'text/javascript'

        response.set_header('Last-Modified', time.strftime(gmt_format_string, time.gmtime()))
        response.set_header('ETag', binascii.b2a_base64(hashlib.sha1(body).digest()).strip())
        response.set_header('Content-Length', len(body))
        return body
    return wrapper

def memoize(f):
    """Memoization decorator for functions taking one or more arguments"""

    class memodict(dict):
        def __init__(self, f):
            self.f = f

        def __call__(self, *args):
            return self[args]

        def __missing__(self, key):
            res = self[key] = self.f(*key)
            return res

        def __repr__(self):
            return self.f.__doc__

        def __get__(self, obj, objtype):
            return functools.partial(self.__call__, obj)
    return memodict(f)