text:
<?php

namespace Silber\Bouncer\Conductors\Concerns;

use Silber\Bouncer\Helpers;
use Silber\Bouncer\Database\Models;

use Illuminate\Support\Arr;
use InvalidArgumentException;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Model;

trait FindsAndCreatesAbilities
{
    /**
     * Get the IDs of the provided abilities.
     *
     * @param  \Illuminate\Database\Eloquent\model|array|int  $abilities
     * @param  \Illuminate\Database\Eloquent\Model|string|array|null  $model
     * @param  array  $attributes
     * @return array
     */
    protected function getAbilityIds($abilities, $model = null, array $attributes = [])
    {
        if ($abilities instanceof Model) {
            return [$abilities->getKey()];
        }

        if ( ! is_null($model)) {
            return $this->getModelAbilityKeys($abilities, $model, $attributes);
        }

        if (Helpers::isAssociativeArray($abilities)) {
            return $this->getAbilityIdsFromMap($abilities, $attributes);
        }

        if (! is_array($abilities) && ! $abilities instanceof Collection) {
            $abilities = [$abilities];
        }

        return $this->getAbilityIdsFromArray($abilities, $attributes);
    }

    /**
     * Get the ability IDs for the given map.
     *
     * The map should use the ['ability-name' => Entity::class] format.
     *
     * @param  array  $map
     * @param  array  $attributes
     * @return array
     */
    protected function getAbilityIdsFromMap(array $map, array $attributes)
    {
        list($map, $list) = Helpers::partition($map, function ($value, $key) {
            return ! is_int($key);
        });

        return $map->map(function ($entity, $ability) use ($attributes) {
            return $this->getAbilityIds($ability, $entity, $attributes);
        })->collapse()->merge($this->getAbilityIdsFromArray($list, $attributes))->all();
    }

    /**
     * Get the ability IDs from the provided array, creating the ones that don't exist.
     *
     * @param  iterable  $abilities
     * @param  array  $attributes
     * @return array
     */
    protected function getAbilityIdsFromArray($abilities, array $attributes)
    {
        $groups = Helpers::groupModelsAndIdentifiersByType($abilities);

        $keyName = Models::ability()->getKeyName();

        $groups['strings'] = $this->abilitiesByName($groups['strings'], $attributes)
                                  ->pluck($keyName)->all();

        $groups['models'] = Arr::pluck($groups['models'], $keyName);

        return Arr::collapse($groups);
    }

    /**
     * Get the abilities for the given model ability descriptors.
     *
     * @param  array|string  $abilities
     * @param  \Illuminate\Database\Eloquent\Model|string|array  $model
     * @param  array  $attributes
     * @return array
     */
    protected function getModelAbilityKeys($abilities, $model, array $attributes)
    {
        $abilities = Collection::make(is_array($abilities) ? $abilities : [$abilities]);

        $models = Collection::make(is_array($model) ? $model : [$model]);

        return $abilities->map(function ($ability) use ($models, $attributes) {
            return $models->map(function ($model) use ($ability, $attributes) {
                return $this->getModelAbility($ability, $model, $attributes)->getKey();
            });
        })->collapse()->all();
    }

    /**
     * Get an ability for the given entity.
     *
     * @param  string  $ability
     * @param  \Illuminate\Database\Eloquent\Model|string  $entity
     * @param  array  $attributes
     * @return \Silber\Bouncer\Database\Ability
     */
    protected function getModelAbility($ability, $entity, array $attributes)
    {
        $entity = $this->getEntityInstance($entity);

        $existing = $this->findAbility($ability, $entity, $attributes);

        return $existing ?: $this->createAbility($ability, $entity, $attributes);
    }

    /**
     * Find the ability for the given entity.
     *
     * @param  string  $ability
     * @param  \Illuminate\Database\Eloquent\Model|string  $entity
     * @param  array  $attributes
     * @return \Silber\Bouncer\Database\Ability|null
     */
    protected function findAbility($ability, $entity, $attributes)
    {
        $onlyOwned = isset($attributes['only_owned']) ? $attributes['only_owned'] : false;

        $query = Models::ability()
                     ->where('name', $ability)
                     ->forModel($entity, true)
                     ->where('only_owned', $onlyOwned);

        return Models::scope()->applyToModelQuery($query)->first();
    }

    /**
     * Create an ability for the given entity.
     *
     * @param  string  $ability
     * @param  \Illuminate\Database\Eloquent\Model|string  $entity
     * @param  array  $attributes
     * @return \Silber\Bouncer\Database\Ability
     */
    protected function createAbility($ability, $entity, $attributes)
    {
        return Models::ability()->createForModel($entity, $attributes + [
            'name' => $ability,
        ]);
    }

    /**
     * Get an instance of the given model.
     *
     * @param  \Illuminate\Database\Eloquent\Model|string  $model
     * @return \Illuminate\Database\Eloquent\Model|string
     */
    protected function getEntityInstance($model)
    {
        if ($model === '*') {
            return '*';
        }

        if ( ! $model instanceof Model) {
            return new $model;
        }

        // Creating an ability for a non-existent model gives the authority that
        // ability on all instances of that model. If the developer passed in
        // a model instance that does not exist, it is probably a mistake.
        if ( ! $model->exists) {
            throw new InvalidArgumentException(
                'The model does not exist. To edit access to all models, use the class name instead'
            );
        }

        return $model;
    }

    /**
     * Get or create abilities by their name.
     *
     * @param  array|string  $abilities
     * @param  array  $attributes
     * @return \Illuminate\Support\Collection
     */
    protected function abilitiesByName($abilities, $attributes = [])
    {
        $abilities = array_unique(is_array($abilities) ? $abilities : [$abilities]);

        if (empty($abilities)) {
            return new Collection;
        }

        $existing = Models::ability()->simpleAbility()->whereIn('name', $abilities)->get();

        return $existing->merge($this->createMissingAbilities(
            $existing, $abilities, $attributes
        ));
    }

    /**
     * Create the non-existant abilities by name.
     *
     * @param  \Illuminate\Database\Eloquent\Collection  $existing
     * @param  string[]  $abilities
     * @param  array  $attributes
     * @return array
     */
    protected function createMissingAbilities($existing, array $abilities, $attributes = [])
    {
        $missing = array_diff($abilities, $existing->pluck('name')->all());

        return array_map(function ($ability) use ($attributes) {
            return Models::ability()->create($attributes + ['name' => $ability]);
        }, $missing);
    }
}


text:
class AddCompletedAtToTodoItems < ActiveRecord::Migration[5.0]
  def change
  	add_column :todo_items, :completed_at, :datetime
  end
end

redpajama_set_name: RedPajamaGithub


text:
function Chunker(data, breakString, chunkSize) {
  this.chunks = [];

  for (var cursor = 0, dataSize = data.length; cursor < dataSize;) {
    var nextCursor = cursor + chunkSize > dataSize ?
      dataSize - 1 :
      cursor + chunkSize;

    if (data[nextCursor] != breakString)
      nextCursor = data.indexOf(breakString, nextCursor);
    if (nextCursor == -1)
      nextCursor = data.length - 1;

    this.chunks.push(data.substring(cursor, nextCursor + breakString.length));
    cursor = nextCursor + breakString.length;
  }
}

Chunker.prototype.isEmpty = function () {
  return this.chunks.length === 0;
};

Chunker.prototype.next = function () {
  return this.chunks.shift();
};

module.exports = Chunker;


text:
<?php

namespace Core\Api\Crypt;

use Core\Api\Models\ApiKey;
use Core\Api\Exception\ApiException;

class RsaCrypt extends Crypt {

    protected $our_side;
    protected $other_side;

    /** @var 公钥 */
    const KEY_TYPE_PUBLIC = 1;

    /** @var 私钥 */
    const KEY_TYPE_PRIVATE = 2;

    public function __construct($business, $partner) {
        $this->our_side = ApiKey::where('name', $business)->first();
        if (!$this->our_side) {
            throw new ApiException("business:$business not exists");
        }
        $this->other_side = ApiKey::where('name', $partner)->first();
        if (!$this->other_side) {
            throw new ApiException("partner:$partner not exists");
        }
    }

    /**
     * 用对方公钥加密
     */
    public function encrypt($data) {
        return $this->rsaEncrypt($data, $this->other_side->public_key, self::KEY_TYPE_PUBLIC);
    }

    /**
     * 用我方私钥解密
     */
    public function decrypt($data) {
        return $this->rsaDecrypt($data, $this->our_side->private_key, self::KEY_TYPE_PRIVATE);
    }

    /**
     * 用我方私钥加签
     */
    public function sign($data) {
        return $this->rsaEncrypt($data, $this->our_side->private_key, self::KEY_TYPE_PRIVATE);
    }

    /**
     * 用对方公钥验签
     */
    public function checkSign($data, $sign) {
        $un_sign = $this->rsaDecrypt($sign, $this->other_side->public_key, self::KEY_TYPE_PUBLIC);
        if ($un_sign === $data) {
            return true;
        }
        return false;
    }

    /**
     * 使用公钥对内容进行RSA加密
     * @param $ary
     * @param $key
     * @return string
     */
    private function rsaEncrypt($ary, $key, $type = self::KEY_TYPE_PUBLIC) {
        $rawData = json_encode($ary);
        $keyContent = file_get_contents(_base_path() . '/openssl/' . $key);
        $encryptedList = array();
        $step = 117;
        for ($i = 0, $len = strlen($rawData); $i < $len; $i+=$step) {
            $data = substr($rawData, $i, $step);
            $encrypted = '';
            if($type === self::KEY_TYPE_PUBLIC){
                openssl_public_encrypt($data, $encrypted, $keyContent);
            }
            if($type === self::KEY_TYPE_PRIVATE){
                openssl_private_encrypt($data, $encrypted, $keyContent);
            }
            $encryptedList[] = ($encrypted);
        }
        $data = base64_encode(join('', $encryptedList));
        return $data;
    }

    /**
     * RSA解密
     * @param $ary
     * @param $key
     * @return string
     */
    private function rsaDecrypt($ary, $key, $type = self::KEY_TYPE_PRIVATE) {
        $encryptedData = base64_decode($ary);
        $keyContent = file_get_contents(_base_path() . '/openssl/' . $key);
        $decryptedList = array();
        $step = 128;
        if (strlen($key) > 1000) {
            $step = 256;
        }
        for ($i = 0, $len = strlen($encryptedData); $i < $len; $i+=$step) {
            $data = substr($encryptedData, $i, $step);
            $decrypted = '';
            if($type === self::KEY_TYPE_PUBLIC){
                openssl_public_decrypt($data, $decrypted, $keyContent);
            }
            if($type === self::KEY_TYPE_PRIVATE){
                openssl_private_decrypt($data, $decrypted, $keyContent);
            }
            $decryptedList[] = $decrypted;
        }
        return join('', $decryptedList);
    }
}


text:
//-----------------------------------------------------------------------------
// Product:     OpenCTM tools
// File:        meshio.cpp
// Description: Mesh I/O using different file format loaders/savers.
//-----------------------------------------------------------------------------
// Copyright (c) 2009-2010 Marcus Geelnard
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
//     1. The origin of this software must not be misrepresented; you must not
//     claim that you wrote the original software. If you use this software
//     in a product, an acknowledgment in the product documentation would be
//     appreciated but is not required.
//
//     2. Altered source versions must be plainly marked as such, and must not
//     be misrepresented as being the original software.
//
//     3. This notice may not be removed or altered from any source
//     distribution.
//-----------------------------------------------------------------------------

