text:
package main

import (
	"testing"

	"github.com/kataras/iris/v12/httptest"
)

func TestShareServices(t *testing.T) {
	app := newApp()
	e := httptest.New(t, app)

	e.GET("/").Expect().Status(httptest.StatusOK).Body().Equal("Hello, Gophers!")
}


text:
require 'templater'
require 'thor'

module RubyHtmlApp
  class FileGenerator < Templater::Generator

    def initialize(target, args)
      @params = args
      super(target)
    end

    def self.source_root
      File.join(File.dirname(__FILE__), 'templates')
    end
  end

  class CLI < Thor
    desc "create", "create a new ruby html app"
    def create(raw_name)
      name = raw_name.chomp("/")
      namespaced_path = name.tr('-', '/')
      target = File.join(Dir.pwd, name)
      constant_name = name.split('_').map{|p| p[0..0].upcase + p[1..-1] }.join
      constant_name = constant_name.split('-').map{|q| q[0..0].upcase + q[1..-1] }.join('::') if constant_name =~ /-/
      constant_array = constant_name.split('::')
      git_user_name = `git config user.name`.chomp
      git_user_email = `git config user.email`.chomp
      `bundle gem #{raw_name}`
      opts = {
        :name            => name,
        :namespaced_path => namespaced_path,
        :constant_name   => constant_name,
        :constant_array  => constant_array,
        :author          => git_user_name.empty? ? "TODO: Write your name" : git_user_name,
        :email           => git_user_email.empty? ? "TODO: Write your email address" : git_user_email,
        :test            => options[:test]
      }
      gen = FileGenerator.new(name, opts)
      #static files
      FileGenerator.file(:application_html, "html/application.html.haml", "lib/#{name}/html/application.html.haml")
      FileGenerator.file(:layout_html, "html/layout.html.haml", "lib/#{name}/html/layout.html.haml")
      FileGenerator.empty_directory(:images, "lib/#{name}/images/")
      FileGenerator.file(:application_js, "javascripts/application.js", "lib/#{name}/javascripts/application.js")
      FileGenerator.file(:application_css, "stylesheets/application.css", "lib/#{name}/stylesheets/application.css")
      FileGenerator.empty_directory(:dist, "dist/")
      FileGenerator.file(:helpers, "helpers.rb", "lib/#{name}/helpers.rb")

      #erb files
      FileGenerator.template(:cli, "cli.rb", "lib/#{name}/cli.rb")
      FileGenerator.template(:run, "run", "bin/#{name}")
      FileGenerator.template(:gemspec, "newgem.gemspec", "#{name}.gemspec")
      FileGenerator.template(:app, "newgem.rb", "lib/#{name}.rb")
      gen.invoke!
      Dir.chdir(name) { `git add .`; `git commit -m "initialize rubyhtmlapp"`;  }
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
import {InjectionToken} from './injection_token';
import {Injector} from './injector';
import {InjectorMarkers} from './injector_marker';

/**
 * An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.
 *
 * Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a
 * project.
 *
 * @publicApi
 */
export const INJECTOR = new InjectionToken<Injector>(
    'INJECTOR',
    // Disable tslint because this is const enum which gets inlined not top level prop access.
    // tslint:disable-next-line: no-toplevel-property-access
    InjectorMarkers.Injector as any,  // Special value used by Ivy to identify `Injector`.
);


text:
Part of the Aspects Suite.

Allows you to configure Apache 2.2 server and virtual hosts.

This role enables very few Apache modules. Less than both CentOS 6.5 and Ubuntu 12.04 do by default. Keep that in mind as you debug any applications served by Apache 2.2.

**WARNING**: This role has currently only been tested with default configuration on Virtualbox VMs of CentOS 6.5 and Ubuntu 12.04. There is a LOT left to test before it's anything close to production ready.
##Requirements

Set ```hash_behaviour=merge``` in your ansible.cfg file.

##Role Variables
See the files in defaults for examples of most variables. If any are not self explanatory, see the Apache 2.2 docs. Each individual configuration option is named the same, or similar, to the Apache directive it controls.

* ```aspects_apache22_enabled```: Flag to enable or disable this role. Default is disabled.
* ```aspects_apache22_packages```: The various apache 2.2 packages you can install.
* ```aspects_apache22_default_vhosts```: Dictionary of default virtual host configurations. Used to disable or enable the default vhosts on Ubuntu.
* ```aspects_apache22_mods```: Dictionary of modules that you wish to enable or disable. Remember to ensure the correct package is installed before you try to use them.
* ```aspects_apache22_httpdconf```: Blocks of apache configuration. Use this to modify the defaults set by the distribution. These are sorted by key. Override blocks by setting the key value to "".
* ```aspects_apache22_vhosts```: Blocks of apache vhost configuration. Use this to add new vhosts. These are sorted by key. Override blocks by setting the key value to "".
* ```aspects_apache22_disabled_directives```: When you disable some modules, like autoindex, configuration directives might be left behind in files created by the OS's packages, resulting in invalid Apache configuration. Use this dictionary to define what directives should be removed, and which files to remove them from.

##Example Playbook

    - hosts:
      - foo.bar.com
      roles:
      - aspects_apache22
      vars:
        aspects_apache22_enabled: True
        aspects_apache22_packages:
          modauthmysql:
            state: "latest"
        aspects_apache22_mods:
          modauthmysql:
            Debian:
              enable: True
              links:
                loadfile: "auth_mysql.load"
        aspects_apache22_httpdconf:
          1defaultssl: |
            # 1defaultssl config from aspects_apache22/defaults/main.yml
            # CipherSuite set from https://community.qualys.com/blogs/securitylabs/2013/08/05/configuring-apache-nginx-and-openssl-for-forward-secrecy
            <IfModule mod_ssl.c>
              SSLProtocol All -SSLv2 -SSLv3 -TLSv1
              SSLHonorCipherOrder On
              SSLCipherSuite EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA384:EECDH+aRSA+SHA256:EECDH+aRSA+RC4:EECDH:EDH+aRSA:RC4:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:+RC4:RC4
            </IfModule>
        aspects_apache22_vhosts:
          2boringdotcom: |
            <VirtualHost *:80>
              ServerAdmin webmaster@boring.com
              ServerName boring.com
              ServerAlias www.boring.com
              DocumentRoot /var/www/boring.com
              AuthName "MySQL Testing"
              AuthType Basic
              AuthMySQLHost localhost
              AuthMySQLDB test
              AuthMySQLUserTable user_info
              AuthMySQLEnable On
              require valid-user
            </VirtualHost>

## Installing Modules
* Find the correct module in ```aspects_apache22_packages```
* Set ```state``` to ```latest``` or ```present```.

    aspects_apache22_packages:
      modulekey:
        state: "latest"

If the module is not in ```aspects_apache22_packages``` already, or doesn't have a package name for your OS, just do something like:

    aspects_apache22_packages:
      modulekey:
        state: "latest"
        OS: "package name"

## Overriding values
If you have a ```aspects_apache22_httpdconf``` section set in a group_vars file but you want to get rid of it, or modify it on an individual server, just find the key, and set in your host_vars file. That's why we use ```hash_behaviour=merge```.

##License

MIT


text:
layout: page
title: Guardian Company Executive Retreat
date: 2016-05-24
author: Walter Baker
tags: weekly links, java
status: published
summary: Morbi in sem mi. Aenean egestas iaculis arcu, nec rhoncus.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 02/15/2019
  endDate: 02/17/2019
  ctyhocn: ATLELHX
  groupCode: GCER
published: true
---
Curabitur mattis gravida augue, nec rutrum dui feugiat nec. Phasellus consectetur elit velit, vel placerat sem imperdiet ac. Suspendisse volutpat accumsan lorem, a consequat augue tempus sit amet. Vestibulum tempus, nibh ac tincidunt commodo, diam est aliquet metus, nec tempus tellus magna a magna. Donec sollicitudin facilisis ipsum et pretium. Nullam volutpat ornare lacinia. Suspendisse eget maximus risus.

1 Nunc commodo risus at pretium scelerisque
1 Phasellus fringilla mauris in risus euismod condimentum
1 Integer at felis vel justo tincidunt egestas vel in eros.

Nullam et ante eget ipsum gravida aliquam. Vivamus in consectetur est, ac molestie nibh. Sed maximus tortor nibh, vitae dictum libero venenatis at. Aenean id vulputate risus. Quisque ac enim ullamcorper, accumsan massa ac, faucibus sem. Mauris sit amet massa eros. Ut blandit metus vulputate, dapibus quam nec, ultrices sapien. Morbi vitae arcu ipsum. Nulla nunc dolor, mattis vel rhoncus eget, commodo sed nunc. Nam justo nibh, imperdiet euismod pretium et, consequat id arcu. Cras sed interdum nisi. Curabitur suscipit, enim sed tincidunt pharetra, mauris quam vehicula augue, a posuere dolor justo id odio. Maecenas nunc leo, ornare ac gravida non, pharetra sit amet ex. Proin quis hendrerit quam.
Sed risus ante, rutrum eu accumsan eu, accumsan ut risus. Integer ac dictum risus, vitae bibendum nisi. Nam sed dui ut elit fermentum vehicula. Curabitur urna enim, mollis vel lectus nec, ornare dapibus mauris. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi sit amet vestibulum sem. Curabitur pretium convallis leo sit amet lobortis. Praesent faucibus vel mauris quis ullamcorper. In posuere ligula eget fringilla malesuada. Nulla feugiat, massa vitae venenatis sagittis, tellus lectus vestibulum sem, nec maximus orci orci a libero.


text:
cmdname=$(basename $0)

echoerr() { if [[ $QUIET -ne 1 ]]; then echo "$@" 1>&2; fi }

usage() {
    cat << USAGE >&2
Usage:
    $cmdname host:port [-s] [-t timeout] [-- command args]
    -s | --strict               Only execute subcommand if the test succeeds
    -q | --quiet                Don't output any status messages
    -t TIMEOUT | --timeout=TIMEOUT
                                Timeout in seconds, zero for no timeout
    -- COMMAND ARGS             Execute command with args after the test finishes
USAGE
    exit 1
}

wait_for() {
    local wait_host=$1
    local wait_port=$2
    if [[ $TIMEOUT -gt 0 ]]; then
        echoerr "$cmdname: waiting $TIMEOUT seconds for $wait_host:$wait_port"
    else
        echoerr "$cmdname: waiting for $wait_host:$wait_port without a timeout"
    fi
    local start_ts=$(date +%s)
    while :
    do
        (echo > /dev/tcp/$wait_host/$wait_port) >/dev/null 2>&1
        local result=$?
        if [[ $result -eq 0 ]]; then
            local end_ts=$(date +%s)
            echoerr "$cmdname: $wait_host:$wait_port is available after $((end_ts - start_ts)) seconds"
            break
        fi
        sleep 1
    done
    return $result
}