#include <stdexcept>
#include <string>
#include <list>
#include "mesh.h"
#include "meshio.h"
#include "convoptions.h"
#include "ctm.h"
#include "stl.h"
//#include "ply.h"
//#include "3ds.h"
//#include "dae.h"
//#include "obj.h"
//#include "lwo.h"
//#include "off.h"
//#include "wrl.h"
#include "common.h"

using namespace std;

/// Import a mesh from a file.
void ImportMesh(const char * aFileName, Mesh * aMesh)
{
  string fileExt = UpperCase(ExtractFileExt(string(aFileName)));
  if(fileExt == string(".CTM"))
      Import_CTM(aFileName, aMesh);
  else if(fileExt == string(".STL"))
      Import_STL(aFileName, aMesh);
  /*else if(fileExt == string(".PLY"))
    Import_PLY(aFileName, aMesh);
  else if(fileExt == string(".3DS"))
    Import_3DS(aFileName, aMesh);
  else if(fileExt == string(".DAE"))
    Import_DAE(aFileName, aMesh);
  else if(fileExt == string(".OBJ"))
    Import_OBJ(aFileName, aMesh);
  else if(fileExt == string(".LWO"))
    Import_LWO(aFileName, aMesh);
  else if(fileExt == string(".OFF"))
    Import_OFF(aFileName, aMesh);
  else if(fileExt == string(".WRL"))
    Import_WRL(aFileName, aMesh);*/
  else
    throw runtime_error("Unknown input file extension.");
}

/// Export a mesh to a file.
void ExportMesh(const char * aFileName, Mesh * aMesh, Options &aOptions)
{
  string fileExt = UpperCase(ExtractFileExt(string(aFileName)));
  if(fileExt == string(".CTM"))
      Export_CTM(aFileName, aMesh, aOptions);
  else if(fileExt == string(".STL"))
      Export_STL(aFileName, aMesh, aOptions);
  /*else if(fileExt == string(".PLY"))
    Export_PLY(aFileName, aMesh, aOptions);
  else if(fileExt == string(".3DS"))
    Export_3DS(aFileName, aMesh, aOptions);
  else if(fileExt == string(".DAE"))
    Export_DAE(aFileName, aMesh, aOptions);
  else if(fileExt == string(".OBJ"))
    Export_OBJ(aFileName, aMesh, aOptions);
  else if(fileExt == string(".LWO"))
    Export_LWO(aFileName, aMesh, aOptions);
  else if(fileExt == string(".OFF"))
    Export_OFF(aFileName, aMesh, aOptions);
  else if(fileExt == string(".WRL"))
    Export_WRL(aFileName, aMesh, aOptions);*/
  else
    throw runtime_error("Unknown output file extension.");
}

/// Return a list of supported formats.
void SupportedFormats(list<string> &aList)
{
  aList.push_back(string("OpenCTM (.ctm)"));
  aList.push_back(string("Stanford triangle format (.ply)"));
  aList.push_back(string("Stereolithography (.stl)"));
  aList.push_back(string("3D Studio (.3ds)"));
  aList.push_back(string("COLLADA 1.4/1.5 (.dae)"));
  aList.push_back(string("Wavefront geometry file (.obj)"));
  aList.push_back(string("LightWave object (.lwo)"));
  aList.push_back(string("Geomview object file format (.off)"));
  aList.push_back(string("VRML 2.0 (.wrl) - export only"));
}


text:
title: Kapacitor Version 1.0 Documentation

menu:
  kapacitor:
    name: v1.0
    identifier: kapacitor_1_0
    weight: 2
---

Kapacitor is an open source data processing framework that makes it easy to create
alerts, run ETL jobs and detect anomalies.
Kapacitor is the final piece of the [TICK stack](https://influxdata.com/time-series-platform/).

## Key features

Here are some of the features that Kapacitor currently supports that make it a
great choice for data processing.

* Process both streaming data and batch data.
* Query data from InfluxDB on a schedule, and receive data via the
[line protocol](/influxdb/v1.0/write_protocols/line/) and any other method InfluxDB supports.
* Perform any transformation currently possible in [InfluxQL](/influxdb/v1.0/query_language/spec/).
* Store transformed data back in InfluxDB.
* Add custom user defined functions to detect anomalies.
* Integrate with HipChat, OpsGenie, Alerta, Sensu, PagerDuty, Slack, and more.


text:
class AddCompletionStatusToEvent < ActiveRecord::Migration[4.2]
  def change
    add_column :marty_events, :error, :boolean, null: true
    execute "update marty_events set error = 'f'"
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.o/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>SQP survey quality prediction and coding system</title>

Survey Quality Prediction (SQP)

Welcome to the SQP website. Please choose one of the following:

                    Estimate the reliability and validity of survey questions

        Provide codes for ESS round 5 questions


text:
In the previous section, we showed how you can crunch the numbers for all the records
in your dataset. This is useful for administrative tasks, but often our applications
are more user-centric. The good news is that aggregations work for every connection in
your API.

Let's compound on the previous example and ask the question, "How many reads did MY posts
get on average in 2016?". To make this work, we need to introduce a `User` type.

Once we setup the connection between our `User` and `Article` types, we can issue a query like this

This query will only perform the aggregation on the articles that are attached to the logged in
user via the `articles` connection. You can continue to manipulate these queries with more and more
advanced filters and aggregations. You'll find that every connection in your API operates the same
way allowing you do run multiple aggregations at different levels in your GraphQL API!

Here is a simple connection between `User` and `Article`:

```graphql
type User {
  id: ID!
  username: String
  password: Secret
  articles: ArticleConnection
}

type Article {
  id: ID!
  title: String
  content: Text
  recommends: Int
  reads: Int
  author: User
}
```

We want to know how many reads did I get in 2016? Conversion?

```graphql
query PostData {
  viewer {
    user {
      articles(where:{ createdAt: { gt: "2016", lt: "2017" }}) {
        aggregations {
          count
          sum {
            recommends
            reads
          }
          avg {
            recommends
            reads
          }
        }
      }
    }
  }
}
```

With Scaphold you can query extremely complex aggregations and combine that with the power of GraphQL connections. This gives incredible power to the client that never before existed. Now go try it in your apps!


text:
package org.hl7.fhir.dstu3.model.codesystems;

// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0

import org.hl7.fhir.exceptions.FHIRException;

public enum SupplydeliveryStatus {

        /**
         * Supply has been requested, but not delivered.
         */
        INPROGRESS,
        /**
         * Supply has been delivered ("completed").
         */
        COMPLETED,
        /**
         * Dispensing was not completed.
         */
        ABANDONED,
        /**
         * added to help the parsers
         */
        NULL;
        public static SupplydeliveryStatus fromCode(String codeString) throws FHIRException {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("in-progress".equals(codeString))
          return INPROGRESS;
        if ("completed".equals(codeString))
          return COMPLETED;
        if ("abandoned".equals(codeString))
          return ABANDONED;
        throw new FHIRException("Unknown SupplydeliveryStatus code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case INPROGRESS: return "in-progress";
            case COMPLETED: return "completed";
            case ABANDONED: return "abandoned";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/supplydelivery-status";
        }
        public String getDefinition() {
          switch (this) {
            case INPROGRESS: return "Supply has been requested, but not delivered.";
            case COMPLETED: return "Supply has been delivered (\"completed\").";
            case ABANDONED: return "Dispensing was not completed.";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case INPROGRESS: return "In Progress";
            case COMPLETED: return "Delivered";
            case ABANDONED: return "Abandoned";
            default: return "?";
          }
    }

}


text:
Ansible all afternoon

## Testing with Vagrant
Initial setup:
```
vagrant up --provision
```

Connect to box:
```
vagrant ssh
```

Stops and delets machine:
```
vagrant destroy
```

Run an ansible playbook manually against  machine (instead of vagrant provision):
```
run_ansible_on_vagrant.sh <playbook>
```

## Being fancy
![ScreenShot](.fancy-machine.jpg)


text:
using System;
using System.Collections.Generic;
using Xamarin.Forms.Internals;

namespace Xamarin.Forms
{
	public partial class VisualElement : Element, IAnimatable, IVisualElementController, IResourcesProvider
	{
		internal static readonly BindablePropertyKey NavigationPropertyKey = BindableProperty.CreateReadOnly("Navigation", typeof(INavigation), typeof(VisualElement), default(INavigation));

		public static readonly BindableProperty NavigationProperty = NavigationPropertyKey.BindableProperty;

		public static readonly BindableProperty InputTransparentProperty = BindableProperty.Create("InputTransparent", typeof(bool), typeof(VisualElement), default(bool));

		public static readonly BindableProperty IsEnabledProperty = BindableProperty.Create("IsEnabled", typeof(bool), typeof(VisualElement), true);

		static readonly BindablePropertyKey XPropertyKey = BindableProperty.CreateReadOnly("X", typeof(double), typeof(VisualElement), default(double));

		public static readonly BindableProperty XProperty = XPropertyKey.BindableProperty;

		static readonly BindablePropertyKey YPropertyKey = BindableProperty.CreateReadOnly("Y", typeof(double), typeof(VisualElement), default(double));

		public static readonly BindableProperty YProperty = YPropertyKey.BindableProperty;

		public static readonly BindableProperty AnchorXProperty = BindableProperty.Create("AnchorX", typeof(double), typeof(VisualElement), .5d);

		public static readonly BindableProperty AnchorYProperty = BindableProperty.Create("AnchorY", typeof(double), typeof(VisualElement), .5d);

		public static readonly BindableProperty TranslationXProperty = BindableProperty.Create("TranslationX", typeof(double), typeof(VisualElement), 0d);

		public static readonly BindableProperty TranslationYProperty = BindableProperty.Create("TranslationY", typeof(double), typeof(VisualElement), 0d);

		static readonly BindablePropertyKey WidthPropertyKey = BindableProperty.CreateReadOnly("Width", typeof(double), typeof(VisualElement), -1d,
			coerceValue: (bindable, value) => double.IsNaN((double)value) ? 0d : value);

		public static readonly BindableProperty WidthProperty = WidthPropertyKey.BindableProperty;

		static readonly BindablePropertyKey HeightPropertyKey = BindableProperty.CreateReadOnly("Height", typeof(double), typeof(VisualElement), -1d,
			coerceValue: (bindable, value) => double.IsNaN((double)value) ? 0d : value);

		public static readonly BindableProperty HeightProperty = HeightPropertyKey.BindableProperty;

		public static readonly BindableProperty RotationProperty = BindableProperty.Create("Rotation", typeof(double), typeof(VisualElement), default(double));

		public static readonly BindableProperty RotationXProperty = BindableProperty.Create("RotationX", typeof(double), typeof(VisualElement), default(double));

		public static readonly BindableProperty RotationYProperty = BindableProperty.Create("RotationY", typeof(double), typeof(VisualElement), default(double));

		public static readonly BindableProperty ScaleProperty = BindableProperty.Create("Scale", typeof(double), typeof(VisualElement), 1d);

		public static readonly BindableProperty IsVisibleProperty = BindableProperty.Create("IsVisible", typeof(bool), typeof(VisualElement), true,
			propertyChanged: (bindable, oldvalue, newvalue) => ((VisualElement)bindable).OnIsVisibleChanged((bool)oldvalue, (bool)newvalue));

		public static readonly BindableProperty OpacityProperty = BindableProperty.Create("Opacity", typeof(double), typeof(VisualElement), 1d, coerceValue: (bindable, value) => ((double)value).Clamp(0, 1));

		public static readonly BindableProperty BackgroundColorProperty = BindableProperty.Create("BackgroundColor", typeof(Color), typeof(VisualElement), Color.Default);

		internal static readonly BindablePropertyKey BehaviorsPropertyKey = BindableProperty.CreateReadOnly("Behaviors", typeof(IList<Behavior>), typeof(VisualElement), default(IList<Behavior>),
			defaultValueCreator: bindable =>
			{
				var collection = new AttachedCollection<Behavior>();
				collection.AttachTo(bindable);
				return collection;
			});

		public static readonly BindableProperty BehaviorsProperty = BehaviorsPropertyKey.BindableProperty;

		internal static readonly BindablePropertyKey TriggersPropertyKey = BindableProperty.CreateReadOnly("Triggers", typeof(IList<TriggerBase>), typeof(VisualElement), default(IList<TriggerBase>),
			defaultValueCreator: bindable =>
			{
				var collection = new AttachedCollection<TriggerBase>();
				collection.AttachTo(bindable);
				return collection;
			});

		public static readonly BindableProperty TriggersProperty = TriggersPropertyKey.BindableProperty;

		public static readonly BindableProperty StyleProperty = BindableProperty.Create("Style", typeof(Style), typeof(VisualElement), default(Style),
			propertyChanged: (bindable, oldvalue, newvalue) => ((VisualElement)bindable)._mergedStyle.Style = (Style)newvalue);

		public static readonly BindableProperty WidthRequestProperty = BindableProperty.Create("WidthRequest", typeof(double), typeof(VisualElement), -1d, propertyChanged: OnRequestChanged);

		public static readonly BindableProperty HeightRequestProperty = BindableProperty.Create("HeightRequest", typeof(double), typeof(VisualElement), -1d, propertyChanged: OnRequestChanged);

		public static readonly BindableProperty MinimumWidthRequestProperty = BindableProperty.Create("MinimumWidthRequest", typeof(double), typeof(VisualElement), -1d, propertyChanged: OnRequestChanged);

		public static readonly BindableProperty MinimumHeightRequestProperty = BindableProperty.Create("MinimumHeightRequest", typeof(double), typeof(VisualElement), -1d, propertyChanged: OnRequestChanged);

		internal static readonly BindablePropertyKey IsFocusedPropertyKey = BindableProperty.CreateReadOnly("IsFocused", typeof(bool), typeof(VisualElement), default(bool),
			propertyChanged: OnIsFocusedPropertyChanged);

		public static readonly BindableProperty IsFocusedProperty = IsFocusedPropertyKey.BindableProperty;

		readonly Dictionary<Size, SizeRequest> _measureCache = new Dictionary<Size, SizeRequest>();

		readonly MergedStyle _mergedStyle;

		int _batched;
		LayoutConstraint _computedConstraint;

		bool _isInNativeLayout;

		bool _isNativeStateConsistent = true;

		bool _isPlatformEnabled;

		double _mockHeight = -1;

		double _mockWidth = -1;

		double _mockX = -1;

		double _mockY = -1;

		ResourceDictionary _resources;
		LayoutConstraint _selfConstraint;

		internal VisualElement()
		{
			Navigation = new NavigationProxy();
			_mergedStyle = new MergedStyle(GetType(), this);
		}

		public double AnchorX
		{
			get { return (double)GetValue(AnchorXProperty); }
			set { SetValue(AnchorXProperty, value); }
		}

		public double AnchorY
		{
			get { return (double)GetValue(AnchorYProperty); }
			set { SetValue(AnchorYProperty, value); }
		}

		public Color BackgroundColor
		{
			get { return (Color)GetValue(BackgroundColorProperty); }
			set { SetValue(BackgroundColorProperty, value); }
		}

		public IList<Behavior> Behaviors
		{
			get { return (IList<Behavior>)GetValue(BehaviorsProperty); }
		}

		public Rectangle Bounds
		{
			get { return new Rectangle(X, Y, Width, Height); }
			private set
			{
				if (value.X == X && value.Y == Y && value.Height == Height && value.Width == Width)
					return;
				BatchBegin();
				X = value.X;
				Y = value.Y;
				SetSize(value.Width, value.Height);
				BatchCommit();
			}
		}

		public double Height
		{
			get { return _mockHeight == -1 ? (double)GetValue(HeightProperty) : _mockHeight; }
			private set { SetValue(HeightPropertyKey, value); }
		}

		public double HeightRequest
		{
			get { return (double)GetValue(HeightRequestProperty); }
			set { SetValue(HeightRequestProperty, value); }
		}

		public bool InputTransparent
		{
			get { return (bool)GetValue(InputTransparentProperty); }
			set { SetValue(InputTransparentProperty, value); }
		}

		public bool IsEnabled
		{
			get { return (bool)GetValue(IsEnabledProperty); }
			set { SetValue(IsEnabledProperty, value); }
		}

		public bool IsFocused
		{
			get { return (bool)GetValue(IsFocusedProperty); }
		}

		public bool IsVisible
		{
			get { return (bool)GetValue(IsVisibleProperty); }
			set { SetValue(IsVisibleProperty, value); }
		}

		public double MinimumHeightRequest
		{
			get { return (double)GetValue(MinimumHeightRequestProperty); }
			set { SetValue(MinimumHeightRequestProperty, value); }
		}

		public double MinimumWidthRequest
		{
			get { return (double)GetValue(MinimumWidthRequestProperty); }
			set { SetValue(MinimumWidthRequestProperty, value); }
		}

		public INavigation Navigation
		{
			get { return (INavigation)GetValue(NavigationProperty); }
			internal set { SetValue(NavigationPropertyKey, value); }
		}

		public double Opacity
		{
			get { return (double)GetValue(OpacityProperty); }
			set { SetValue(OpacityProperty, value); }
		}

		public double Rotation
		{
			get { return (double)GetValue(RotationProperty); }
			set { SetValue(RotationProperty, value); }
		}

		public double RotationX
		{
			get { return (double)GetValue(RotationXProperty); }
			set { SetValue(RotationXProperty, value); }
		}

		public double RotationY
		{
			get { return (double)GetValue(RotationYProperty); }
			set { SetValue(RotationYProperty, value); }
		}

		public double Scale
		{
			get { return (double)GetValue(ScaleProperty); }
			set { SetValue(ScaleProperty, value); }
		}

		public Style Style
		{
			get { return (Style)GetValue(StyleProperty); }
			set { SetValue(StyleProperty, value); }
		}

		[TypeConverter (typeof(ListStringTypeConverter))]
		public IList<string> StyleClass
		{
			get { return _mergedStyle.StyleClass; }
			set { _mergedStyle.StyleClass = value; }
		}

		public double TranslationX
		{
			get { return (double)GetValue(TranslationXProperty); }
			set { SetValue(TranslationXProperty, value); }
		}

		public double TranslationY
		{
			get { return (double)GetValue(TranslationYProperty); }
			set { SetValue(TranslationYProperty, value); }
		}

		public IList<TriggerBase> Triggers
		{
			get { return (IList<TriggerBase>)GetValue(TriggersProperty); }
		}

		public double Width
		{
			get { return _mockWidth == -1 ? (double)GetValue(WidthProperty) : _mockWidth; }
			private set { SetValue(WidthPropertyKey, value); }
		}

		public double WidthRequest
		{
			get { return (double)GetValue(WidthRequestProperty); }
			set { SetValue(WidthRequestProperty, value); }
		}

		public double X
		{
			get { return _mockX == -1 ? (double)GetValue(XProperty) : _mockX; }
			private set { SetValue(XPropertyKey, value); }
		}

		public double Y
		{
			get { return _mockY == -1 ? (double)GetValue(YProperty) : _mockY; }
			private set { SetValue(YPropertyKey, value); }
		}

		internal bool Batched
		{
			get { return _batched > 0; }
		}

		internal LayoutConstraint ComputedConstraint
		{
			get { return _computedConstraint; }
			set
			{
				if (_computedConstraint == value)
					return;

				LayoutConstraint oldConstraint = Constraint;
				_computedConstraint = value;
				LayoutConstraint newConstraint = Constraint;
				if (oldConstraint != newConstraint)
					OnConstraintChanged(oldConstraint, newConstraint);
			}
		}

		internal LayoutConstraint Constraint
		{
			get { return ComputedConstraint | SelfConstraint; }
		}

		internal bool DisableLayout { get; set; }

		internal bool IsInNativeLayout
		{
			get
			{
				if (_isInNativeLayout)
					return true;

				Element parent = RealParent;
				while (parent != null)
				{
					var visualElement = parent as VisualElement;
					if (visualElement != null && visualElement.IsInNativeLayout)
						return true;
					parent = parent.RealParent;
				}

				return false;
			}
			set { _isInNativeLayout = value; }
		}

		internal bool IsNativeStateConsistent
		{
			get { return _isNativeStateConsistent; }
			set
			{
				if (_isNativeStateConsistent == value)
					return;
				_isNativeStateConsistent = value;
				if (value && IsPlatformEnabled)
					InvalidateMeasureInternal(InvalidationTrigger.RendererReady);
			}
		}

		internal bool IsPlatformEnabled
		{
			get { return _isPlatformEnabled; }
			set
			{
				if (value == _isPlatformEnabled)
					return;

				_isPlatformEnabled = value;
				if (value && IsNativeStateConsistent)
					InvalidateMeasureInternal(InvalidationTrigger.RendererReady);

				OnIsPlatformEnabledChanged();
			}
		}

		internal NavigationProxy NavigationProxy
		{
			get { return Navigation as NavigationProxy; }
		}

		internal LayoutConstraint SelfConstraint
		{
			get { return _selfConstraint; }
			set
			{
				if (_selfConstraint == value)
					return;

				LayoutConstraint oldConstraint = Constraint;
				_selfConstraint = value;
				LayoutConstraint newConstraint = Constraint;
				if (oldConstraint != newConstraint)
				{
					OnConstraintChanged(oldConstraint, newConstraint);
				}
			}
		}

		public void BatchBegin()
		{
			_batched++;
		}

		public void BatchCommit()
		{
			_batched = Math.Max(0, _batched - 1);
			if (!Batched && BatchCommitted != null)
				BatchCommitted(this, new EventArg<VisualElement>(this));
		}

		public ResourceDictionary Resources
		{
			get { return _resources; }
			set
			{
				if (_resources == value)
					return;
				OnPropertyChanging();
				if (_resources != null)
					((IResourceDictionary)_resources).ValuesChanged -= OnResourcesChanged;
				_resources = value;
				OnResourcesChanged(value);
				if (_resources != null)
					((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged;
				OnPropertyChanged();
			}
		}

		void IVisualElementController.NativeSizeChanged()
		{
			InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
		}

		public event EventHandler ChildrenReordered;

		public bool Focus()
		{
			if (IsFocused)
				return true;

			if (FocusChangeRequested == null)
				return false;

			var arg = new FocusRequestArgs { Focus = true };
			FocusChangeRequested(this, arg);
			return arg.Result;
		}

		public event EventHandler<FocusEventArgs> Focused;

		[Obsolete("Use Measure")]
		public virtual SizeRequest GetSizeRequest(double widthConstraint, double heightConstraint)
		{
			SizeRequest cachedResult;
			var constraintSize = new Size(widthConstraint, heightConstraint);
			if (_measureCache.TryGetValue(constraintSize, out cachedResult))
			{
				return cachedResult;
			}

			double widthRequest = WidthRequest;
			double heightRequest = HeightRequest;
			if (widthRequest >= 0)
				widthConstraint = Math.Min(widthConstraint, widthRequest);
			if (heightRequest >= 0)
				heightConstraint = Math.Min(heightConstraint, heightRequest);

			SizeRequest result = OnMeasure(widthConstraint, heightConstraint);
			bool hasMinimum = result.Minimum != result.Request;
			Size request = result.Request;
			Size minimum = result.Minimum;

			if (heightRequest != -1)
			{
				request.Height = heightRequest;
				if (!hasMinimum)
					minimum.Height = heightRequest;
			}

			if (widthRequest != -1)
			{
				request.Width = widthRequest;
				if (!hasMinimum)
					minimum.Width = widthRequest;
			}

			double minimumHeightRequest = MinimumHeightRequest;
			double minimumWidthRequest = MinimumWidthRequest;

			if (minimumHeightRequest != -1)
				minimum.Height = minimumHeightRequest;
			if (minimumWidthRequest != -1)
				minimum.Width = minimumWidthRequest;

			minimum.Height = Math.Min(request.Height, minimum.Height);
			minimum.Width = Math.Min(request.Width, minimum.Width);

			var r = new SizeRequest(request, minimum);

			if (r.Request.Width > 0 && r.Request.Height > 0)
			{
				_measureCache[constraintSize] = r;
			}

			return r;
		}

		public void Layout(Rectangle bounds)
		{
			Bounds = bounds;
		}

		public SizeRequest Measure(double widthConstraint, double heightConstraint, MeasureFlags flags = MeasureFlags.None)
		{
			bool includeMargins = (flags & MeasureFlags.IncludeMargins) != 0;
			Thickness margin = default(Thickness);
			if (includeMargins)
			{
				var view = this as View;
				if (view != null)
					margin = view.Margin;
				widthConstraint = Math.Max(0, widthConstraint - margin.HorizontalThickness);
				heightConstraint = Math.Max(0, heightConstraint - margin.VerticalThickness);
			}
#pragma warning disable 0618 // retain until GetSizeRequest removed
			SizeRequest result = GetSizeRequest(widthConstraint, heightConstraint);
#pragma warning restore 0618

			if (includeMargins)
			{

				if (!margin.IsDefault)
				{
					result.Minimum = new Size(result.Minimum.Width + margin.HorizontalThickness, result.Minimum.Height + margin.VerticalThickness);
					result.Request = new Size(result.Request.Width + margin.HorizontalThickness, result.Request.Height + margin.VerticalThickness);
				}
			}

			return result;
		}

		public event EventHandler MeasureInvalidated;

		public event EventHandler SizeChanged;

		public void Unfocus()
		{
			if (!IsFocused)
				return;

			EventHandler<FocusRequestArgs> unfocus = FocusChangeRequested;
			if (unfocus != null)
			{
				unfocus(this, new FocusRequestArgs());
			}
		}

		public event EventHandler<FocusEventArgs> Unfocused;

		protected virtual void InvalidateMeasureInternal()
		{
			InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
		}

		protected override void OnChildAdded(Element child)
		{
			base.OnChildAdded(child);
			var view = child as View;
			if (view != null)
				ComputeConstraintForView(view);
		}

		protected override void OnChildRemoved(Element child)
		{
			base.OnChildRemoved(child);
			var view = child as View;
			if (view != null)
				view.ComputedConstraint = LayoutConstraint.None;
		}

		protected void OnChildrenReordered()
		{
			if (ChildrenReordered != null)
				ChildrenReordered(this, EventArgs.Empty);
		}

		protected virtual SizeRequest OnMeasure(double widthConstraint, double heightConstraint)
		{
#pragma warning disable 0618 // retain until OnSizeRequest removed
			return OnSizeRequest(widthConstraint, heightConstraint);
#pragma warning restore 0618
		}

		protected override void OnParentSet()
		{
#pragma warning disable 0618 // retain until ParentView removed
			base.OnParentSet();

			if (ParentView != null)
			{
				NavigationProxy.Inner = ParentView.NavigationProxy;
			}
			else
			{
				NavigationProxy.Inner = null;
			}
#pragma warning restore 0618
		}

		protected virtual void OnSizeAllocated(double width, double height)
		{
		}

		[Obsolete("Use OnMeasure")]
		protected virtual SizeRequest OnSizeRequest(double widthConstraint, double heightConstraint)
		{
			if (Platform == null || !IsPlatformEnabled)
			{
				return new SizeRequest(new Size(-1, -1));
			}
			return Platform.GetNativeSize(this, widthConstraint, heightConstraint);
		}

		protected void SizeAllocated(double width, double height)
		{
			OnSizeAllocated(width, height);
		}

		internal event EventHandler<EventArg<VisualElement>> BatchCommitted;

		internal void ComputeConstrainsForChildren()
		{
			for (var i = 0; i < LogicalChildren.Count; i++)
			{
				var child = LogicalChildren[i] as View;
				if (child != null)
					ComputeConstraintForView(child);
			}
		}

		internal virtual void ComputeConstraintForView(View view)
		{
			view.ComputedConstraint = LayoutConstraint.None;
		}

		internal event EventHandler<FocusRequestArgs> FocusChangeRequested;

		internal virtual void InvalidateMeasureInternal(InvalidationTrigger trigger)
		{
			_measureCache.Clear();
			MeasureInvalidated?.Invoke(this, new InvalidationEventArgs(trigger));
		}

		void IVisualElementController.InvalidateMeasure(InvalidationTrigger trigger)
		{
			InvalidateMeasureInternal(trigger);
		}

		internal void MockBounds(Rectangle bounds)
		{
			_mockX = bounds.X;
			_mockY = bounds.Y;
			_mockWidth = bounds.Width;
			_mockHeight = bounds.Height;
		}

		internal virtual void OnConstraintChanged(LayoutConstraint oldConstraint, LayoutConstraint newConstraint)
		{
			ComputeConstrainsForChildren();
		}

		internal virtual void OnIsPlatformEnabledChanged()
		{
		}

		internal virtual void OnIsVisibleChanged(bool oldValue, bool newValue)
		{
			InvalidateMeasureInternal(InvalidationTrigger.Undefined);
		}

		internal override void OnParentResourcesChanged(IEnumerable<KeyValuePair<string, object>> values)
		{
			if (values == null)
				return;

			if (Resources == null || Resources.Count == 0)
			{
				base.OnParentResourcesChanged(values);
				return;
			}

			var innerKeys = new HashSet<string>();
			var changedResources = new List<KeyValuePair<string, object>>();
			foreach (KeyValuePair<string, object> c in Resources)
				innerKeys.Add(c.Key);
			foreach (KeyValuePair<string, object> value in values)
			{
				if (innerKeys.Add(value.Key))
					changedResources.Add(value);
				else if (value.Key.StartsWith(Style.StyleClassPrefix, StringComparison.Ordinal))
				{
					var mergedClassStyles = new List<Style>(Resources[value.Key] as List<Style>);
					mergedClassStyles.AddRange(value.Value as List<Style>);
					changedResources.Add(new KeyValuePair<string, object>(value.Key, mergedClassStyles));
				}
			}
			if (changedResources.Count != 0)
				OnResourcesChanged(changedResources);
		}

		internal void UnmockBounds()
		{
			_mockX = _mockY = _mockWidth = _mockHeight = -1;
		}

		void OnFocused()
		{
			EventHandler<FocusEventArgs> focus = Focused;
			if (focus != null)
				focus(this, new FocusEventArgs(this, true));
		}

		static void OnIsFocusedPropertyChanged(BindableObject bindable, object oldvalue, object newvalue)
		{
			var element = bindable as VisualElement;

			var isFocused = (bool)newvalue;
			if (isFocused)
			{
				element.OnFocused();
			}
			else
			{
				element.OnUnfocus();
			}
		}

		static void OnRequestChanged(BindableObject bindable, object oldvalue, object newvalue)
		{
			var constraint = LayoutConstraint.None;
			var element = (VisualElement)bindable;
			if (element.WidthRequest >= 0 && element.MinimumWidthRequest >= 0)
			{
				constraint |= LayoutConstraint.HorizontallyFixed;
			}
			if (element.HeightRequest >= 0 && element.MinimumHeightRequest >= 0)
			{
				constraint |= LayoutConstraint.VerticallyFixed;
			}

			element.SelfConstraint = constraint;
			((VisualElement)bindable).InvalidateMeasureInternal(InvalidationTrigger.SizeRequestChanged);
		}

		void OnUnfocus()
		{
			EventHandler<FocusEventArgs> unFocus = Unfocused;
			if (unFocus != null)
				unFocus(this, new FocusEventArgs(this, false));
		}

		void SetSize(double width, double height)
		{
			if (Width == width && Height == height)
				return;

			Width = width;
			Height = height;

			SizeAllocated(width, height);
			if (SizeChanged != null)
				SizeChanged(this, EventArgs.Empty);
		}

		internal class FocusRequestArgs : EventArgs
		{
			public bool Focus { get; set; }

			public bool Result { get; set; }
		}
	}
}


text:
from django.conf.urls import include, url
from rest_framework.routers import DefaultRouter
from experiment_session.views import (ExperimentSessionViewSet, get_experiment_settings,
                                      get_lightset, pause_current_lightset, report_user_data,
                                      report_training_finished, create_sessions)

router = DefaultRouter(trailing_slash=False)
router.register(r'experiment-sessions', ExperimentSessionViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^extra/get-experiment', get_experiment_settings),
    url(r'^extra/get-lightset', get_lightset),
    url(r'^extra/pause-lightset', pause_current_lightset),
    url(r'^extra/report-data', report_user_data),
    url(r'^extra/training-finished', report_training_finished),
    url(r'^extra/create-sessions', create_sessions),
]


text:
@interface DPSqlserverDepartmentCrud : NSObject <DPDepartmentCrud>

@end


text:
<readable><title>207237775_fa0a15c6fe</title><content>
A man doing a back flip while another takes a picture .
A person is taking a picture of another person doing a flip in midair in the grass .
A young man takes a picture of his friend doing gymnastics in a field
One man taking a photo of another man jumping in a field by a small tree .
One person does a flip in the middle of the field while their friend takes a picture .
</content></readable>


text:
using Cake.Core.Tooling;

namespace Cake.DocFx.Serve
{
    /// <summary>
    /// Contains settings used by <see cref="DocFxServeRunner"/>.
    /// </summary>
    public class DocFxServeSettings : ToolSettings
    {
        /// <summary>
        /// Gets or sets the hostname on which to serve the content. Defaults to 'localhost'.
        /// </summary>
        public string Hostname { get; set; }

        /// <summary>
        /// Gets or sets the local port on which to serve the content. Defaults to '8080'.
        /// </summary>
        public string Port { get; set; }
    }
}


text:
// Copyright (C) 2013 by Toni Petrina
//
// 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.

using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Collections.Specialized;
using Wp7nl.Behaviors;

namespace WP.Helpers.Ui.Behaviors
{
    public class EmptyListBoxBehavior : SafeBehavior<ListBox>
    {
        #region EmptyTemplate dependency property

        public ControlTemplate EmptyTemplate
        {
            get { return (ControlTemplate)GetValue(EmptyTemplateProperty); }
            set { SetValue(EmptyTemplateProperty, value); }
        }

        public static readonly DependencyProperty EmptyTemplateProperty = DependencyProperty.Register(
            "EmptyTemplate", typeof(ControlTemplate), typeof(EmptyListBoxBehavior), new PropertyMetadata(null));

        #endregion

        #region DefaultTemplate dependency property

        public ControlTemplate DefaultTemplate
        {
            get { return (ControlTemplate)GetValue(DefaultTemplateProperty); }
            set { SetValue(DefaultTemplateProperty, value); }
        }

        public static readonly DependencyProperty DefaultTemplateProperty = DependencyProperty.Register(
            "DefaultTemplate", typeof(ControlTemplate), typeof(EmptyListBoxBehavior), new PropertyMetadata(null));

        #endregion

        #region ItemsSource dependency property

        public IEnumerable ItemsSource
        {
            get { return (IEnumerable)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(
            "ItemsSource", typeof(IEnumerable), typeof(EmptyListBoxBehavior), new PropertyMetadata(null, ItemsSourceChanged));

        #endregion

        protected override void OnAttached()
        {
            base.OnAttached();

            BindingOperations.SetBinding(this, ItemsSourceProperty, new Binding("ItemsSource")
            {
                Source = AssociatedObject,
                Mode = BindingMode.TwoWay,
                Path = new PropertyPath("ItemsSource")
            });

            Update(null, null);
        }

        private static void ItemsSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((EmptyListBoxBehavior)o).Update(e.OldValue, e.NewValue);
        }

        private void Update(object oldValue, object newValue)
        {
            var oldSource = oldValue as IEnumerable;
            var newSource = newValue as IEnumerable;

            if ((newSource == null || !newSource.GetEnumerator().MoveNext()) && EmptyTemplate != null)
                AssociatedObject.Template = EmptyTemplate;
            else
                AssociatedObject.Template = DefaultTemplate;

            var oldCollection = oldSource as INotifyCollectionChanged;
            var newCollection = newSource as INotifyCollectionChanged;

            if (newCollection != null)
                newCollection.CollectionChanged += newCollection_CollectionChanged;
            if (oldCollection != null)
                oldCollection.CollectionChanged -= newCollection_CollectionChanged;
        }

        void newCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((IList)sender).Count != 0)
                AssociatedObject.Template = DefaultTemplate;
            else
                AssociatedObject.Template = EmptyTemplate;
        }
    }
}


text:
'use strict';

module.exports = require('./skej');


text:
$(document).ready(function() {
    var s = $(".querybar-content");
    var pos = s.position();
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        if (windowpos >= pos.top) {
            s.addClass("stick");
        } else {
            s.removeClass("stick");
        }
    });
});


text:
import React from "react";
import reactNative from "react-native";
import Component from "../../framework/component";
const {View, Image, TouchableOpacity, Platform, NativeModules: {ImagePickerManager}} = reactNative;
import I18n from "react-native-i18n";
import {uploadCompanyMediaAction} from '../../helpers/requests'

export default class ImageScreen extends Component {
    selectPhotoTapped() {
        let self = this;
        const options = {
            title: I18n.t('image_picker'),
            takePhotoButtonTitle: I18n.t('take_image'),
            chooseFromLibraryButtonTitle: I18n.t('choose_image'),
            cancelButtonTitle:  I18n.t('cancel'),
            storageOptions: {
                skipBackup: true,
                path: 'App-Arena'
            },
            noData: true,
            allowsEditing: true
        };

        ImagePickerManager.showImagePicker(options, (response) => {
            console.log('Response = ', response);

            if (response.didCancel) {
                console.log('User cancelled photo picker');
            }
            else if (response.error) {
                console.log('ImagePickerManager Error: ', response.error);
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            }
            else {
                // You can display the image using either:
                //const source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true};
                var fileURL;
                if (Platform.OS === 'android') {
                    fileURL = response.uri
                } else {
                    fileURL = response.uri.replace('file://', '')
                }
                let data = new FormData();
                if (fileURL) {
                    data.append('image', {uri: fileURL, name: self.props.configId + '.jpg', type: 'image/jpg'})
                }
                uploadCompanyMediaAction(self.props.auth.companyId, data)
                    .then((response) => response.json())
                    .then((result) => {
                        if (result.status == "201") {
                            this.props.setValue(result.files[0].uri)
                        }
                    })
                    .catch((error) => {
                        console.warn(error);
                    });
            }
        });
    }

    render() {
        return (
            <View>
                <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
                    <Image
                        resizeMode="contain"
                        style={{flex:1, height: 250, backgroundColor: '#fff'}}
                        source={{uri: this.props.value}}/>
                </TouchableOpacity>
            </View>
        );
    }

}


text:
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ReactDOM from 'react-dom';

import Glyphicon from '../src/Glyphicon';

describe('Glyphicon', () => {
  it('Should have correct class', () => {
    let instance = ReactTestUtils.renderIntoDocument(
      <Glyphicon glyph='star' />
    );
    assert.ok(ReactDOM.findDOMNode(instance).className.match(/\bglyphicon\b/));
    assert.ok(ReactDOM.findDOMNode(instance).className.match(/\bglyphicon-star\b/));
  });

  it('renders without the .form-control-feedback class', () => {
    let instance = ReactTestUtils.renderIntoDocument(
      <Glyphicon glyph='star' />
    );

    assert.notOk(ReactDOM.findDOMNode(instance).className.match(/\bform-control-feedback\b/));
  });

  context('when setting the formControlFeedback prop', () => {
    it('should have the .form-control-feedback class set', () => {
      let instance = ReactTestUtils.renderIntoDocument(
        <Glyphicon formControlFeedback glyph='star' />
      );

      assert.ok(ReactDOM.findDOMNode(instance).className.match(/\bform-control-feedback\b/));
    });
  });
});


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/download/download_service.h"
#include "chrome/browser/download/download_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/chromeos_switches.h"
#include "components/signin/core/browser/signin_manager_base.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/download_item.h"
#include "content/public/browser/download_manager.h"
#include "content/public/test/download_test_observer.h"
#include "grit/theme_resources.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/url_request/url_request_slow_download_job.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/message_center_observer.h"
#include "url/gurl.h"

namespace {

enum {
  DUMMY_ACCOUNT_INDEX = 0,
  PRIMARY_ACCOUNT_INDEX = 1,
  SECONDARY_ACCOUNT_INDEX_START = 2,
};

// Structure to describe an account info.
struct TestAccountInfo {
  const char* const email;
  const char* const gaia_id;
  const char* const hash;
  const char* const display_name;
};

// Accounts for multi profile test.
static const TestAccountInfo kTestAccounts[] = {
    {"__dummy__@invalid.domain", "10000", "hashdummy", "Dummy Account"},
    {"alice@invalid.domain",     "10001", "hashalice", "Alice"},
    {"bob@invalid.domain",       "10002", "hashbobbo", "Bob"},
    {"charlie@invalid.domain",   "10003", "hashcharl", "Charlie"},
};

bool IsInNotifications(
    const message_center::NotificationList::Notifications& notifications,
    const std::string& id) {
  for (const auto& notification : notifications) {
    if (notification->id() == id)
      return true;
  }
  return false;
}

// Base class observing notification events.
class MessageCenterChangeObserver
    : public message_center::MessageCenterObserver {
 public:
  MessageCenterChangeObserver() {
    message_center::MessageCenter::Get()->AddObserver(this);
  }

  ~MessageCenterChangeObserver() override {
    message_center::MessageCenter::Get()->RemoveObserver(this);
  }

 protected:
  void RunLoop() {
    base::MessageLoop::ScopedNestableTaskAllower allow(
        base::MessageLoop::current());
    run_loop_.Run();
  }

  void QuitRunLoop() {
    run_loop_.Quit();
  }

 private:
  base::RunLoop run_loop_;

  DISALLOW_COPY_AND_ASSIGN(MessageCenterChangeObserver);
};

// Class observing of "ADD" notification events.
class NotificationAddObserver : public MessageCenterChangeObserver {
 public:
  NotificationAddObserver() : count_(1) {}
  explicit NotificationAddObserver(int count) : count_(count) {
    MessageCenterChangeObserver();
  }
  ~NotificationAddObserver() override {}

  bool Wait() {
    if (count_ <= 0)
      return count_ == 0;

    waiting_ = true;
    RunLoop();
    waiting_ = false;
    return count_ == 0;
  }

  // message_center::MessageCenterObserver:
  void OnNotificationAdded(const std::string& notification_id) override {
    count_--;

    notification_ids_.push_back(notification_id);

    if (waiting_ && count_ == 0)
      QuitRunLoop();
  }

  const std::string& notification_id() const { return notification_ids_.at(0); }
  const std::vector<std::string>& notification_ids() const {
    return notification_ids_;
  }

 private:
  std::vector<std::string> notification_ids_;
  bool waiting_ = false;
  int count_;

  DISALLOW_COPY_AND_ASSIGN(NotificationAddObserver);
};

// Class observing of "UPDATE" notification events.
class NotificationUpdateObserver : public MessageCenterChangeObserver {
 public:
  NotificationUpdateObserver() {}
  ~NotificationUpdateObserver() override {}

  std::string Wait() {
    if (!notification_id_.empty())
      return notification_id_;

    waiting_ = true;
    RunLoop();
    waiting_ = false;
    return notification_id_;
  }

  void OnNotificationUpdated(const std::string& notification_id) override {
    if (notification_id_.empty()) {
      notification_id_ = notification_id;

      if (waiting_)
        QuitRunLoop();
    }
  }

 private:
  std::string notification_id_;
  bool waiting_ = false;

  DISALLOW_COPY_AND_ASSIGN(NotificationUpdateObserver);
};

// Class observing of "REMOVE" notification events.
class NotificationRemoveObserver : public MessageCenterChangeObserver {
 public:
  NotificationRemoveObserver() {}
  ~NotificationRemoveObserver() override {}

  std::string Wait() {
    if (!notification_id_.empty())
      return notification_id_;

    waiting_ = true;
    RunLoop();
    waiting_ = false;
    return notification_id_;
  }

  // message_center::MessageCenterObserver:
  void OnNotificationRemoved(
      const std::string& notification_id, bool by_user) override {
    if (notification_id_.empty()) {
      notification_id_ = notification_id;

      if (waiting_)
        QuitRunLoop();
    }
  }

 private:
  std::string notification_id_;
  bool waiting_ = false;

  DISALLOW_COPY_AND_ASSIGN(NotificationRemoveObserver);
};

class TestChromeDownloadManagerDelegate : public ChromeDownloadManagerDelegate {
 public:
  explicit TestChromeDownloadManagerDelegate(Profile* profile)
      : ChromeDownloadManagerDelegate(profile), opened_(false) {}
  ~TestChromeDownloadManagerDelegate() override {}

  // ChromeDownloadManagerDelegate override:
  void OpenDownload(content::DownloadItem* item) override { opened_ = true; }

  // Return if  the download is opened.
  bool opened() const { return opened_; }

 private:
  bool opened_;
};

// Utility method to retrieve a message center.
message_center::MessageCenter* GetMessageCenter() {
  return message_center::MessageCenter::Get();
}

// Utility method to retrieve a notification object by id.
message_center::Notification* GetNotification(const std::string& id) {
  return GetMessageCenter()->FindVisibleNotificationById(id);
}

}  // anonnymous namespace

// Base class for tests
class DownloadNotificationTestBase : public InProcessBrowserTest {
 public:
  ~DownloadNotificationTestBase() override {}

  void SetUpCommandLine(base::CommandLine* command_line) override {
    // TODO(yoshiki): Remove this after the download notification launches.
    command_line->AppendSwitchASCII(switches::kEnableDownloadNotification,
                                    "enabled");
  }

  void SetUp() override {
    base::FilePath test_data_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir);
    embedded_test_server()->ServeFilesFromDirectory(test_data_dir);

    ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
    embedded_test_server()->StopThread();
    InProcessBrowserTest::SetUp();
  }

  void SetUpOnMainThread() override {
    embedded_test_server()->RestartThreadAndListen();

    content::BrowserThread::PostTask(
        content::BrowserThread::IO, FROM_HERE,
        base::Bind(&net::URLRequestSlowDownloadJob::AddUrlHandler));
  }

  content::DownloadManager* GetDownloadManager(Browser* browser) {
    return content::BrowserContext::GetDownloadManager(browser->profile());
  }
};