wait_for_wrapper() {
    local wait_host=$1
    local wait_port=$2
    # In order to support SIGINT during timeout: http://unix.stackexchange.com/a/57692
    if [[ $QUIET -eq 1 ]]; then
        timeout $TIMEOUT $0 $wait_host:$wait_port --quiet --child --timeout=$TIMEOUT &
    else
        timeout $TIMEOUT $0 $wait_host:$wait_port --child --timeout=$TIMEOUT &
    fi
    PID=$!
    trap "kill -INT -$PID" INT
    wait $PID
    RESULT=$?
    if [[ $RESULT -ne 0 ]]; then
        echoerr "$cmdname: timeout occurred after waiting $TIMEOUT seconds for $wait_host:$wait_port"
    fi
    return $RESULT
}

parse_arguments() {
  local index=0
  while [[ $# -gt 0 ]]
  do
      case "$1" in
          *:* )
          hostport=(${1//:/ })
          HOST[$index]=${hostport[0]}
          PORT[$index]=${hostport[1]}
          shift 1
          ;;
          --child)
          CHILD=1
          shift 1
          ;;
          -q | --quiet)
          QUIET=1
          shift 1
          ;;
          -s | --strict)
          STRICT=1
          shift 1
          ;;
          -t)
          TIMEOUT="$2"
          if [[ $TIMEOUT == "" ]]; then break; fi
          shift 2
          ;;
          --timeout=*)
          TIMEOUT="${1#*=}"
          shift 1
          ;;
          --)
          shift
          CLI="$@"
          break
          ;;
          --help)
          usage
          ;;
          *)
          echoerr "Unknown argument: $1"
          usage
          ;;
      esac
      let index+=1
  done
  if [[ ${#HOST[@]} -eq 0 || ${#PORT[@]} -eq 0 ]]; then
      echoerr "Error: you need to provide a host and port to test."
      usage
  fi
}

iterate_hosts() {
  local result=0
  local index=0
  local wait_function=$1
  while [[ $result -eq 0 && $index -lt ${#HOST[@]} ]]; do
    ($wait_function ${HOST[$index]} ${PORT[$index]})
    result=$?
    let index+=1
  done
  echo $result
}

wait_for_services() {
  TIMEOUT=${TIMEOUT:-15}
  STRICT=${STRICT:-0}
  CHILD=${CHILD:-0}
  QUIET=${QUIET:-0}

  if [[ $CHILD -gt 0 ]]; then
      exit $(iterate_hosts wait_for)
  else
      if [[ $TIMEOUT -gt 0 ]]; then
          RESULT=$(iterate_hosts wait_for_wrapper)
      else
          RESULT=$(iterate_hosts wait_for)
      fi
  fi
}

parse_arguments "$@"
wait_for_services

if [[ $CLI != "" ]]; then
    if [[ $RESULT -ne 0 && $STRICT -eq 1 ]]; then
        echoerr "$cmdname: strict mode, refusing to execute subprocess"
        exit $RESULT
    fi
    exec $CLI
else
    exit $RESULT
fi


text:
<?php

namespace Proxy\__CG__\Newscoop\Entity;

/**
 * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR
 */
class Author extends \Newscoop\Entity\Author implements \Doctrine\ORM\Proxy\Proxy
{
    /**
     * @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
     *      three parameters, being respectively the proxy object to be initialized, the method that triggered the
     *      initialization process and an array of ordered parameters that were passed to that method.
     *
     * @see \Doctrine\Common\Persistence\Proxy::__setInitializer
     */
    public $__initializer__;

    /**
     * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
     *
     * @see \Doctrine\Common\Persistence\Proxy::__setCloner
     */
    public $__cloner__;

    /**
     * @var boolean flag indicating if this object was already initialized
     *
     * @see \Doctrine\Common\Persistence\Proxy::__isInitialized
     */
    public $__isInitialized__ = false;

    /**
     * @var array properties to be lazy loaded, with keys being the property
     *            names and values being their default values
     *
     * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
     */
    public static $lazyPropertiesDefaults = array();

    /**
     * @param \Closure $initializer
     * @param \Closure $cloner
     */
    public function __construct($initializer = null, $cloner = null)
    {

        $this->__initializer__ = $initializer;
        $this->__cloner__      = $cloner;
    }

    /**
     *
     * @return array
     */
    public function __sleep()
    {
        if ($this->__isInitialized__) {
            return array('__isInitialized__', 'id', 'first_name', 'user', 'last_name', 'email', 'type', 'skype', 'jabber', 'aim', 'biography', 'image', 'articles');
        }

        return array('__isInitialized__', 'id', 'first_name', 'user', 'last_name', 'email', 'type', 'skype', 'jabber', 'aim', 'biography', 'image', 'articles');
    }

    /**
     *
     */
    public function __wakeup()
    {
        if ( ! $this->__isInitialized__) {
            $this->__initializer__ = function (Author $proxy) {
                $proxy->__setInitializer(null);
                $proxy->__setCloner(null);

                $existingProperties = get_object_vars($proxy);

                foreach ($proxy->__getLazyProperties() as $property => $defaultValue) {
                    if ( ! array_key_exists($property, $existingProperties)) {
                        $proxy->$property = $defaultValue;
                    }
                }
            };

        }
    }

    /**
     *
     */
    public function __clone()
    {
        $this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', array());
    }

    /**
     * Forces initialization of the proxy
     */
    public function __load()
    {
        $this->__initializer__ && $this->__initializer__->__invoke($this, '__load', array());
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     */
    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     */
    public function __setInitialized($initialized)
    {
        $this->__isInitialized__ = $initialized;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     */
    public function __setInitializer(\Closure $initializer = null)
    {
        $this->__initializer__ = $initializer;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     */
    public function __getInitializer()
    {
        return $this->__initializer__;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     */
    public function __setCloner(\Closure $cloner = null)
    {
        $this->__cloner__ = $cloner;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific cloning logic
     */
    public function __getCloner()
    {
        return $this->__cloner__;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     * @static
     */
    public function __getLazyProperties()
    {
        return self::$lazyPropertiesDefaults;
    }

    /**
     * {@inheritDoc}
     */
    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int)  parent::getId();
        }

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', array());

        return parent::getId();
    }

    /**
     * {@inheritDoc}
     */
    public function setId($id)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setId', array($id));

        return parent::setId($id);
    }

    /**
     * {@inheritDoc}
     */
    public function getFirstName()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getFirstName', array());

        return parent::getFirstName();
    }

    /**
     * {@inheritDoc}
     */
    public function setFirstName($firstName)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setFirstName', array($firstName));

        return parent::setFirstName($firstName);
    }

    /**
     * {@inheritDoc}
     */
    public function getLastName()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getLastName', array());

        return parent::getLastName();
    }

    /**
     * {@inheritDoc}
     */
    public function setLastName($lastName)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setLastName', array($lastName));

        return parent::setLastName($lastName);
    }

    /**
     * {@inheritDoc}
     */
    public function getFullName()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getFullName', array());

        return parent::getFullName();
    }

    /**
     * {@inheritDoc}
     */
    public function getEmail()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getEmail', array());

        return parent::getEmail();
    }

    /**
     * {@inheritDoc}
     */
    public function setEmail($email)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setEmail', array($email));

        return parent::setEmail($email);
    }

    /**
     * {@inheritDoc}
     */
    public function getType()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getType', array());

        return parent::getType();
    }

    /**
     * {@inheritDoc}
     */
    public function setType(\Newscoop\Entity\AuthorType $type)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setType', array($type));

        return parent::setType($type);
    }

    /**
     * {@inheritDoc}
     */
    public function getSkype()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getSkype', array());

        return parent::getSkype();
    }

    /**
     * {@inheritDoc}
     */
    public function setSkype($skype)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setSkype', array($skype));

        return parent::setSkype($skype);
    }

    /**
     * {@inheritDoc}
     */
    public function getJabber()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getJabber', array());

        return parent::getJabber();
    }

    /**
     * {@inheritDoc}
     */
    public function setJabber($jabber)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setJabber', array($jabber));

        return parent::setJabber($jabber);
    }

    /**
     * {@inheritDoc}
     */
    public function getAim()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getAim', array());

        return parent::getAim();
    }

    /**
     * {@inheritDoc}
     */
    public function setAim($aim)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setAim', array($aim));

        return parent::setAim($aim);
    }

    /**
     * {@inheritDoc}
     */
    public function getBiography()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getBiography', array());

        return parent::getBiography();
    }

    /**
     * {@inheritDoc}
     */
    public function setBiography($biography)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setBiography', array($biography));

        return parent::setBiography($biography);
    }

    /**
     * {@inheritDoc}
     */
    public function getImage()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getImage', array());

        return parent::getImage();
    }

    /**
     * {@inheritDoc}
     */
    public function setImage($image)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setImage', array($image));

        return parent::setImage($image);
    }

    /**
     * {@inheritDoc}
     */
    public function getUser()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getUser', array());

        return parent::getUser();
    }

    /**
     * {@inheritDoc}
     */
    public function setUser(\Newscoop\Entity\User $user)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setUser', array($user));

        return parent::setUser($user);
    }

    /**
     * {@inheritDoc}
     */
    public function getView()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getView', array());

        return parent::getView();
    }

    /**
     * {@inheritDoc}
     */
    public function getArticles()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getArticles', array());

        return parent::getArticles();
    }

}


text:
using Microsoft.AspNetCore.Mvc;

namespace WithFeatureFolders.Features.Ninjas
{
    [Route("/Ninjas/Swords/", Name ="NinjaSwords")]
    public class SwordsController : Controller
    {
        public IActionResult Index()
        {
            var swords = new string[] {"Katana", "Ninjago"};
            return View(swords);
        }
    }
}


text:
import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { CurrentUserService } from './current-user.service';
import { CurrentUser } from '../dto/current-user';
import { BackendCommsService } from './backend-comms.service';

/**
 * Ensure the user cannot navigate to any routes with
 * this guard if they haven't logged in. The guard will
 * instead send the user to the login screen.
 */
@Injectable()
export class LoginGuard implements CanActivate {
  constructor(
    private backendCommsService: BackendCommsService,
    private currentUserService: CurrentUserService) {

  }