//////////////////////////////////////////////////
// Test with a single profile
//////////////////////////////////////////////////

class DownloadNotificationTest : public DownloadNotificationTestBase {
 public:
  ~DownloadNotificationTest() override {}

  void SetUpOnMainThread() override {
    Profile* profile = browser()->profile();

    scoped_ptr<TestChromeDownloadManagerDelegate> test_delegate;
    test_delegate.reset(new TestChromeDownloadManagerDelegate(profile));
    test_delegate->GetDownloadIdReceiverCallback().Run(
        content::DownloadItem::kInvalidId + 1);
    DownloadServiceFactory::GetForBrowserContext(profile)
        ->SetDownloadManagerDelegateForTesting(test_delegate.Pass());

    DownloadNotificationTestBase::SetUpOnMainThread();
  }

  TestChromeDownloadManagerDelegate* GetDownloadManagerDelegate() const {
    return static_cast<TestChromeDownloadManagerDelegate*>(
        DownloadServiceFactory::GetForBrowserContext(browser()->profile())
            ->GetDownloadManagerDelegate());
  }

  void PrepareIncognitoBrowser() {
    incognito_browser_ = CreateIncognitoBrowser();
    Profile* incognito_profile = incognito_browser_->profile();

    scoped_ptr<TestChromeDownloadManagerDelegate> incognito_test_delegate;
    incognito_test_delegate.reset(
        new TestChromeDownloadManagerDelegate(incognito_profile));
    DownloadServiceFactory::GetForBrowserContext(incognito_profile)
        ->SetDownloadManagerDelegateForTesting(incognito_test_delegate.Pass());
  }