  /**
   * The application has just loaded. The user may
   * have still be logged in - so check the backend first
   */
  private checkIfLoggedIn(currentUrl: string): Promise<boolean> {
    this.currentUserService.initialApplicationStart = false;
    return this.backendCommsService
      .get('CurrentUser')
      .then((value: CurrentUser) => {
        return this.processCurrentUser(value, currentUrl);
      });
  }

  /**
   * We just received a user object from the backend.
   * Check the login status and redirect if required.
   */
  private processCurrentUser(dto: CurrentUser, currentUrl: string): boolean {
    if (dto.username != null) {
      this.currentUserService.login(dto.username);
      return true;
    } else {
      this.currentUserService.redirectToLogin(currentUrl);
      return false;
    }
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    if (this.currentUserService.isLoggedIn) {
      return true;
    }

    if (this.currentUserService.initialApplicationStart) {
      return this.checkIfLoggedIn(state.url);
    }

    this.currentUserService.redirectToLogin(state.url);
    return false;
  }
}


text:
Capybara::SpecHelper.spec '#has_select?' do
  before { @session.visit('/form') }

  it "should be true if the field is on the page" do
    expect(@session).to have_select('Locale')
    expect(@session).to have_select('form_region')
    expect(@session).to have_select('Languages')
    expect(@session).to have_select(:'Languages')
  end

  it "should be false if the field is not on the page" do
    expect(@session).not_to have_select('Monkey')
  end

  context 'with selected value' do
    it "should be true if a field with the given value is on the page" do
      expect(@session).to have_select('form_locale', :selected => 'English')
      expect(@session).to have_select('Region', :selected => 'Norway')
      expect(@session).to have_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns'
      ])
    end

    it "should be false if the given field is not on the page" do
      expect(@session).not_to have_select('Locale', :selected => 'Swedish')
      expect(@session).not_to have_select('Does not exist', :selected => 'John')
      expect(@session).not_to have_select('City', :selected => 'Not there')
      expect(@session).not_to have_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns', 'Nonexistant'
      ])
      expect(@session).not_to have_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs', 'Boxers', 'Commando', "Frenchman's Pantalons", 'Long Johns'
      ])
      expect(@session).not_to have_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs','Commando', "Frenchman's Pantalons"
      ])
    end

    it "should be true after the given value is selected" do
      @session.select('Swedish', :from => 'Locale')
      expect(@session).to have_select('Locale', :selected => 'Swedish')
    end

    it "should be false after a different value is selected" do
      @session.select('Swedish', :from => 'Locale')
      expect(@session).not_to have_select('Locale', :selected => 'English')
    end

    it "should be true after the given values are selected" do
      @session.select('Boxers', :from => 'Underwear')
      expect(@session).to have_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs', 'Boxers', 'Commando', "Frenchman's Pantalons", 'Long Johns'
      ])
    end

    it "should be false after one of the values is unselected" do
      @session.unselect('Briefs', :from => 'Underwear')
      expect(@session).not_to have_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns'
      ])
    end
  end

  context 'with exact options' do
    it "should be true if a field with the given options is on the page" do
      expect(@session).to have_select('Region', :options => ['Norway', 'Sweden', 'Finland'])
      expect(@session).to have_select('Tendency', :options => [])
    end

    it "should be false if the given field is not on the page" do
      expect(@session).not_to have_select('Locale', :options => ['Swedish'])
      expect(@session).not_to have_select('Does not exist', :options => ['John'])
      expect(@session).not_to have_select('City', :options => ['London', 'Made up city'])
      expect(@session).not_to have_select('Region', :options => ['Norway', 'Sweden'])
      expect(@session).not_to have_select('Region', :options => ['Norway', 'Norway', 'Norway'])
    end
  end

  context 'with partial options' do
    it "should be true if a field with the given partial options is on the page" do
      expect(@session).to have_select('Region', :with_options => ['Norway', 'Sweden'])
      expect(@session).to have_select('City', :with_options => ['London'])
    end

    it "should be false if a field with the given partial options is not on the page" do
      expect(@session).not_to have_select('Locale', :with_options => ['Uruguayan'])
      expect(@session).not_to have_select('Does not exist', :with_options => ['John'])
      expect(@session).not_to have_select('Region', :with_options => ['Norway', 'Sweden', 'Finland', 'Latvia'])
    end
  end
end

Capybara::SpecHelper.spec '#has_no_select?' do
  before { @session.visit('/form') }

  it "should be false if the field is on the page" do
    expect(@session).not_to have_no_select('Locale')
    expect(@session).not_to have_no_select('form_region')
    expect(@session).not_to have_no_select('Languages')
  end

  it "should be true if the field is not on the page" do
    expect(@session).to have_no_select('Monkey')
  end

  context 'with selected value' do
    it "should be false if a field with the given value is on the page" do
      expect(@session).not_to have_no_select('form_locale', :selected => 'English')
      expect(@session).not_to have_no_select('Region', :selected => 'Norway')
      expect(@session).not_to have_no_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns'
      ])
    end

    it "should be true if the given field is not on the page" do
      expect(@session).to have_no_select('Locale', :selected => 'Swedish')
      expect(@session).to have_no_select('Does not exist', :selected => 'John')
      expect(@session).to have_no_select('City', :selected => 'Not there')
      expect(@session).to have_no_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns', 'Nonexistant'
      ])
      expect(@session).to have_no_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs', 'Boxers', 'Commando', "Frenchman's Pantalons", 'Long Johns'
      ])
      expect(@session).to have_no_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs','Commando', "Frenchman's Pantalons"
      ])
    end

    it "should be false after the given value is selected" do
      @session.select('Swedish', :from => 'Locale')
      expect(@session).not_to have_no_select('Locale', :selected => 'Swedish')
    end

    it "should be true after a different value is selected" do
      @session.select('Swedish', :from => 'Locale')
      expect(@session).to have_no_select('Locale', :selected => 'English')
    end

    it "should be false after the given values are selected" do
      @session.select('Boxers', :from => 'Underwear')
      expect(@session).not_to have_no_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs', 'Boxers', 'Commando', "Frenchman's Pantalons", 'Long Johns'
      ])
    end

    it "should be true after one of the values is unselected" do
      @session.unselect('Briefs', :from => 'Underwear')
      expect(@session).to have_no_select('Underwear', :selected => [
        'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns'
      ])
    end
  end

  context 'with exact options' do
    it "should be false if a field with the given options is on the page" do
      expect(@session).not_to have_no_select('Region', :options => ['Norway', 'Sweden', 'Finland'])
    end

    it "should be true if the given field is not on the page" do
      expect(@session).to have_no_select('Locale', :options => ['Swedish'])
      expect(@session).to have_no_select('Does not exist', :options => ['John'])
      expect(@session).to have_no_select('City', :options => ['London', 'Made up city'])
      expect(@session).to have_no_select('Region', :options => ['Norway', 'Sweden'])
      expect(@session).to have_no_select('Region', :options => ['Norway', 'Norway', 'Norway'])
    end
  end

  context 'with partial options' do
    it "should be false if a field with the given partial options is on the page" do
      expect(@session).not_to have_no_select('Region', :with_options => ['Norway', 'Sweden'])
      expect(@session).not_to have_no_select('City', :with_options => ['London'])
    end

    it "should be true if a field with the given partial options is not on the page" do
      expect(@session).to have_no_select('Locale', :with_options => ['Uruguayan'])
      expect(@session).to have_no_select('Does not exist', :with_options => ['John'])
      expect(@session).to have_no_select('Region', :with_options => ['Norway', 'Sweden', 'Finland', 'Latvia'])
    end
  end
end


text:
from twisted.trial import unittest
from twisted.application import service
from cStringIO import StringIO
import gc

from foolscap.api import Referenceable, Copyable, RemoteCopy, \
     flushEventualQueue, serialize, unserialize, Tub
from foolscap.referenceable import RemoteReference
from foolscap.tokens import Violation
from foolscap.util import allocate_tcp_port
from foolscap.test.common import ShouldFailMixin

class Foo:
    # instances of non-Copyable classes are not serializable
    pass
class Bar(Copyable, RemoteCopy):
    # but if they're Copyable, they're ok
    typeToCopy = "bar"
    copytype = "bar"
    pass

class Serialize(unittest.TestCase, ShouldFailMixin):

    def setUp(self):
        self.s = service.MultiService()
        self.s.startService()

    def tearDown(self):
        d = self.s.stopService()
        d.addCallback(flushEventualQueue)
        return d

    def NOT_test_data_synchronous(self):
        obj = ["look at the pretty graph", 3, True]
        obj.append(obj) # and look at the pretty cycle
        data = serialize(obj)
        obj2 = unserialize(data)
        self.failUnlessEqual(obj2[1], 3)
        self.failUnlessIdentical(obj2[3], obj2)

    def test_data(self):
        obj = ["simple graph", 3, True]
        d = serialize(obj)
        d.addCallback(lambda data: unserialize(data))
        def _check(obj2):
            self.failUnlessEqual(obj2[1], 3)
        d.addCallback(_check)
        return d

    def test_cycle(self):
        obj = ["look at the pretty graph", 3, True]
        obj.append(obj) # and look at the pretty cycle
        d = serialize(obj)
        d.addCallback(lambda data: unserialize(data))
        def _check(obj2):
            self.failUnlessEqual(obj2[1], 3)
            self.failUnlessIdentical(obj2[3], obj2)
        d.addCallback(_check)
        return d

    def test_copyable(self):
        obj = ["fire pretty", Bar()]
        d = serialize(obj)
        d.addCallback(lambda data: unserialize(data))
        def _check(obj2):
            self.failUnless(isinstance(obj2[1], Bar))
            self.failIfIdentical(obj[1], obj2[1])
        d.addCallback(_check)
        return d

    def test_data_outstream(self):
        obj = ["look at the pretty graph", 3, True]
        obj.append(obj) # and look at the pretty cycle
        b = StringIO()
        d = serialize(obj, outstream=b)
        def _out(res):
            self.failUnlessIdentical(res, b)
            return b.getvalue()
        d.addCallback(_out)
        d.addCallback(lambda data: unserialize(data))
        def _check(obj2):
            self.failUnlessEqual(obj2[1], 3)
            self.failUnlessIdentical(obj2[3], obj2)
        d.addCallback(_check)
        return d

    def test_unhandled_objects(self):
        obj1 = [1, Referenceable()]
        d = self.shouldFail(Violation, "1",
                            "This object can only be serialized by a broker",
                            serialize, obj1)
        obj2 = [1, Foo()]
        d.addCallback(lambda ign:
                      self.shouldFail(Violation, "2",
                                      "cannot serialize <foolscap.test.test_serialize.Foo instance",
                                      serialize, obj2))
        return d

    def test_referenceable(self):
        t1 = Tub()
        t1.setServiceParent(self.s)
        portnum = allocate_tcp_port()
        t1.listenOn("tcp:%d:interface=127.0.0.1" % portnum)
        t1.setLocation("127.0.0.1:%d" % portnum)
        r1 = Referenceable()
        # the serialized blob can't keep the reference alive, so you must
        # arrange for that separately
        t1.registerReference(r1)
        t2 = Tub()
        t2.setServiceParent(self.s)
        obj = ("graph tangly", r1)
        d = t1.serialize(obj)
        del r1; del obj
        def _done(data):
            self.failUnless("their-reference" in data)
            return data
        d.addCallback(_done)
        d.addCallback(lambda data: t2.unserialize(data))
        def _check(obj2):
            self.failUnlessEqual(obj2[0], "graph tangly")
            self.failUnless(isinstance(obj2[1], RemoteReference))
        d.addCallback(_check)
        return d
    test_referenceable.timeout = 5

    def test_referenceables_die(self):
        # serialized data will not keep the referenceable alive
        t1 = Tub()
        t1.setServiceParent(self.s)
        portnum = allocate_tcp_port()
        t1.listenOn("tcp:%d:interface=127.0.0.1" % portnum)
        t1.setLocation("127.0.0.1:%d" % portnum)
        r1 = Referenceable()
        t2 = Tub()
        t2.setServiceParent(self.s)
        obj = ("graph tangly", r1)
        d = t1.serialize(obj)
        del r1; del obj
        gc.collect()
        d.addCallback(lambda data:
                      self.shouldFail(KeyError, "test_referenceables_die",
                                      "unable to find reference for name",
                                      t2.unserialize, data))
        return d
    test_referenceables_die.timeout = 5


text:
/**
 *
 */
/**
 * @author Leeyon
 *
 */
package com.leeyonsoft.clonepintrest.application;


text:
//**********************************************************************************************************************************************************
//Link
//**********************************************************************************************************************************************************
/**
 * Extends mxShape.
 */
function mxShapeMockupLink(bounds, fill, stroke, strokewidth)
{
	mxShape.call(this);
	this.bounds = bounds;
	this.fill = fill;
	this.stroke = stroke;
	this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};

/**
 * Extends mxShape.
 */
mxUtils.extend(mxShapeMockupLink, mxShape);

mxShapeMockupLink.prototype.cst = {
		LINK_TEXT : 'linkText',
		TEXT_SIZE : 'textSize',
		TEXT_COLOR : 'textColor',
		SHAPE_LINK : 'mxgraph.mockup.text.link'
};

/**
 * Function: paintVertexShape
 *
 * Paints the vertex shape.
 */
mxShapeMockupLink.prototype.paintVertexShape = function(c, x, y, w, h)
{
	var linkText = mxUtils.getValue(this.style, mxShapeMockupLink.prototype.cst.LINK_TEXT, 'Link');
	var textSize = mxUtils.getValue(this.style, mxShapeMockupLink.prototype.cst.TEXT_SIZE, '17');
	var textColor = mxUtils.getValue(this.style, mxShapeMockupLink.prototype.cst.TEXT_COLOR, '#0000ff');

	c.translate(x, y);
	var width = mxUtils.getSizeForString(linkText, textSize, mxConstants.DEFAULT_FONTFAMILY).width;
	c.setStrokeColor(textColor);
	c.setFontSize(textSize);
	c.setFontColor(textColor);

	c.text(w * 0.5, h * 0.5, 0, 0, linkText, mxConstants.ALIGN_CENTER, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);

	c.begin();
	c.moveTo(w * 0.5 - width * 0.5, (h + parseInt(textSize, 10)) * 0.5);
	c.lineTo(w * 0.5 + width * 0.5, (h + parseInt(textSize, 10)) * 0.5);
	c.stroke();
};

mxCellRenderer.prototype.defaultShapes[mxShapeMockupLink.prototype.cst.SHAPE_LINK] = mxShapeMockupLink;

//**********************************************************************************************************************************************************
//Link Bar
//**********************************************************************************************************************************************************
/**
 * Extends mxShape.
 */
function mxShapeMockupLinkBar(bounds, fill, stroke, strokewidth)
{
	mxShape.call(this);
	this.bounds = bounds;
	this.fill = fill;
	this.stroke = stroke;
	this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};

/**
 * Extends mxShape.
 */
mxUtils.extend(mxShapeMockupLinkBar, mxShape);

mxShapeMockupLinkBar.prototype.cst = {
		MAIN_TEXT : 'mainText',
		SHAPE_LINK_BAR : 'mxgraph.mockup.text.linkBar',
		TEXT_COLOR : 'textColor',
		TEXT_COLOR2 : 'textColor2',
		STROKE_COLOR2 : 'strokeColor2',
		FILL_COLOR2 : 'fillColor2',
		SELECTED : '+',			//must be 1 char
		TEXT_SIZE : 'textSize'
};

/**
 * Function: paintVertexShape
 *
 * Paints the vertex shape.
 */
mxShapeMockupLinkBar.prototype.paintVertexShape = function(c, x, y, w, h)
{
	var textStrings = mxUtils.getValue(this.style, mxShapeMockupLinkBar.prototype.cst.MAIN_TEXT, '+Button 1, Button 2, Button 3').toString().split(',');
	var fontColor = mxUtils.getValue(this.style, mxShapeMockupLinkBar.prototype.cst.TEXT_COLOR, '#666666');
	var selectedFontColor = mxUtils.getValue(this.style, mxShapeMockupLinkBar.prototype.cst.TEXT_COLOR2, '#ffffff');
	var fontSize = mxUtils.getValue(this.style, mxShapeMockupLinkBar.prototype.cst.TEXT_SIZE, '17').toString();
	var frameColor = mxUtils.getValue(this.style, mxConstants.STYLE_STROKECOLOR, '#666666');
	var separatorColor = mxUtils.getValue(this.style, mxShapeMockupLinkBar.prototype.cst.STROKE_COLOR2, '#c4c4c4');
	var bgColor = mxUtils.getValue(this.style, mxConstants.STYLE_FILLCOLOR, '#ffffff');
	var selectedFillColor = mxUtils.getValue(this.style, mxShapeMockupLinkBar.prototype.cst.FILL_COLOR2, '#008cff');
	var buttonNum = textStrings.length;
	var buttonWidths = new Array(buttonNum);
	var buttonTotalWidth = 0;
	var selectedButton = -1;
	var rSize = 10; //rounding size
	var labelOffset = 5;

	for (var i = 0; i < buttonNum; i++)
	{
		var buttonText = textStrings[i];

		if(buttonText.charAt(0) === mxShapeMockupLinkBar.prototype.cst.SELECTED)
		{
			buttonText = textStrings[i].substring(1);
			selectedButton = i;
		}

		var currW = mxUtils.getSizeForString(buttonText, fontSize, mxConstants.DEFAULT_FONTFAMILY).width;

		if (currW === 0)
		{
			buttonWidths[i] = 42;
		}
		else
		{
			buttonWidths[i] = currW;
		}

		buttonTotalWidth += buttonWidths[i];
	}

	var trueH = Math.max(h, fontSize * 1.5, 20);
	var minW = 2 * labelOffset * buttonNum + buttonTotalWidth;
	var trueW = Math.max(w, minW);

	c.translate(x, y);
	this.background(c, trueW, trueH, rSize, buttonNum, buttonWidths, labelOffset, minW, frameColor, separatorColor, bgColor, selectedFillColor, selectedButton);
	c.setShadow(false);

	var currWidth = 0;

	for (var i = 0; i < buttonNum; i++)
	{
		if (i === selectedButton)
		{
			c.setFontColor(selectedFontColor);
			c.setStrokeColor(selectedFontColor);
		}
		else
		{
			c.setFontColor(fontColor);
			c.setStrokeColor(fontColor);
		}

		currWidth = currWidth + labelOffset;
		this.buttonText(c, currWidth, trueH, textStrings[i], buttonWidths[i], fontSize, minW, trueW);
		currWidth = currWidth + buttonWidths[i] + labelOffset;
	}
};

mxShapeMockupLinkBar.prototype.background = function(c, w, h, rSize, buttonNum, buttonWidths, labelOffset, minW, frameColor, separatorColor, bgColor, selectedFillColor, selectedButton)
{
	c.begin();

	//draw the frame
	c.setStrokeColor(frameColor);
	c.setFillColor(bgColor);
	c.rect(0, 0, w, h);
	c.fillAndStroke();

	//draw the button separators
	c.setStrokeColor(separatorColor);
	c.begin();

	for (var i = 1; i < buttonNum; i++)
	{
		if (i !== selectedButton && i !== (selectedButton + 1))
		{
			var currWidth = 0;

			for (var j = 0; j < i; j++)
			{
				currWidth += buttonWidths[j] + 2 * labelOffset;
			}

			currWidth = currWidth * w / minW;
			c.moveTo(currWidth, 0);
			c.lineTo(currWidth, h);
		}
	}

	c.stroke();

	//draw the selected button
	var buttonLeft = 0;
	c.setFillColor(selectedFillColor);

	for (var i = 0; i < selectedButton; i++)
	{
		buttonLeft += buttonWidths[i] + 2 * labelOffset;
	}

	buttonLeft = buttonLeft * w / minW;
	var buttonRight = (buttonWidths[selectedButton] + 2 * labelOffset) * w / minW;
	buttonRight += buttonLeft;

	if (selectedButton === 0)
	{
		c.rect(0, 0, buttonRight, h);
		c.fill();
	}
	else if (selectedButton === buttonNum - 1)
	{
		c.rect(buttonLeft, 0, buttonRight - buttonLeft, h);
		c.fill();
	}
	else if (selectedButton !== -1)
	{
		c.rect(buttonLeft, 0, buttonRight - buttonLeft, h);
		c.fill();
	}

	//draw the frame again, to achieve a nicer effect
	c.setStrokeColor(frameColor);
	c.setFillColor(bgColor);
	c.rect(0, 0, w, h);
	c.stroke();
};