  TestChromeDownloadManagerDelegate* GetIncognitoDownloadManagerDelegate()
      const {
    Profile* incognito_profile = incognito_browser()->profile();
    return static_cast<TestChromeDownloadManagerDelegate*>(
        DownloadServiceFactory::GetForBrowserContext(incognito_profile)->
        GetDownloadManagerDelegate());
  }

  void CreateDownload() {
    return CreateDownloadForBrowserAndURL(
        browser(),
        GURL(net::URLRequestSlowDownloadJob::kKnownSizeUrl));
  }

  void CreateDownloadForBrowserAndURL(Browser* browser, GURL url) {
    // Starts a download.
    NotificationAddObserver download_start_notification_observer;
    ui_test_utils::NavigateToURL(browser, url);
    EXPECT_TRUE(download_start_notification_observer.Wait());

    // Confirms that a notification is created.
    notification_id_ = download_start_notification_observer.notification_id();
    EXPECT_FALSE(notification_id_.empty());
    ASSERT_TRUE(notification());

    // Confirms that there is only one notification.
    message_center::NotificationList::Notifications
        visible_notifications = GetMessageCenter()->GetVisibleNotifications();
    EXPECT_EQ(1u, visible_notifications.size());
    EXPECT_TRUE(IsInNotifications(visible_notifications, notification_id_));

    // Confirms that a download is also started.
    std::vector<content::DownloadItem*> downloads;
    GetDownloadManager(browser)->GetAllDownloads(&downloads);
    EXPECT_EQ(1u, downloads.size());
    download_item_ = downloads[0];
    ASSERT_TRUE(download_item_);
  }