mxShapeMockupLinkBar.prototype.buttonText = function(c, w, h, textString, buttonWidth, fontSize, minW, trueW)
{
	if(textString.charAt(0) === mxShapeMockupLinkBar.prototype.cst.SELECTED)
	{
		textString = textString.substring(1);
	}

	c.begin();
	c.setFontSize(fontSize);
	c.text((w + buttonWidth * 0.5) * trueW / minW, h * 0.5, 0, 0, textString, mxConstants.ALIGN_CENTER, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);

	var textW = mxUtils.getSizeForString(textString, fontSize, mxConstants.DEFAULT_FONTFAMILY).width * 0.5;

	if (textString !== null && textString !== '')
	{
		c.begin();
		c.moveTo((w + buttonWidth * 0.5) * trueW / minW - textW, h * 0.5 + fontSize * 0.5);
		c.lineTo((w + buttonWidth * 0.5) * trueW / minW + textW, h * 0.5 + fontSize * 0.5);
		c.stroke();
	}
};

mxCellRenderer.prototype.defaultShapes[mxShapeMockupLinkBar.prototype.cst.SHAPE_LINK_BAR] = mxShapeMockupLinkBar;

//**********************************************************************************************************************************************************
//Callout
//**********************************************************************************************************************************************************
/**
 * Extends mxShape.
 */
function mxShapeMockupCallout(bounds, fill, stroke, strokewidth)
{
	mxShape.call(this);
	this.bounds = bounds;
	this.fill = fill;
	this.stroke = stroke;
	this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};

/**
 * Extends mxShape.
 */
mxUtils.extend(mxShapeMockupCallout, mxShape);

mxShapeMockupCallout.prototype.cst = {
		CALLOUT_TEXT : 'linkText',
		CALLOUT_DIR : 'callDir',
		CALLOUT_STYLE : 'callStyle',
		STYLE_LINE : 'line',
		STYLE_RECT : 'rect',
		STYLE_ROUNDRECT : 'roundRect',
		DIR_NW : 'NW',
		DIR_NE : 'NE',
		DIR_SE : 'SE',
		DIR_SW : 'SW',
		TEXT_SIZE : 'textSize',
		TEXT_COLOR : 'textColor',
		SHAPE_CALLOUT : 'mxgraph.mockup.text.callout'
};

/**
 * Function: paintVertexShape
 *
 * Paints the vertex shape.
 */
mxShapeMockupCallout.prototype.paintVertexShape = function(c, x, y, w, h)
{
	var calloutText = mxUtils.getValue(this.style, mxShapeMockupCallout.prototype.cst.CALLOUT_TEXT, 'Callout');
	var textSize = mxUtils.getValue(this.style, mxShapeMockupCallout.prototype.cst.TEXT_SIZE, '17');
	var textColor = mxUtils.getValue(this.style, mxShapeMockupCallout.prototype.cst.TEXT_COLOR, '#666666');
	var callStyle = mxUtils.getValue(this.style, mxShapeMockupCallout.prototype.cst.CALLOUT_STYLE, mxShapeMockupCallout.prototype.cst.STYLE_LINE);
	var callDir = mxUtils.getValue(this.style, mxShapeMockupCallout.prototype.cst.CALLOUT_DIR, mxShapeMockupCallout.prototype.cst.DIR_NW);
	var textWidth = mxUtils.getSizeForString(calloutText, textSize, mxConstants.DEFAULT_FONTFAMILY).width;
	textWidth = textWidth * 1.2;

	if (textWidth == 0)
	{
		textWidth = 70;
	}

	c.translate(x, y);
	c.setFontSize(textSize);
	c.setFontColor(textColor);
	var callH = textSize * 1.5;

	if (callDir === mxShapeMockupCallout.prototype.cst.DIR_NW)
	{
		if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_LINE)
		{
			c.begin();
			c.moveTo(0, callH);
			c.lineTo(textWidth, callH);
			c.lineTo(w, h);
			c.stroke();
		}
		else if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_RECT)
		{
			c.rect(0,0, textWidth, callH);
			c.fillAndStroke();
			c.begin();
			c.moveTo(textWidth * 0.5, callH);
			c.lineTo(w, h);
			c.stroke();
		}
		else if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_ROUNDRECT)
		{
			c.roundrect(0, 0, textWidth, callH, callH * 0.25, callH * 0.25);
			c.fillAndStroke();
			c.begin();
			c.moveTo(textWidth * 0.5, callH);
			c.lineTo(w, h);
			c.stroke();
		}

		c.text(textWidth * 0.5, callH * 0.5, 0, 0, calloutText, mxConstants.ALIGN_CENTER, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);
	}
	else if (callDir === mxShapeMockupCallout.prototype.cst.DIR_NE)
	{
		if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_LINE)
		{
			c.begin();
			c.moveTo(w, callH);
			c.lineTo(w - textWidth, callH);
			c.lineTo(0, h);
			c.stroke();
		}
		else if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_RECT)
		{
			c.rect(w - textWidth,0, textWidth, callH);
			c.fillAndStroke();
			c.begin();
			c.moveTo(w - textWidth * 0.5, callH);
			c.lineTo(0, h);
			c.stroke();
		}
		else if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_ROUNDRECT)
		{
			c.roundrect(w - textWidth,0, textWidth, callH, callH * 0.25, callH * 0.25);
			c.fillAndStroke();
			c.begin();
			c.moveTo(w - textWidth * 0.5, callH);
			c.lineTo(0, h);
			c.stroke();
		}

		c.text(w - textWidth * 0.5, callH * 0.5, 0, 0, calloutText, mxConstants.ALIGN_CENTER, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);
	}
	else if (callDir === mxShapeMockupCallout.prototype.cst.DIR_SE)
	{
		if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_LINE)
		{
			c.begin();
			c.moveTo(w, h);
			c.lineTo(w - textWidth, h);
			c.lineTo(0, 0);
			c.stroke();
		}
		else if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_RECT)
		{
			c.rect(w - textWidth, h - callH, textWidth, callH);
			c.fillAndStroke();
			c.begin();
			c.moveTo(w - textWidth * 0.5, h - callH);
			c.lineTo(0, 0);
			c.stroke();
		}
		else if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_ROUNDRECT)
		{
			c.roundrect(w - textWidth,h - callH, textWidth, callH, callH * 0.25, callH * 0.25);
			c.fillAndStroke();
			c.begin();
			c.moveTo(w - textWidth * 0.5, h - callH);
			c.lineTo(0, 0);
			c.stroke();
		}

		c.text(w - textWidth * 0.5, h - callH * 0.5, 0, 0, calloutText, mxConstants.ALIGN_CENTER, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);
	}
	else if (callDir === mxShapeMockupCallout.prototype.cst.DIR_SW)
	{
		if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_LINE)
		{
			c.begin();
			c.moveTo(0, h);
			c.lineTo(textWidth, h);
			c.lineTo(w, 0);
			c.stroke();
		}
		else if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_RECT)
		{
			c.rect(0, h - callH, textWidth, callH);
			c.fillAndStroke();
			c.begin();
			c.moveTo(textWidth * 0.5, h - callH);
			c.lineTo(w, 0);
			c.stroke();
		}
		else if (callStyle === mxShapeMockupCallout.prototype.cst.STYLE_ROUNDRECT)
		{
			c.roundrect(0, h - callH, textWidth, callH, callH * 0.25, callH * 0.25);
			c.fillAndStroke();
			c.begin();
			c.moveTo(textWidth * 0.5, h - callH);
			c.lineTo(w, 0);
			c.stroke();
		}

		c.text(textWidth * 0.5, h - callH * 0.5, 0, 0, calloutText, mxConstants.ALIGN_CENTER, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);
	}

};

mxCellRenderer.prototype.defaultShapes[mxShapeMockupCallout.prototype.cst.SHAPE_CALLOUT] = mxShapeMockupCallout;

//**********************************************************************************************************************************************************
//Sticky Note
//**********************************************************************************************************************************************************
/**
 * Extends mxShape.
 */
function mxShapeMockupStickyNote(bounds, fill, stroke, strokewidth)
{
	mxShape.call(this);
	this.bounds = bounds;
	this.fill = fill;
	this.stroke = stroke;
	this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};

/**
 * Extends mxShape.
 */
mxUtils.extend(mxShapeMockupStickyNote, mxShape);

mxShapeMockupStickyNote.prototype.cst = {
		MAIN_TEXT : 'mainText',
		TEXT_COLOR : 'textColor',
		TEXT_SIZE : 'textSize',
		SHAPE_STICKY_NOTE : 'mxgraph.mockup.text.stickyNote'
};

/**
 * Function: paintVertexShape
 *
 * Paints the vertex shape.
 */
mxShapeMockupStickyNote.prototype.paintVertexShape = function(c, x, y, w, h)
{
	c.translate(x, y);
	this.background(c, w, h);
	c.setShadow(false);
	this.foreground(c, w, h);
};

mxShapeMockupStickyNote.prototype.background = function(c, w, h)
{
	c.setFillColor('#ffffcc');
	c.begin();
	c.moveTo(w * 0.03, h * 0.07);
	c.lineTo(w * 0.89, h * 0.06);
	c.arcTo(2.81 * w, 2.92 * h, 1, 0, 0, w * 0.99, h * 0.98);
	c.lineTo(w * 0.09, h * 0.99);
	c.arcTo(2.81 * w, 2.92 * h, 1, 0, 1, w * 0.03, h * 0.07);
	c.close();
	c.fill();
};

mxShapeMockupStickyNote.prototype.foreground = function(c, w, h)
{
	var mainText = mxUtils.getValue(this.style, mxShapeMockupStickyNote.prototype.cst.MAIN_TEXT, 'Note line 1,Note line 2,Note line 3').toString().split(',');
	var fontColor = mxUtils.getValue(this.style, mxShapeMockupStickyNote.prototype.cst.TEXT_COLOR, '#666666').toString();
	var fontSize = mxUtils.getValue(this.style, mxShapeMockupStickyNote.prototype.cst.TEXT_SIZE, '17').toString();

	c.setFillColor('#ff3300');
	c.begin();
	c.moveTo(w * 0.28 , 0);
	c.lineTo(w * 0.59, 0);
	c.lineTo(w * 0.6, h * 0.12);
	c.lineTo(w * 0.28, h * 0.13);
	c.close();
	c.fill();

	c.setFontSize(fontSize);
	c.setFontColor(fontColor);
	var lineNum = mainText.length;
	var textH = lineNum * fontSize * 1.5;

	for (var i = 0; i < mainText.length; i++)
	{
		c.text(w / 2, (h - textH) / 2 + i * fontSize * 1.5 + fontSize * 0.75, 0, 0, mainText[i], mxConstants.ALIGN_CENTER, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);
	}
};

mxCellRenderer.prototype.defaultShapes[mxShapeMockupStickyNote.prototype.cst.SHAPE_STICKY_NOTE] = mxShapeMockupStickyNote;

//**********************************************************************************************************************************************************
//Bulleted List
//**********************************************************************************************************************************************************
/**
 * Extends mxShape.
 */
function mxShapeMockupBulletedList(bounds, fill, stroke, strokewidth)
{
	mxShape.call(this);
	this.bounds = bounds;
	this.fill = fill;
	this.stroke = stroke;
	this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};

/**
 * Extends mxShape.
 */
mxUtils.extend(mxShapeMockupBulletedList, mxShape);

mxShapeMockupBulletedList.prototype.cst = {
		MAIN_TEXT : 'mainText',
		TEXT_COLOR : 'textColor',
		TEXT_SIZE : 'textSize',
		BULLET_STYLE : 'bulletStyle',
		STYLE_HYPHEN : 'hyphen',
		STYLE_NUM : 'number',
		STYLE_DOT : 'dot',
		SHAPE_BULLETED_LIST : 'mxgraph.mockup.text.bulletedList'
};

/**
 * Function: paintVertexShape
 *
 * Paints the vertex shape.
 */
mxShapeMockupBulletedList.prototype.paintVertexShape = function(c, x, y, w, h)
{
	c.translate(x, y);
	this.background(c, w, h);
	c.setShadow(false);
	this.foreground(c, w, h);
};

mxShapeMockupBulletedList.prototype.background = function(c, w, h)
{
	c.rect(0, 0, w, h);
	c.fillAndStroke();
};

mxShapeMockupBulletedList.prototype.foreground = function(c, w, h)
{
	var mainText = mxUtils.getValue(this.style, mxShapeMockupBulletedList.prototype.cst.MAIN_TEXT, 'Note line 1,Note line 2,Note line 3').toString().split(',');
	var fontColor = mxUtils.getValue(this.style, mxShapeMockupBulletedList.prototype.cst.TEXT_COLOR, '#666666');
	var fontSize = mxUtils.getValue(this.style, mxShapeMockupBulletedList.prototype.cst.TEXT_SIZE, '17');
	var bulletStyle = mxUtils.getValue(this.style, mxShapeMockupBulletedList.prototype.cst.BULLET_STYLE, 'none');

	c.setFontColor(fontColor);
	c.setFontSize(fontSize);

	var bullet = '';

	for (var i = 0; i < mainText.length; i++)
	{
		var currText = '';

		if (bulletStyle === mxShapeMockupBulletedList.prototype.cst.STYLE_NUM)
		{
			currText = (i + 1) + ') ' + mainText[i];
		}
		else if (bulletStyle === mxShapeMockupBulletedList.prototype.cst.STYLE_HYPHEN)
		{
			currText = '- ' + mainText[i];
		}
		else if(bulletStyle === mxShapeMockupBulletedList.prototype.cst.STYLE_DOT)
		{
			currText = String.fromCharCode(8226) + ' ' + mainText[i];
		}
		else
		{
			currText = '  ' + mainText[i];
		}

		c.text(10, i * fontSize * 1.5 + fontSize * 0.75, 0, 0, currText, mxConstants.ALIGN_LEFT, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);
	}
};

mxCellRenderer.prototype.defaultShapes[mxShapeMockupBulletedList.prototype.cst.SHAPE_BULLETED_LIST] = mxShapeMockupBulletedList;

//**********************************************************************************************************************************************************
//Text Box
//**********************************************************************************************************************************************************
/**
 * Extends mxShape.
 */
function mxShapeMockupTextBox(bounds, fill, stroke, strokewidth)
{
	mxShape.call(this);
	this.bounds = bounds;
	this.fill = fill;
	this.stroke = stroke;
	this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};

/**
 * Extends mxShape.
 */
mxUtils.extend(mxShapeMockupTextBox, mxShape);

mxShapeMockupTextBox.prototype.cst = {
		MAIN_TEXT : 'mainText',
		TEXT_COLOR : 'textColor',
		TEXT_SIZE : 'textSize',
		SHAPE_TEXT_BOX : 'mxgraph.mockup.text.textBox'
};

/**
 * Function: paintVertexShape
 *
 * Paints the vertex shape.
 */
mxShapeMockupTextBox.prototype.paintVertexShape = function(c, x, y, w, h)
{
	c.translate(x, y);
	this.background(c, w, h);
	c.setShadow(false);
	this.foreground(c, w, h);
};

mxShapeMockupTextBox.prototype.background = function(c, w, h)
{
	c.rect(0, 0, w, h);
	c.fillAndStroke();
};

mxShapeMockupTextBox.prototype.foreground = function(c, w, h)
{
	var mainText = mxUtils.getValue(this.style, mxShapeMockupTextBox.prototype.cst.MAIN_TEXT, 'Note line 1').toString().split(',');
	var fontColor = mxUtils.getValue(this.style, mxShapeMockupTextBox.prototype.cst.TEXT_COLOR, '#666666');
	var fontSize = mxUtils.getValue(this.style, mxShapeMockupTextBox.prototype.cst.TEXT_SIZE, '17');

	c.setFontColor(fontColor);
	c.setFontSize(fontSize);

	for (var i = 0; i < mainText.length; i++)
	{
		c.text(5, i * fontSize * 1.5 + fontSize * 0.75, 0, 0, mainText[i], mxConstants.ALIGN_LEFT, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);
	}
};

mxCellRenderer.prototype.defaultShapes[mxShapeMockupTextBox.prototype.cst.SHAPE_TEXT_BOX] = mxShapeMockupTextBox;

//**********************************************************************************************************************************************************
//Captcha
//**********************************************************************************************************************************************************
/**
 * Extends mxShape.
 */
function mxShapeMockupCaptcha(bounds, fill, stroke, strokewidth)
{
	mxShape.call(this);
	this.bounds = bounds;
	this.fill = fill;
	this.stroke = stroke;
	this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};

/**
 * Extends mxShape.
 */
mxUtils.extend(mxShapeMockupCaptcha, mxShape);

mxShapeMockupCaptcha.prototype.cst = {
		MAIN_TEXT : 'mainText',
		TEXT_COLOR : 'textColor',
		TEXT_SIZE : 'textSize',
		SHAPE_CAPTCHA : 'mxgraph.mockup.text.captcha'
};

/**
 * Function: paintVertexShape
 *
 * Paints the vertex shape.
 */
mxShapeMockupCaptcha.prototype.paintVertexShape = function(c, x, y, w, h)
{
	c.translate(x, y);
	this.background(c, w, h);
	c.setShadow(false);
	this.foreground(c, w, h);
};

mxShapeMockupCaptcha.prototype.background = function(c, w, h)
{
	c.rect(0, 0, w, h);
	c.fillAndStroke();
};

mxShapeMockupCaptcha.prototype.foreground = function(c, w, h)
{
	var mainText = mxUtils.getValue(this.style, mxShapeMockupCaptcha.prototype.cst.MAIN_TEXT, 'Note line 1');
	var fontColor = mxUtils.getValue(this.style, mxShapeMockupCaptcha.prototype.cst.TEXT_COLOR, '#666666');
	var fontSize = mxUtils.getValue(this.style, mxShapeMockupCaptcha.prototype.cst.TEXT_SIZE, '25');

	c.setFillColor('#88aaff');
	c.begin();
	c.moveTo(0, 0);
	c.lineTo(w * 0.35, 0);
	c.lineTo(w * 0.55, h * 0.85);
	c.lineTo(w * 0.4, h * 0.75);
	c.close();
	c.fill();

	c.begin();
	c.moveTo(w * 0.7, h * 0.1);
	c.lineTo(w * 0.95, h * 0.23);
	c.lineTo(w, h * 0.4);
	c.lineTo(w, h * 0.9);
	c.lineTo(w, h);
	c.lineTo(w * 0.8, h);
	c.close();
	c.fill();

	c.setFontColor(fontColor);
	c.setFontSize(fontSize);

	c.text(w * 0.5, h * 0.5, 0, 0, mainText, mxConstants.ALIGN_CENTER, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);

	c.rect(0, 0, w, h);
	c.stroke();
};

mxCellRenderer.prototype.defaultShapes[mxShapeMockupCaptcha.prototype.cst.SHAPE_CAPTCHA] = mxShapeMockupCaptcha;

//**********************************************************************************************************************************************************
//Alphanumeric
//**********************************************************************************************************************************************************
/**
 * Extends mxShape.
 */
function mxShapeMockupAlphanumeric(bounds, fill, stroke, strokewidth)
{
	mxShape.call(this);
	this.bounds = bounds;
	this.fill = fill;
	this.stroke = stroke;
	this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};

/**
 * Extends mxShape.
 */
mxUtils.extend(mxShapeMockupAlphanumeric, mxShape);

mxShapeMockupAlphanumeric.prototype.cst = {
		MAIN_TEXT : 'linkText',
		TEXT_SIZE : 'textSize',
		TEXT_COLOR : 'textColor',
		SHAPE_ALPHANUMERIC : 'mxgraph.mockup.text.alphanumeric'
};

/**
 * Function: paintVertexShape
 *
 * Paints the vertex shape.
 */
mxShapeMockupAlphanumeric.prototype.paintVertexShape = function(c, x, y, w, h)
{
	var mainText = mxUtils.getValue(this.style, mxShapeMockupAlphanumeric.prototype.cst.MAIN_TEXT, '0-9 A B C D E F G H I J K L M N O P Q R S T U V X Y Z');
	var textSize = mxUtils.getValue(this.style, mxShapeMockupAlphanumeric.prototype.cst.TEXT_SIZE, '17');
	var textColor = mxUtils.getValue(this.style, mxShapeMockupAlphanumeric.prototype.cst.TEXT_COLOR, '#0000ff');

	c.translate(x, y);
	var width = mxUtils.getSizeForString(mainText, textSize, mxConstants.DEFAULT_FONTFAMILY).width;
	c.setStrokeColor(textColor);
	c.setFontSize(textSize);
	c.setFontColor(textColor);
	c.text(w * 0.5, h * 0.5, 0, 0, mainText, mxConstants.ALIGN_CENTER, mxConstants.ALIGN_MIDDLE, 0, null, 0, 0, 0);
	c.begin();
	c.moveTo(w * 0.5 - width * 0.5, (h + parseInt(textSize, 10)) * 0.5);
	c.lineTo(w * 0.5 + width * 0.5, (h + parseInt(textSize, 10)) * 0.5);
	c.stroke();
};

mxCellRenderer.prototype.defaultShapes[mxShapeMockupAlphanumeric.prototype.cst.SHAPE_ALPHANUMERIC] = mxShapeMockupAlphanumeric;