  content::DownloadItem* download_item() const { return download_item_; }
  std::string notification_id() const { return notification_id_; }
  message_center::Notification* notification() const {
    return GetNotification(notification_id_);
  }
  Browser* incognito_browser() const { return incognito_browser_; }
  base::FilePath GetDownloadPath() {
    return DownloadPrefs::FromDownloadManager(GetDownloadManager(browser()))->
      DownloadPath();
  }

 private:
  content::DownloadItem* download_item_ = nullptr;
  Browser* incognito_browser_ = nullptr;
  std::string notification_id_;
};

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest, DownloadFile) {
  CreateDownload();

  EXPECT_EQ(l10n_util::GetStringFUTF16(
                IDS_DOWNLOAD_STATUS_IN_PROGRESS_TITLE,
                download_item()->GetFileNameToReportUser().LossyDisplayName()),
            GetNotification(notification_id())->title());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_PROGRESS,
            GetNotification(notification_id())->type());

  NotificationUpdateObserver download_notification_update_observer;

  // Requests to complete the download.
  ui_test_utils::NavigateToURL(
      browser(), GURL(net::URLRequestSlowDownloadJob::kFinishDownloadUrl));

  // Waits for download completion.
  while (download_item()->GetState() != content::DownloadItem::COMPLETE) {
    NotificationUpdateObserver download_change_notification_observer;
    download_change_notification_observer.Wait();
  }

  // Waits for new notification.
  download_notification_update_observer.Wait();

  // Checks strings.
  EXPECT_EQ(l10n_util::GetStringFUTF16(
                IDS_DOWNLOAD_STATUS_DOWNLOADED_TITLE,
                download_item()->GetFileNameToReportUser().LossyDisplayName()),
            GetNotification(notification_id())->title());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id())->type());

  // Confirms that there is only one notification.
  message_center::NotificationList::Notifications
      visible_notifications = GetMessageCenter()->GetVisibleNotifications();
  EXPECT_EQ(1u, visible_notifications.size());
  EXPECT_TRUE(IsInNotifications(visible_notifications, notification_id()));

  // Opens the message center.
  GetMessageCenter()->SetVisibility(message_center::VISIBILITY_MESSAGE_CENTER);

  // Try to open the downloaded item by clicking the notification.
  EXPECT_FALSE(GetDownloadManagerDelegate()->opened());
  GetMessageCenter()->ClickOnNotification(notification_id());
  EXPECT_TRUE(GetDownloadManagerDelegate()->opened());

  EXPECT_FALSE(GetNotification(notification_id()));
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest, DownloadDangerousFile) {
  GURL download_url(embedded_test_server()->GetURL(
      "/downloads/dangerous/dangerous.swf"));

  content::DownloadTestObserverTerminal download_terminal_observer(
      GetDownloadManager(browser()),
      1u,  /* wait_count */
      content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE);

  CreateDownloadForBrowserAndURL(browser(), download_url);

  base::FilePath filename = download_item()->GetFileNameToReportUser();

  // Checks the download status.
  EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE,
            download_item()->GetDangerType());
  EXPECT_TRUE(download_item()->IsDangerous());

  // Opens the message center.
  GetMessageCenter()->SetVisibility(message_center::VISIBILITY_MESSAGE_CENTER);

  NotificationRemoveObserver notification_close_observer;
  NotificationAddObserver notification_add_observer;

  // Cicks the "keep" button.
  notification()->ButtonClick(1);  // 2nd button: "Keep"
  // Clicking makes the message center closed.
  GetMessageCenter()->SetVisibility(message_center::VISIBILITY_TRANSIENT);

  // Confirms that the notification is closed and re-shown.
  EXPECT_EQ(notification_id(), notification_close_observer.Wait());
  notification_add_observer.Wait();
  EXPECT_EQ(notification_id(), notification_add_observer.notification_id());
  EXPECT_EQ(1u, GetMessageCenter()->GetVisibleNotifications().size());

  // Checks the download status.
  EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED,
            download_item()->GetDangerType());
  EXPECT_FALSE(download_item()->IsDangerous());

  // Wait for the download completion.
  download_terminal_observer.WaitForFinished();

  // Checks the download status.
  EXPECT_FALSE(download_item()->IsDangerous());
  EXPECT_EQ(content::DownloadItem::COMPLETE, download_item()->GetState());

  // Checks the downloaded file.
  EXPECT_TRUE(base::PathExists(GetDownloadPath().Append(filename.BaseName())));
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest, DiscardDangerousFile) {
  GURL download_url(embedded_test_server()->GetURL(
      "/downloads/dangerous/dangerous.swf"));

  content::DownloadTestObserverTerminal download_terminal_observer(
      GetDownloadManager(browser()),
      1u,  /* wait_count */
      content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE);

  CreateDownloadForBrowserAndURL(browser(), download_url);

  base::FilePath filename = download_item()->GetFileNameToReportUser();

  // Checks the download status.
  EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE,
            download_item()->GetDangerType());
  EXPECT_TRUE(download_item()->IsDangerous());

  // Opens the message center.
  GetMessageCenter()->SetVisibility(message_center::VISIBILITY_MESSAGE_CENTER);

  NotificationRemoveObserver notification_close_observer;

  // Clicks the "Discard" button.
  notification()->ButtonClick(0);  // 1st button: "Discard"
  // Clicking makes the message center closed.
  GetMessageCenter()->SetVisibility(message_center::VISIBILITY_TRANSIENT);

  // Confirms that the notification is closed.
  EXPECT_EQ(notification_id(), notification_close_observer.Wait());

  // Wait for the download completion.
  download_terminal_observer.WaitForFinished();

  // Checks there is neither any download nor any notification.
  EXPECT_EQ(0u, GetMessageCenter()->GetVisibleNotifications().size());
  std::vector<content::DownloadItem*> downloads;
  GetDownloadManager(browser())->GetAllDownloads(&downloads);
  EXPECT_EQ(0u, downloads.size());

  // Checks the downloaded file doesn't exist.
  EXPECT_FALSE(base::PathExists(GetDownloadPath().Append(filename.BaseName())));
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest, DownloadImageFile) {
  GURL download_url(embedded_test_server()->GetURL(
      "/downloads/image-octet-stream.png"));

  content::DownloadTestObserverTerminal download_terminal_observer(
      GetDownloadManager(browser()), 1u, /* wait_count */
      content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE);

  CreateDownloadForBrowserAndURL(browser(), download_url);

  // Wait for the download completion.
  download_terminal_observer.WaitForFinished();

  // Waits for download completion.
  while (GetNotification(notification_id())->image().IsEmpty()) {
    NotificationUpdateObserver download_change_notification_observer;
    download_change_notification_observer.Wait();
  }
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest,
                       CloseNotificationAfterDownload) {
  CreateDownload();

  // Requests to complete the download.
  ui_test_utils::NavigateToURL(
      browser(), GURL(net::URLRequestSlowDownloadJob::kFinishDownloadUrl));

  // Waits for download completion.
  while (download_item()->GetState() != content::DownloadItem::COMPLETE) {
    NotificationUpdateObserver download_change_notification_observer;
    download_change_notification_observer.Wait();
  }

  // Opens the message center.
  GetMessageCenter()->SetVisibility(message_center::VISIBILITY_MESSAGE_CENTER);

  // Closes the notification.
  NotificationRemoveObserver notification_close_observer;
  GetMessageCenter()->RemoveNotification(notification_id(), true /* by_user */);
  EXPECT_EQ(notification_id(), notification_close_observer.Wait());

  EXPECT_EQ(0u, GetMessageCenter()->GetVisibleNotifications().size());

  // Confirms that a download is also started.
  std::vector<content::DownloadItem*> downloads;
  GetDownloadManager(browser())->GetAllDownloads(&downloads);
  EXPECT_EQ(1u, downloads.size());
  EXPECT_EQ(content::DownloadItem::COMPLETE, downloads[0]->GetState());
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest,
                       CloseNotificationWhileDownloading) {
  CreateDownload();

  // Closes the notification.
  NotificationRemoveObserver notification_close_observer;
  GetMessageCenter()->RemoveNotification(notification_id(), true /* by_user */);
  EXPECT_EQ(notification_id(), notification_close_observer.Wait());

  EXPECT_EQ(0u, GetMessageCenter()->GetVisibleNotifications().size());

  // Confirms that a download is still in progress.
  std::vector<content::DownloadItem*> downloads;
  content::DownloadManager* download_manager = GetDownloadManager(browser());
  download_manager->GetAllDownloads(&downloads);
  EXPECT_EQ(1u, downloads.size());
  EXPECT_EQ(content::DownloadItem::IN_PROGRESS, downloads[0]->GetState());

  // Installs observers before requesting the completion.
  NotificationAddObserver download_notification_add_observer;
  content::DownloadTestObserverTerminal download_terminal_observer(
      download_manager,
      1u, /* wait_count */
      content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);

  // Requests to complete the download and wait for it.
  ui_test_utils::NavigateToURL(
      browser(), GURL(net::URLRequestSlowDownloadJob::kFinishDownloadUrl));
  download_terminal_observer.WaitForFinished();

  // Waits that new notification.
  download_notification_add_observer.Wait();

  // Confirms that there is only one notification.
  message_center::NotificationList::Notifications
      visible_notifications = GetMessageCenter()->GetVisibleNotifications();
  EXPECT_EQ(1u, visible_notifications.size());
  EXPECT_TRUE(IsInNotifications(visible_notifications, notification_id()));
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest, InterruptDownload) {
  CreateDownload();

  // Installs observers before requesting.
  NotificationUpdateObserver download_notification_update_observer;
  content::DownloadTestObserverTerminal download_terminal_observer(
      GetDownloadManager(browser()),
      1u, /* wait_count */
      content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);

  // Requests to fail the download and wait for it.
  ui_test_utils::NavigateToURL(
      browser(), GURL(net::URLRequestSlowDownloadJob::kErrorDownloadUrl));
  download_terminal_observer.WaitForFinished();

  // Waits that new notification.
  download_notification_update_observer.Wait();

  // Confirms that there is only one notification.
  message_center::NotificationList::Notifications
      visible_notifications = GetMessageCenter()->GetVisibleNotifications();
  EXPECT_EQ(1u, visible_notifications.size());
  EXPECT_TRUE(IsInNotifications(visible_notifications, notification_id()));

  // Checks strings.
  EXPECT_EQ(l10n_util::GetStringFUTF16(
                IDS_DOWNLOAD_STATUS_DOWNLOAD_FAILED_TITLE,
                download_item()->GetFileNameToReportUser().LossyDisplayName()),
            GetNotification(notification_id())->title());
  EXPECT_EQ(l10n_util::GetStringFUTF16(
                IDS_DOWNLOAD_STATUS_INTERRUPTED,
                l10n_util::GetStringUTF16(
                    IDS_DOWNLOAD_INTERRUPTED_STATUS_NETWORK_ERROR)),
            GetNotification(notification_id())->message());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id())->type());
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest,
                       InterruptDownloadAfterClosingNotification) {
  CreateDownload();

  // Closes the notification.
  NotificationRemoveObserver notification_close_observer;
  GetMessageCenter()->RemoveNotification(notification_id(), true /* by_user */);
  EXPECT_EQ(notification_id(), notification_close_observer.Wait());

  EXPECT_EQ(0u, GetMessageCenter()->GetVisibleNotifications().size());

  // Confirms that a download is still in progress.
  std::vector<content::DownloadItem*> downloads;
  content::DownloadManager* download_manager = GetDownloadManager(browser());
  download_manager->GetAllDownloads(&downloads);
  EXPECT_EQ(1u, downloads.size());
  EXPECT_EQ(content::DownloadItem::IN_PROGRESS, downloads[0]->GetState());

  // Installs observers before requesting the completion.
  NotificationAddObserver download_notification_add_observer;
  content::DownloadTestObserverTerminal download_terminal_observer(
      download_manager,
      1u, /* wait_count */
      content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);

  // Requests to fail the download and wait for it.
  ui_test_utils::NavigateToURL(
      browser(), GURL(net::URLRequestSlowDownloadJob::kErrorDownloadUrl));
  download_terminal_observer.WaitForFinished();

  // Waits that new notification.
  download_notification_add_observer.Wait();

  // Confirms that there is only one notification.
  message_center::NotificationList::Notifications
      visible_notifications = GetMessageCenter()->GetVisibleNotifications();
  EXPECT_EQ(1u, visible_notifications.size());
  EXPECT_TRUE(IsInNotifications(visible_notifications, notification_id()));
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest, DownloadRemoved) {
  CreateDownload();

  NotificationRemoveObserver notification_close_observer;
  download_item()->Remove();
  EXPECT_EQ(notification_id(), notification_close_observer.Wait());

  // Confirms that the notification is removed.
  EXPECT_EQ(0u, GetMessageCenter()->GetVisibleNotifications().size());

  // Confirms that the download item is removed.
  std::vector<content::DownloadItem*> downloads;
  GetDownloadManager(browser())->GetAllDownloads(&downloads);
  EXPECT_EQ(0u, downloads.size());
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest, DownloadMultipleFiles) {
  GURL url1(net::URLRequestSlowDownloadJob::kUnknownSizeUrl);
  GURL url2(net::URLRequestSlowDownloadJob::kKnownSizeUrl);

  // Starts the 1st download.
  NotificationAddObserver download_start_notification_observer1;
  ui_test_utils::NavigateToURL(browser(), url1);
  EXPECT_TRUE(download_start_notification_observer1.Wait());
  std::string notification_id1 =
      download_start_notification_observer1.notification_id();
  EXPECT_FALSE(notification_id1.empty());

  // Confirms that there is a download.
  std::vector<content::DownloadItem*> downloads;
  GetDownloadManager(browser())->GetAllDownloads(&downloads);
  EXPECT_EQ(1u, downloads.size());
  content::DownloadItem* download1or2 = downloads[0];

  // Starts the 2nd download and waits for 2 notifications (normal and
  // grouped one).
  NotificationAddObserver download_start_notification_observer2(2);
  ui_test_utils::NavigateToURL(browser(), url2);
  EXPECT_TRUE(download_start_notification_observer2.Wait());

  // Confirms that there are 2 downloads.
  downloads.clear();
  GetDownloadManager(browser())->GetAllDownloads(&downloads);
  content::DownloadItem* download1 = downloads[0];
  content::DownloadItem* download2 = downloads[1];
  EXPECT_EQ(2u, downloads.size());
  EXPECT_NE(download1, download2);
  EXPECT_TRUE(download1 == download1or2 || download2 == download1or2);

  // Confirms that there is only one group notification.
  message_center::NotificationList::Notifications
      visible_notifications = GetMessageCenter()->GetVisibleNotifications();
  EXPECT_EQ(3u, visible_notifications.size());

  std::string notification_id2;
  std::string notification_id_group;
  for (auto notification : visible_notifications) {
    if (notification->id() == notification_id1) {
      continue;
    } else if (notification->type() ==
               message_center::NOTIFICATION_TYPE_PROGRESS) {
      notification_id2 = (notification->id());
    } else if (notification->type() ==
               message_center::NOTIFICATION_TYPE_MULTIPLE) {
      notification_id_group = (notification->id());
    }
  }
  EXPECT_TRUE(!notification_id2.empty());
  EXPECT_TRUE(!notification_id_group.empty());
  EXPECT_NE(notification_id2, notification_id_group);

  // Confirms the types of download notifications are correct.
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_MULTIPLE,
            GetNotification(notification_id_group)->type());
  EXPECT_EQ(2u, GetNotification(notification_id_group)->items().size());
  EXPECT_EQ(2u, GetNotification(notification_id_group)->items().size());

  // Requests to complete the downloads.
  ui_test_utils::NavigateToURL(
      browser(), GURL(net::URLRequestSlowDownloadJob::kFinishDownloadUrl));

  // Waits for the completion of downloads.
  while (download1->GetState() != content::DownloadItem::COMPLETE ||
         download2->GetState() != content::DownloadItem::COMPLETE) {
    NotificationUpdateObserver download_change_notification_observer;
    download_change_notification_observer.Wait();
  }

  visible_notifications = GetMessageCenter()->GetVisibleNotifications();
  EXPECT_EQ(3u, visible_notifications.size());
  EXPECT_TRUE(IsInNotifications(visible_notifications,
                                notification_id_group));
  EXPECT_TRUE(IsInNotifications(visible_notifications,
                                notification_id1));
  EXPECT_TRUE(IsInNotifications(visible_notifications,
                                notification_id2));

  // Confirms the types of download notifications are correct.
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id1)->type());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id2)->type());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_MULTIPLE,
            GetNotification(notification_id_group)->type());
  EXPECT_EQ(2u, GetNotification(notification_id_group)->items().size());
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest, CancelDownload) {
  CreateDownload();

  // Opens the message center.
  GetMessageCenter()->SetVisibility(message_center::VISIBILITY_MESSAGE_CENTER);

  // Cancels the notification by clicking the "cancel' button.
  NotificationRemoveObserver notification_close_observer;
  notification()->ButtonClick(1);
  EXPECT_EQ(notification_id(), notification_close_observer.Wait());
  EXPECT_EQ(0u, GetMessageCenter()->GetVisibleNotifications().size());

  // Confirms that a download is also cancelled.
  std::vector<content::DownloadItem*> downloads;
  GetDownloadManager(browser())->GetAllDownloads(&downloads);
  EXPECT_EQ(1u, downloads.size());
  EXPECT_EQ(content::DownloadItem::CANCELLED, downloads[0]->GetState());
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest,
                       DownloadCancelledByUserExternally) {
  CreateDownload();

  // Cancels the notification by clicking the "cancel' button.
  NotificationRemoveObserver notification_close_observer;
  download_item()->Cancel(true /* by_user */);
  EXPECT_EQ(notification_id(), notification_close_observer.Wait());
  EXPECT_EQ(0u, GetMessageCenter()->GetVisibleNotifications().size());

  // Confirms that a download is also cancelled.
  std::vector<content::DownloadItem*> downloads;
  GetDownloadManager(browser())->GetAllDownloads(&downloads);
  EXPECT_EQ(1u, downloads.size());
  EXPECT_EQ(content::DownloadItem::CANCELLED, downloads[0]->GetState());
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest,
                       DownloadCancelledExternally) {
  CreateDownload();

  // Cancels the notification by clicking the "cancel' button.
  NotificationRemoveObserver notification_close_observer;
  download_item()->Cancel(false /* by_user */);
  EXPECT_EQ(notification_id(), notification_close_observer.Wait());
  EXPECT_EQ(0u, GetMessageCenter()->GetVisibleNotifications().size());

  // Confirms that a download is also cancelled.
  std::vector<content::DownloadItem*> downloads;
  GetDownloadManager(browser())->GetAllDownloads(&downloads);
  EXPECT_EQ(1u, downloads.size());
  EXPECT_EQ(content::DownloadItem::CANCELLED, downloads[0]->GetState());
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest, IncognitoDownloadFile) {
  PrepareIncognitoBrowser();

  // Starts an incognito download.
  CreateDownloadForBrowserAndURL(
      incognito_browser(),
      GURL(net::URLRequestSlowDownloadJob::kKnownSizeUrl));

  EXPECT_EQ(l10n_util::GetStringFUTF16(
                IDS_DOWNLOAD_STATUS_IN_PROGRESS_TITLE,
                download_item()->GetFileNameToReportUser().LossyDisplayName()),
            GetNotification(notification_id())->title());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_PROGRESS,
            GetNotification(notification_id())->type());
  EXPECT_TRUE(download_item()->GetBrowserContext()->IsOffTheRecord());

  // Requests to complete the download.
  ui_test_utils::NavigateToURL(
      incognito_browser(),
      GURL(net::URLRequestSlowDownloadJob::kFinishDownloadUrl));

  // Waits for download completion.
  while (download_item()->GetState() != content::DownloadItem::COMPLETE) {
    NotificationUpdateObserver download_change_notification_observer;
    download_change_notification_observer.Wait();
  }

  EXPECT_EQ(l10n_util::GetStringFUTF16(
                IDS_DOWNLOAD_STATUS_DOWNLOADED_TITLE,
                download_item()->GetFileNameToReportUser().LossyDisplayName()),
            GetNotification(notification_id())->title());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id())->type());

  // Opens the message center.
  GetMessageCenter()->SetVisibility(message_center::VISIBILITY_MESSAGE_CENTER);

  // Try to open the downloaded item by clicking the notification.
  EXPECT_FALSE(GetIncognitoDownloadManagerDelegate()->opened());
  GetMessageCenter()->ClickOnNotification(notification_id());
  EXPECT_TRUE(GetIncognitoDownloadManagerDelegate()->opened());
  EXPECT_FALSE(GetDownloadManagerDelegate()->opened());

  EXPECT_FALSE(GetNotification(notification_id()));
  chrome::CloseWindow(incognito_browser());
}