//**********************************************************************************************************************************************************
//Rounded rectangle (adjustable rounding)
//**********************************************************************************************************************************************************
/**
* Extends mxShape.
*/
function mxShapeMockupTextRRect(bounds, fill, stroke, strokewidth)
{
	mxShape.call(this);
	this.bounds = bounds;
	this.fill = fill;
	this.stroke = stroke;
	this.strokewidth = (strokewidth != null) ? strokewidth : 1;
};

/**
* Extends mxShape.
*/
mxUtils.extend(mxShapeMockupTextRRect, mxShape);

mxShapeMockupTextRRect.prototype.cst = {
		RRECT : 'mxgraph.mockup.text.rrect',
		R_SIZE : 'rSize'
};

/**
* Function: paintVertexShape
*
* Paints the vertex shape.
*/
mxShapeMockupTextRRect.prototype.paintVertexShape = function(c, x, y, w, h)
{
	c.translate(x, y);

	var rSize = parseInt(mxUtils.getValue(this.style, mxShapeMockupTextRRect.prototype.cst.R_SIZE, '10'));
	c.roundrect(0, 0, w, h, rSize);
	c.fillAndStroke();
};

mxCellRenderer.registerShape(mxShapeMockupTextRRect.prototype.cst.RRECT, mxShapeMockupTextRRect);


text:
import passwordHash from 'password-hash';
import Boom from 'boom';

import utils from '../utils';
import mailer from '../services/mailer';
import templates from '../services/templates';
import users from '../dal/users';
import tokens from '../dal/tokens';
import system from '../dal/system';
import constants from '../constants';

function verifyPassword(password, encodedPassword) {
  return passwordHash.verify(password, encodedPassword);
}

export default {
  async resetPassword(email, serverUrl) {
    const resetToken = utils.newToken();
    await users.addResetToken(resetToken, email);
    const template = await templates.setPassword(`${serverUrl}/setPassword/${resetToken}`);

    return mailer.send({
      to: email,
      subject: 'Set your password',
      text: template.text,
      html: template.html,
    });
  },

  async setPassword(token, password) {
    const encodedPassword = passwordHash.generate(password);

    return users.newPassword(token, encodedPassword);
  },

  async login(credentials) {
    const password = await users.getPassword(credentials.username);
    const passwordsMatched = verifyPassword(
      credentials.password,
      password,
    );

    if (passwordsMatched) {
      const token = utils.newToken();
      // TODO: need to chack expired tokens
      const user = await users.getByEmail(credentials.username);
      await tokens.create(user.id, token);

      return token;
    }

    throw Boom.unauthorized('incorrectCredentials');
  },

  async addFirstAdmin(email) {
    // This method exist only for the initialization phase
    const initialized = await system.getByName(constants.INITIALIZING_SETTING_KEY);
    if (!initialized) {
      await users.create({ email });
      await system.update(constants.INITIALIZING_SETTING_KEY, true);
    } else {
      throw Boom.forbidden('Application already initialized');
    }
  },

  async getUserByToken(token) {
    return users.getUserByToken(token);

    // .then((roles) => {
    //   let rolesPromisies = roles.map(function(role) {
    //     return DAL.roles.getRoleById(role.id_role);
    //   });

    //   return Promise.all(rolesPromisies);
    // }).then((roles) => {
    //   rolesArr = roles.map(function(role) {
    //     return role.name;
    //   });

    //   let getActionsPromisies = roles.map(function(role) {
    //     return DAL.actions.getActionsByRoleId(role.id);
    //   });

    //   return Promise.all(getActionsPromisies);
    // }).then((actions) => {
    //   let actionsId = [];
    //   if (actions.length > 0) {
    //     actionsId = actions[0].map(function(action) {
    //       return action.id_action;
    //     });
    //   }

    //   let actionsPromisies = actionsId.map(function(action) {
    //     return DAL.actions.getActionById(action);
    //   });

    //   return Promise.all(actionsPromisies);
    // }).then((actions) => {
    //   actionsArr = actions.map(function(action) {
    //     return action.name;
    //   });
    // }).then(() => {
    //   user.roles = rolesArr;
    //   user.actions = actionsArr;

    //   return user;
    // });
  },

  // isUserExist: (email) => {
  //   return new Promise((resolve) => {
  //     DAL.users.getUserByEmail(email).then(() => {
  //       resolve(true);
  //     }, () => {
  //       resolve(false);
  //     });
  //   });
  // },

  // register: (email, password, confirmPassword, link) => {
  //   return new Promise((resolve, reject) => {
  //     if (confirmPassword !== password) {
  //       reject({
  //         'statusCode': 400,
  //         'message': 'Passwords do not match!'
  //       });
  //     } else {
  //       DAL.company.add().then((res) => {
  //         return DAL.users.register(email, password, res.insertId);
  //       }).then(() => {
  //         const message = [
  //           'Welcome to BizKonect App!'
  //         ].join('\n');

  //         const mail = {
  //           to: email,
  //           subject: 'Register',
  //           text: message,
  //           html: template.templateForWelcome(link)
  //         };

  //         mailer(config).send(mail).then(
  //           () => {
  //             resolve();
  //           }, (err) => {
  //             reject(err);
  //           }
  //         );
  //       }, (err) => {
  //         reject(err);
  //       });
  //     }
  //   });
  // },

  // inviteUser: (email) => {
  //   return new Promise((resolve, reject) => {
  //     let resetToken = utils.newToken();
  //     DAL.users.addUserInvite(email).then(function() {
  //        return DAL.users.addResetToken(resetToken, email);
  //     }).then(() => {
  //       const message = [
  //         // TODO: config.mail.linkForNewPassword should get server addres from request
  //         'Enter password for your login: ' + config.mail.linkForNewPassword + resetToken
  //       ].join('\n');

  //       const mail = {
  //         to: email,
  //         subject: 'Invitation',
  //         text: message
  //       };

  //       mailer(config).send(mail).then(
  //         () => {
  //           resolve();
  //         }, (err) => {
  //           reject(err);
  //         }
  //       );
  //     }, (err) => {
  //       reject(err);
  //     });
  //   });
  // },

  // parseToken: (token) => {
  //   token = token || '';

  //   let splitted = token.split(' ');

  //   return {
  //     name: splitted[0] || '',
  //     value: splitted[1] || ''
  //   };
  // }
};


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright 2015 Priyesh Patel
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <include
        layout="@layout/app_bar"
        android:id="@+id/app_bar" />

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_below="@id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <FrameLayout
                android:id="@+id/container"
                android:layout_above="@+id/ad_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <RelativeLayout
                android:id="@+id/ad_container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/primary"
                android:layout_alignParentBottom="true">

                <TextView
                    android:layout_centerInParent="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Ad Space"
                    android:textColor="@android:color/white"
                    android:textAllCaps="true"
                    android:textStyle="bold"/>

                <com.google.android.gms.ads.AdView
                    android:id="@+id/adView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    ads:adSize="BANNER"
                    ads:adUnitId="@string/banner_ad_unit_id" />

            </RelativeLayout>

        </RelativeLayout>

        <ListView
            android:id="@+id/drawer_list"
            android:paddingTop="16dp"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp"
            android:background="@color/white_100_opacity" />

    </android.support.v4.widget.DrawerLayout>

</RelativeLayout>


text:
<meta charset="UTF-8">
<title>GetNearbyAccessPointsCallbacks - wisefy</title>
<link rel="stylesheet" href="../../../style.css">

wisefy / com.isupatches.wisefy.callbacks / GetNearbyAccessPointsCallbacks

GetNearbyAccessPointsCallbacks

interface GetNearbyAccessPointsCallbacks : BaseCallback

Callbacks for retrieving a list of nearby access points.

See Also

BaseCallback

com.isupatches.wisefy.WiseFy.getNearbyAccessPoints

Author

Patches

Since

3.0

Functions

noAccessPointsFound

abstract fun noAccessPointsFound(): Unit

Called when the Android OS returns no access points.

retrievedNearbyAccessPoints

abstract fun retrievedNearbyAccessPoints(nearbyAccessPoints: List<ScanResult>): Unit

Called when WiseFy has successfully retrieved a list of nearby access points.

Inherited Functions

wisefyFailure

abstract fun wisefyFailure(wisefyFailureCode: Int): Unit

Called when com.isupatches.wisefy.WiseFyPrechecks determines that there
is an issue and an operation cannot be completed.


text:
body {
  display: flex;
}

div {
  background: yellow;
}

@media (orientation: landscape) {
  body {
    flex-direction: row;
  }
}

@media (orientation: portrait) {
  body {
    flex-direction: column;
  }
}


text:
// +build !providerless

package gcepd

import (
	"fmt"
	"path/filepath"
	"regexp"
	"strings"
	"time"

	"k8s.io/klog/v2"
	"k8s.io/mount-utils"
	"k8s.io/utils/exec"
	utilpath "k8s.io/utils/path"

	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/util/sets"
	cloudprovider "k8s.io/cloud-provider"
	cloudvolume "k8s.io/cloud-provider/volume"
	volumehelpers "k8s.io/cloud-provider/volume/helpers"
	"k8s.io/kubernetes/pkg/volume"
	volumeutil "k8s.io/kubernetes/pkg/volume/util"
	gcecloud "k8s.io/legacy-cloud-providers/gce"
)

const (
	diskByIDPath         = "/dev/disk/by-id/"
	diskGooglePrefix     = "google-"
	diskScsiGooglePrefix = "scsi-0Google_PersistentDisk_"
	diskPartitionSuffix  = "-part"
	diskSDPath           = "/dev/sd"
	diskSDPattern        = "/dev/sd*"
	maxRetries           = 10
	checkSleepDuration   = time.Second
	maxRegionalPDZones   = 2

	// Replication type constants must be lower case.
	replicationTypeNone       = "none"
	replicationTypeRegionalPD = "regional-pd"

	// scsi_id output should be in the form of:
	// 0Google PersistentDisk <disk name>
	scsiPattern = `^0Google\s+PersistentDisk\s+([\S]+)\s*$`
)

var (
	// errorSleepDuration is modified only in unit tests and should be constant
	// otherwise.
	errorSleepDuration = 5 * time.Second

	// regex to parse scsi_id output and extract the serial
	scsiRegex = regexp.MustCompile(scsiPattern)
)

// GCEDiskUtil provides operation for GCE PD
type GCEDiskUtil struct{}

// DeleteVolume deletes a GCE PD
// Returns: error
func (util *GCEDiskUtil) DeleteVolume(d *gcePersistentDiskDeleter) error {
	cloud, err := getCloudProvider(d.gcePersistentDisk.plugin.host.GetCloudProvider())
	if err != nil {
		return err
	}

	if err = cloud.DeleteDisk(d.pdName); err != nil {
		klog.V(2).Infof("Error deleting GCE PD volume %s: %v", d.pdName, err)
		// GCE cloud provider returns volume.deletedVolumeInUseError when
		// necessary, no handling needed here.
		return err
	}
	klog.V(2).Infof("Successfully deleted GCE PD volume %s", d.pdName)
	return nil
}

// CreateVolume creates a GCE PD.
// Returns: gcePDName, volumeSizeGB, labels, fsType, error
func (util *GCEDiskUtil) CreateVolume(c *gcePersistentDiskProvisioner, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (string, int, map[string]string, string, error) {
	cloud, err := getCloudProvider(c.gcePersistentDisk.plugin.host.GetCloudProvider())
	if err != nil {
		return "", 0, nil, "", err
	}

	name := volumeutil.GenerateVolumeName(c.options.ClusterName, c.options.PVName, 63) // GCE PD name can have up to 63 characters
	capacity := c.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
	// GCE PDs are allocated in chunks of GiBs
	requestGB, err := volumehelpers.RoundUpToGiB(capacity)
	if err != nil {
		return "", 0, nil, "", err
	}

	// Apply Parameters.
	// Values for parameter "replication-type" are canonicalized to lower case.
	// Values for other parameters are case-insensitive, and we leave validation of these values
	// to the cloud provider.
	diskType := ""
	configuredZone := ""
	var configuredZones sets.String
	zonePresent := false
	zonesPresent := false
	replicationType := replicationTypeNone
	fstype := ""
	for k, v := range c.options.Parameters {
		switch strings.ToLower(k) {
		case "type":
			diskType = v
		case "zone":
			zonePresent = true
			configuredZone = v
		case "zones":
			zonesPresent = true
			configuredZones, err = volumehelpers.ZonesToSet(v)
			if err != nil {
				return "", 0, nil, "", err
			}
		case "replication-type":
			replicationType = strings.ToLower(v)
		case volume.VolumeParameterFSType:
			fstype = v
		default:
			return "", 0, nil, "", fmt.Errorf("invalid option %q for volume plugin %s", k, c.plugin.GetPluginName())
		}
	}

	// TODO: implement PVC.Selector parsing
	if c.options.PVC.Spec.Selector != nil {
		return "", 0, nil, "", fmt.Errorf("claim.Spec.Selector is not supported for dynamic provisioning on GCE")
	}

	var activezones sets.String
	activezones, err = cloud.GetAllCurrentZones()
	if err != nil {
		return "", 0, nil, "", err
	}

	var disk *gcecloud.Disk
	switch replicationType {
	case replicationTypeRegionalPD:
		selectedZones, err := volumehelpers.SelectZonesForVolume(zonePresent, zonesPresent, configuredZone, configuredZones, activezones, node, allowedTopologies, c.options.PVC.Name, maxRegionalPDZones)
		if err != nil {
			klog.V(2).Infof("Error selecting zones for regional GCE PD volume: %v", err)
			return "", 0, nil, "", err
		}
		disk, err = cloud.CreateRegionalDisk(
			name,
			diskType,
			selectedZones,
			requestGB,
			*c.options.CloudTags)
		if err != nil {
			klog.V(2).Infof("Error creating regional GCE PD volume: %v", err)
			return "", 0, nil, "", err
		}
		klog.V(2).Infof("Successfully created Regional GCE PD volume %s", name)

	case replicationTypeNone:
		selectedZone, err := volumehelpers.SelectZoneForVolume(zonePresent, zonesPresent, configuredZone, configuredZones, activezones, node, allowedTopologies, c.options.PVC.Name)
		if err != nil {
			return "", 0, nil, "", err
		}
		disk, err = cloud.CreateDisk(
			name,
			diskType,
			selectedZone,
			requestGB,
			*c.options.CloudTags)
		if err != nil {
			klog.V(2).Infof("Error creating single-zone GCE PD volume: %v", err)
			return "", 0, nil, "", err
		}
		klog.V(2).Infof("Successfully created single-zone GCE PD volume %s", name)

	default:
		return "", 0, nil, "", fmt.Errorf("replication-type of '%s' is not supported", replicationType)
	}

	labels, err := cloud.GetAutoLabelsForPD(disk)
	if err != nil {
		// We don't really want to leak the volume here...
		klog.Errorf("error getting labels for volume %q: %v", name, err)
	}

	return name, int(requestGB), labels, fstype, nil
}

// Returns the first path that exists, or empty string if none exist.
func verifyDevicePath(devicePaths []string, sdBeforeSet sets.String, diskName string) (string, error) {
	if err := udevadmChangeToNewDrives(sdBeforeSet); err != nil {
		// It's possible udevadm was called on other disks so it should not block this
		// call. If it did fail on this disk, then the devicePath will either
		// not exist or be wrong. If it's wrong, then the scsi_id check below will fail.
		klog.Errorf("udevadmChangeToNewDrives failed with: %v", err)
	}

	for _, path := range devicePaths {
		if pathExists, err := mount.PathExists(path); err != nil {
			return "", fmt.Errorf("error checking if path exists: %v", err)
		} else if pathExists {
			// validate that the path actually resolves to the correct disk
			serial, err := getScsiSerial(path, diskName)
			if err != nil {
				return "", fmt.Errorf("failed to get scsi serial %v", err)
			}
			if serial != diskName {
				// The device link is not pointing to the correct device
				// Trigger udev on this device to try to fix the link
				if udevErr := udevadmChangeToDrive(path); udevErr != nil {
					klog.Errorf("udevadmChangeToDrive %q failed with: %v", path, err)
				}

				// Return error to retry WaitForAttach and verifyDevicePath
				return "", fmt.Errorf("scsi_id serial %q for device %q doesn't match disk %q", serial, path, diskName)
			}
			// The device link is correct
			return path, nil
		}
	}

	return "", nil
}

// Calls scsi_id on the given devicePath to get the serial number reported by that device.
func getScsiSerial(devicePath, diskName string) (string, error) {
	exists, err := utilpath.Exists(utilpath.CheckFollowSymlink, "/lib/udev/scsi_id")
	if err != nil {
		return "", fmt.Errorf("failed to check scsi_id existence: %v", err)
	}

	if !exists {
		klog.V(6).Infof("scsi_id doesn't exist; skipping check for %v", devicePath)
		return diskName, nil
	}

	out, err := exec.New().Command(
		"/lib/udev/scsi_id",
		"--page=0x83",
		"--whitelisted",
		fmt.Sprintf("--device=%v", devicePath)).CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("scsi_id failed for device %q with %v", devicePath, err)
	}

	return parseScsiSerial(string(out))
}

// Parse the output returned by scsi_id and extract the serial number
func parseScsiSerial(output string) (string, error) {
	substrings := scsiRegex.FindStringSubmatch(output)
	if substrings == nil {
		return "", fmt.Errorf("scsi_id output cannot be parsed: %q", output)
	}

	return substrings[1], nil
}

// Returns list of all /dev/disk/by-id/* paths for given PD.
func getDiskByIDPaths(pdName string, partition string) []string {
	devicePaths := []string{
		filepath.Join(diskByIDPath, diskGooglePrefix+pdName),
		filepath.Join(diskByIDPath, diskScsiGooglePrefix+pdName),
	}

	if partition != "" {
		for i, path := range devicePaths {
			devicePaths[i] = path + diskPartitionSuffix + partition
		}
	}

	return devicePaths
}

// Return cloud provider
func getCloudProvider(cloudProvider cloudprovider.Interface) (*gcecloud.Cloud, error) {
	var err error
	for numRetries := 0; numRetries < maxRetries; numRetries++ {
		gceCloudProvider, ok := cloudProvider.(*gcecloud.Cloud)
		if !ok || gceCloudProvider == nil {
			// Retry on error. See issue #11321
			klog.Errorf("Failed to get GCE Cloud Provider. plugin.host.GetCloudProvider returned %v instead", cloudProvider)
			time.Sleep(errorSleepDuration)
			continue
		}

		return gceCloudProvider, nil
	}

	return nil, fmt.Errorf("failed to get GCE GCECloudProvider with error %v", err)
}

// Triggers the application of udev rules by calling "udevadm trigger
// --action=change" for newly created "/dev/sd*" drives (exist only in
// after set). This is workaround for Issue #7972. Once the underlying
// issue has been resolved, this may be removed.
func udevadmChangeToNewDrives(sdBeforeSet sets.String) error {
	sdAfter, err := filepath.Glob(diskSDPattern)
	if err != nil {
		return fmt.Errorf("error filepath.Glob(\"%s\"): %v\r", diskSDPattern, err)
	}

	for _, sd := range sdAfter {
		if !sdBeforeSet.Has(sd) {
			return udevadmChangeToDrive(sd)
		}
	}

	return nil
}

// Calls "udevadm trigger --action=change" on the specified drive.
// drivePath must be the block device path to trigger on, in the format "/dev/sd*", or a symlink to it.
// This is workaround for Issue #7972. Once the underlying issue has been resolved, this may be removed.
func udevadmChangeToDrive(drivePath string) error {
	klog.V(5).Infof("udevadmChangeToDrive: drive=%q", drivePath)

	// Evaluate symlink, if any
	drive, err := filepath.EvalSymlinks(drivePath)
	if err != nil {
		return fmt.Errorf("udevadmChangeToDrive: filepath.EvalSymlinks(%q) failed with %v", drivePath, err)
	}
	klog.V(5).Infof("udevadmChangeToDrive: symlink path is %q", drive)

	// Check to make sure input is "/dev/sd*"
	if !strings.Contains(drive, diskSDPath) {
		return fmt.Errorf("udevadmChangeToDrive: expected input in the form \"%s\" but drive is %q", diskSDPattern, drive)
	}

	// Call "udevadm trigger --action=change --property-match=DEVNAME=/dev/sd..."
	_, err = exec.New().Command(
		"udevadm",
		"trigger",
		"--action=change",
		fmt.Sprintf("--property-match=DEVNAME=%s", drive)).CombinedOutput()
	if err != nil {
		return fmt.Errorf("udevadmChangeToDrive: udevadm trigger failed for drive %q with %v", drive, err)
	}
	return nil
}

// Checks whether the given GCE PD volume spec is associated with a regional PD.
func isRegionalPD(spec *volume.Spec) bool {
	if spec.PersistentVolume != nil {
		zonesLabel := spec.PersistentVolume.Labels[v1.LabelZoneFailureDomain]
		zones := strings.Split(zonesLabel, cloudvolume.LabelMultiZoneDelimiter)
		return len(zones) > 1
	}
	return false
}