IN_PROC_BROWSER_TEST_F(DownloadNotificationTest,
                       SimultaneousIncognitoAndNormalDownloads) {
  PrepareIncognitoBrowser();

  GURL url_incognito(net::URLRequestSlowDownloadJob::kUnknownSizeUrl);
  GURL url_normal(net::URLRequestSlowDownloadJob::kKnownSizeUrl);

  // Starts the incognito download.
  NotificationAddObserver download_start_notification_observer1;
  ui_test_utils::NavigateToURL(incognito_browser(), url_incognito);
  EXPECT_TRUE(download_start_notification_observer1.Wait());
  std::string notification_id1 =
      download_start_notification_observer1.notification_id();
  EXPECT_FALSE(notification_id1.empty());

  // Confirms that there is a download.
  std::vector<content::DownloadItem*> downloads;
  GetDownloadManager(browser())->GetAllDownloads(&downloads);
  EXPECT_EQ(0u, downloads.size());
  downloads.clear();
  GetDownloadManager(incognito_browser())->GetAllDownloads(&downloads);
  EXPECT_EQ(1u, downloads.size());
  content::DownloadItem* download_incognito = downloads[0];

  // Starts the normal download.
  NotificationAddObserver download_start_notification_observer2;
  ui_test_utils::NavigateToURL(browser(), url_normal);
  EXPECT_TRUE(download_start_notification_observer2.Wait());
  std::string notification_id2 =
      download_start_notification_observer2.notification_id();
  EXPECT_FALSE(notification_id2.empty());

  // Confirms that there are 2 downloads.
  downloads.clear();
  GetDownloadManager(browser())->GetAllDownloads(&downloads);
  content::DownloadItem* download_normal = downloads[0];
  EXPECT_EQ(1u, downloads.size());
  EXPECT_NE(download_normal, download_incognito);
  downloads.clear();
  GetDownloadManager(incognito_browser())->GetAllDownloads(&downloads);
  EXPECT_EQ(1u, downloads.size());
  EXPECT_EQ(download_incognito, downloads[0]);

  // Confirms the types of download notifications are correct.
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_PROGRESS,
            GetNotification(notification_id1)->type());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_PROGRESS,
            GetNotification(notification_id2)->type());

  EXPECT_TRUE(download_incognito->GetBrowserContext()->IsOffTheRecord());
  EXPECT_FALSE(download_normal->GetBrowserContext()->IsOffTheRecord());

  // Requests to complete the downloads.
  ui_test_utils::NavigateToURL(
      browser(), GURL(net::URLRequestSlowDownloadJob::kFinishDownloadUrl));

  // Waits for the completion of downloads.
  while (download_normal->GetState() != content::DownloadItem::COMPLETE ||
         download_incognito->GetState() != content::DownloadItem::COMPLETE) {
    NotificationUpdateObserver download_change_notification_observer;
    download_change_notification_observer.Wait();
  }

  // Confirms the types of download notifications are correct.
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id1)->type());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id2)->type());

  chrome::CloseWindow(incognito_browser());
}

//////////////////////////////////////////////////
// Test with multi profiles
//////////////////////////////////////////////////

class MultiProfileDownloadNotificationTest
    : public DownloadNotificationTestBase {
 public:
  ~MultiProfileDownloadNotificationTest() override {}

  void SetUpCommandLine(base::CommandLine* command_line) override {
    DownloadNotificationTestBase::SetUpCommandLine(command_line);

    // Logs in to a dummy profile.
    command_line->AppendSwitchASCII(chromeos::switches::kLoginUser,
                                    kTestAccounts[DUMMY_ACCOUNT_INDEX].email);
    command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile,
                                    kTestAccounts[DUMMY_ACCOUNT_INDEX].hash);
  }

  // Logs in to the primary profile.
  void SetUpOnMainThread() override {
    const TestAccountInfo& info = kTestAccounts[PRIMARY_ACCOUNT_INDEX];

    AddUser(info, true);
    DownloadNotificationTestBase::SetUpOnMainThread();
  }

  // Loads all users to the current session and sets up necessary fields.
  // This is used for preparing all accounts in PRE_ test setup, and for testing
  // actual login behavior.
  void AddAllUsers() {
    for (size_t i = 0; i < arraysize(kTestAccounts); ++i)
      AddUser(kTestAccounts[i], i >= SECONDARY_ACCOUNT_INDEX_START);
  }

  Profile* GetProfileByIndex(int index) {
    return chromeos::ProfileHelper::GetProfileByUserIdHash(
        kTestAccounts[index].hash);
  }

  // Adds a new user for testing to the current session.
  void AddUser(const TestAccountInfo& info, bool log_in) {
    user_manager::UserManager* const user_manager =
        user_manager::UserManager::Get();
    if (log_in)
      user_manager->UserLoggedIn(info.email, info.hash, false);
    user_manager->SaveUserDisplayName(info.email,
                                      base::UTF8ToUTF16(info.display_name));
    SigninManagerFactory::GetForProfile(
        chromeos::ProfileHelper::GetProfileByUserIdHash(info.hash))
            ->SetAuthenticatedAccountInfo(info.gaia_id, info.email);
  }
};

IN_PROC_BROWSER_TEST_F(MultiProfileDownloadNotificationTest,
                       PRE_DownloadMultipleFiles) {
  AddAllUsers();
}

IN_PROC_BROWSER_TEST_F(MultiProfileDownloadNotificationTest,
                       DownloadMultipleFiles) {
  AddAllUsers();

  GURL url(net::URLRequestSlowDownloadJob::kUnknownSizeUrl);

  Profile* profile1 = GetProfileByIndex(1);
  Profile* profile2 = GetProfileByIndex(2);
  Browser* browser1 = CreateBrowser(profile1);
  Browser* browser2 = CreateBrowser(profile2);
  EXPECT_NE(browser1, browser2);

  // First user starts a download.
  NotificationAddObserver download_start_notification_observer1;
  ui_test_utils::NavigateToURL(browser1, url);
  download_start_notification_observer1.Wait();

  // Confirms that the download is started.
  std::vector<content::DownloadItem*> downloads;
  GetDownloadManager(browser1)->GetAllDownloads(&downloads);
  EXPECT_EQ(1u, downloads.size());
  content::DownloadItem* download1 = downloads[0];

  // Confirms that a download notification is generated.
  std::string notification_id_user1 =
      download_start_notification_observer1.notification_id();
  EXPECT_FALSE(notification_id_user1.empty());

  // Second user starts a download.
  NotificationAddObserver download_start_notification_observer2;
  ui_test_utils::NavigateToURL(browser2, url);
  download_start_notification_observer2.Wait();
  std::string notification_id_user2_1 =
      download_start_notification_observer2.notification_id();
  EXPECT_FALSE(notification_id_user2_1.empty());

  // Confirms that the second user has only 1 download.
  downloads.clear();
  GetDownloadManager(browser2)->GetAllDownloads(&downloads);
  ASSERT_EQ(1u, downloads.size());

  // Second user starts another download.
  NotificationAddObserver download_start_notification_observer3(2);
  ui_test_utils::NavigateToURL(browser2, url);
  download_start_notification_observer3.Wait();
  std::string notification_id_user2_2;
  std::string notification_id_user2_group;
  {
    auto added_notification_ids =
        download_start_notification_observer3.notification_ids();
    EXPECT_EQ(2u, added_notification_ids.size());
    for (auto notification_id : added_notification_ids) {
      if (GetNotification(notification_id)->type() ==
              message_center::NOTIFICATION_TYPE_MULTIPLE) {
        notification_id_user2_group = notification_id;
      } else {
        notification_id_user2_2 = notification_id;
      }
    }
  }
  EXPECT_FALSE(notification_id_user2_2.empty());
  EXPECT_FALSE(notification_id_user2_group.empty());

  // Confirms that the second user has 2 downloads.
  downloads.clear();
  GetDownloadManager(browser2)->GetAllDownloads(&downloads);
  ASSERT_EQ(2u, downloads.size());
  content::DownloadItem* download2 = downloads[0];
  content::DownloadItem* download3 = downloads[1];
  EXPECT_NE(download1, download2);
  EXPECT_NE(download1, download3);
  EXPECT_NE(download2, download3);

  // Confirms that the first user still has only 1 download.
  downloads.clear();
  GetDownloadManager(browser1)->GetAllDownloads(&downloads);
  ASSERT_EQ(1u, downloads.size());
  EXPECT_EQ(download1, downloads[0]);

  // Confirms the types of download notifications are correct.
  // Normal notification for user1.
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_PROGRESS,
            GetNotification(notification_id_user1)->type());
  // Group notification for user2.
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_MULTIPLE,
            GetNotification(notification_id_user2_group)->type());
  EXPECT_EQ(2u,
            GetNotification(notification_id_user2_group)->items().size());
  // Normal notification for user2.
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_PROGRESS,
            GetNotification(notification_id_user2_1)->type());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_PROGRESS,
            GetNotification(notification_id_user2_2)->type());

  // Requests to complete the downloads.
  ui_test_utils::NavigateToURL(
      browser(), GURL(net::URLRequestSlowDownloadJob::kFinishDownloadUrl));

  // Waits for the completion of downloads.
  while (download1->GetState() != content::DownloadItem::COMPLETE ||
         download2->GetState() != content::DownloadItem::COMPLETE ||
         download3->GetState() != content::DownloadItem::COMPLETE) {
    NotificationUpdateObserver download_change_notification_observer;
    download_change_notification_observer.Wait();
  }

  // Confirms the types of download notifications are correct.
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id_user1)->type());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id_user2_1)->type());
  // There is still a group notification.
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_MULTIPLE,
            GetNotification(notification_id_user2_group)->type());
  EXPECT_EQ(2u,
            GetNotification(notification_id_user2_group)->items().size());
  // Normal notifications for user2.
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id_user2_1)->type());
  EXPECT_EQ(message_center::NOTIFICATION_TYPE_BASE_FORMAT,
            GetNotification(notification_id_user2_2)->type());
}


text:
<?php
namespace TYPO3\CMS\Extbase\Mvc\Exception;

/**
 * An "Invalid URI Pattern" exception
 */
class InvalidUriPatternException extends \TYPO3\CMS\Extbase\Mvc\Exception
{
}