text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
T-Index
</TITLE>

<META NAME="date" CONTENT="2012-07-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

B C D F G I O P R S T U

T

TlvProperties - Class in com.acs.smartcard
This class represents TLV properties in PC/SC 2.0 Part 10.
TlvProperties() -
Constructor for class com.acs.smartcard.TlvProperties

Creates an instance of TlvProperties.

TlvProperties(byte[], int) -
Constructor for class com.acs.smartcard.TlvProperties

Creates and initializes an instance of TlvProperties from the byte array.

toByteArray() -
Method in class com.acs.smartcard.PinModify

Converts the PinModify to the byte array.

toByteArray() -
Method in class com.acs.smartcard.PinVerify

Converts the PinVerify to the byte array.

toByteArray() -
Method in class com.acs.smartcard.ReadKeyOption

Converts the ReadKeyOption to the byte array.

transmit(int, byte[], int, byte[], int) -
Method in class com.acs.smartcard.Reader

Transmits the APDU.

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

B C D F G I O P R S T U

Copyright © 2011-2012 Advanced Card Systems Ltd. All Rights Reserved.


text:
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//     * Neither the name of Rodrigo B. de Oliveira nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion

using System.Collections.Generic;

namespace Boo.Lang.Compiler.Ast
{
	using System;
	using System.Xml.Serialization;

	public delegate bool NodePredicate(Node node);

	public interface ITypedAnnotations
	{
		T Get<T>() where T : class;
		void Set<T>(T annotation) where T : class;
	}

	///
	/// Base class for every node in the AST.
	///
	[Serializable]
	public abstract class Node : ICloneable, ITypedAnnotations
	{
		public static bool Matches<T>(T lhs, T rhs) where T : Node
		{
			return lhs == null ? rhs == null : lhs.Matches(rhs);
		}

		public static bool Matches(Block lhs, Block rhs)
		{
			return lhs == null ? rhs == null || rhs.IsEmpty : lhs.Matches(rhs);
		}

		public static bool AllMatch<T>(IEnumerable<T> lhs, IEnumerable<T> rhs) where T : Node
		{
			if (lhs == null) return rhs == null || IsEmpty(rhs);
			if (rhs == null) return IsEmpty(lhs);

			IEnumerator<T> r = rhs.GetEnumerator();
			foreach (T item in lhs)
			{
				if (!r.MoveNext()) return false;
				if (!Matches(item, r.Current)) return false;
			}
			if (r.MoveNext()) return false;
			return true;
		}

		private static bool IsEmpty<T>(IEnumerable<T> e)
		{
			return !e.GetEnumerator().MoveNext();
		}

		protected LexicalInfo _lexicalInfo = LexicalInfo.Empty;

		protected SourceLocation _endSourceLocation = LexicalInfo.Empty;

		protected Node _parent;

		protected string _documentation;

		protected System.Collections.Hashtable _annotations;

		protected Boo.Lang.Compiler.TypeSystem.IEntity _entity;

		protected bool _isSynthetic;

		protected Node()
		{
			_lexicalInfo = LexicalInfo.Empty;
		}

		protected Node(LexicalInfo lexicalInfo)
		{
			if (null == lexicalInfo)
				throw new ArgumentNullException("lexicalInfo");
			_lexicalInfo = lexicalInfo;
		}

		protected void InitializeFrom(Node other)
		{
			_lexicalInfo = other.LexicalInfo;
			_isSynthetic = other.IsSynthetic;
		}

		public Node CloneNode()
		{
			return (Node)Clone();
		}

		///
		/// true when the node was constructed by the compiler.
		///
		[XmlAttribute]
		[System.ComponentModel.DefaultValue(false)]
		public bool IsSynthetic
		{
			get { return _isSynthetic; }

			set { _isSynthetic = value; }
		}

		[XmlIgnore]
		public TypeSystem.IEntity Entity
		{
			get { return _entity; }

			set { _entity = value; }
		}

		public object this[object key]
		{
			get
			{
				if (_annotations == null) return null;
				return _annotations[key];
			}

			set
			{
				if (_annotations == null) _annotations = new System.Collections.Hashtable();
				_annotations[key] = value;
			}
		}

		///
		/// Strongly typed annotation mechanism.
		///
		/// <example>
		/// generatorSkeleton = generator.Tags.Get[of GeneratorSkeleton]()
		/// </example>
		///
		public ITypedAnnotations Tags
		{
			get { return this; }
		}

		T ITypedAnnotations.Get<T>()
		{
			return (T) this[typeof(T).TypeHandle];
		}

		void ITypedAnnotations.Set<T>(T annotation)
		{
			Annotate(typeof(T).TypeHandle, annotation);
		}

		public bool HasAnnotations
		{
			get { return _annotations != null && _annotations.Count > 0; }
		}

		public void Annotate(object key)
		{
			Annotate(key, key);
		}

		public void Annotate(object key, object value)
		{
			if (_annotations == null) _annotations = new System.Collections.Hashtable();
			_annotations.Add(key, value);
		}

		public bool ContainsAnnotation(object key)
		{
			if (_annotations == null) return false;
			return _annotations.ContainsKey(key);
		}

		public void RemoveAnnotation(object key)
		{
			if (_annotations == null) return;
			_annotations.Remove(key);
		}

		internal virtual void ClearTypeSystemBindings()
		{
			_annotations = null;
			_entity = null;
		}

		public Node ParentNode
		{
			get { return _parent; }
		}

		public string Documentation
		{
			get { return _documentation; }

			set { _documentation = value; }
		}

		///
		/// Where this element appears in the source file.
		///
		[XmlIgnore]
		public LexicalInfo LexicalInfo
		{
			get
			{
				if (_lexicalInfo.Equals(LexicalInfo.Empty) && null != ParentNode && null != ParentNode.LexicalInfo)
					_lexicalInfo = ParentNode.LexicalInfo;
				return _lexicalInfo;
			}

			set
			{
				if (null == value)
					throw new ArgumentNullException("LexicalInfo");
				_lexicalInfo = value;
			}
		}

		///
		/// Where this element ends in the source file.
		/// This information is generally available and/or accurate
		/// only for blocks and member definitions.
		///
		[XmlIgnore]
		public virtual SourceLocation EndSourceLocation
		{
			get { return _endSourceLocation; }

			set
			{
				if (null == value)
					throw new ArgumentNullException("EndSourceLocation");
				_endSourceLocation = value;
			}
		}

		public virtual bool Replace(Node existing, Node newNode)
		{
			if (null == existing)
				throw new ArgumentNullException("existing");
			return false;
		}

		private sealed class ReplaceVisitor : DepthFirstTransformer
		{
			readonly NodePredicate _predicate;
			readonly Node _template;

			public ReplaceVisitor(NodePredicate predicate, Node template)
			{
				_predicate = predicate;
				_template = template;
			}

			public int MatchCount { get; private set; }

			override protected void OnNode(Node node)
			{
				if (_predicate(node))
				{
					++MatchCount;
					ReplaceCurrentNode(_template.CloneNode());
				}
				else
				{
					base.OnNode(node);
				}
			}
		}

		///
		/// Replaces all occurrences of the pattern pattern anywhere in the tree
		/// with a clone of template.
		///
		/// <returns>the number of nodes replaced</returns>
		public int ReplaceNodes(Node pattern, Node template)
		{
			var predicate = new NodePredicate(pattern.Matches);
			return ReplaceNodes(predicate, template);
		}

		///
		/// Replaces all node for which predicate returns true anywhere in the tree
		/// with a clone of template.
		///
		/// <returns>the number of nodes replaced</returns>
		public int ReplaceNodes(NodePredicate predicate, Node template)
		{
			var visitor = new ReplaceVisitor(predicate, template);
			Accept(visitor);
			return visitor.MatchCount;
		}

		internal void InitializeParent(Node parent)
		{
			_parent = parent;
		}

		public abstract void Accept(IAstVisitor visitor);

		public abstract object Clone();

		///
		/// Returns a Clone of the this node with any
		/// annotations removed (including type system bindings).
		///
		public Node CleanClone()
		{
			var clone = (Node)Clone();
			clone.ClearTypeSystemBindings();
			return clone;
		}

		public abstract bool Matches(Node other);

		protected bool NoMatch(string fieldName)
		{
			//helps debugging Node.Matches logic
			//Console.Error.WriteLine("No match for '{0}'.", fieldName);
			return false;
		}

		public abstract NodeType NodeType
		{
			get;
		}

		override public string ToString()
		{
			return ToCodeString();
		}

		public string ToCodeString()
		{
			var writer = new System.IO.StringWriter();
			Accept(new Visitors.BooPrinterVisitor(writer));
			return writer.ToString();
		}

		///
		///Returns the closest ancestor node of type <paramref name="ancestorType"/>
		///or null if no ancestor of requested type has been found.
		///
		///<param name="ancestorType">The type of node you request.</param>
		public Node GetAncestor(NodeType ancestorType)
		{
			return GetAncestor(ancestorType, int.MaxValue);
		}

		///
		///Returns the closest ancestor node of type <paramref name="ancestorType"/>
		///within <paramref name="limitDepth"/> or null if no ancestor of requested
		///type has been found.
		///
		///<param name="ancestorType">The type of node you request.</param>
		///<param name="limitDepth">Maximum depth difference from this node to ancestor.</param>
		public Node GetAncestor(NodeType ancestorType, int limitDepth)
		{
			Node parent = this.ParentNode;
			while (null != parent && limitDepth > 0)
			{
				if (ancestorType == parent.NodeType)
					return parent;
				parent = parent.ParentNode;
				limitDepth--;
			}
			return null;
		}

		///
		///Returns the closest ancestor node of type <paramref name="TAncestor"/>
		///or null if no ancestor of requested type has been found.
		///
		///<param name="TAncestor">The type of node you request.</param>
		public TAncestor GetAncestor<TAncestor>() where TAncestor : Node
		{
			var parent = ParentNode;
			while (parent != null)
			{
				var ancestor = parent as TAncestor;
				if (null != ancestor)
					return ancestor;
				parent = parent.ParentNode;
			}
			return null;
		}

		///
		///Returns the farthest ancestor node of type <paramref name="TAncestor"/>
		///or null if no ancestor of requested type has been found.
		///
		///<param name="TAncestor">The type of node you request.</param>
		public TAncestor GetRootAncestor<TAncestor>() where TAncestor : Node
		{
			TAncestor root = null;
			foreach (TAncestor ancestor in GetAncestors<TAncestor>())
				root = ancestor;
			return root;
		}

		///
		///Yields <paramref name="TAncestor"/> ancestors in order from closest to farthest from this node.
		///
		///<param name="TAncestor">The type of node you request.</param>
		public IEnumerable<TAncestor> GetAncestors<TAncestor>() where TAncestor : Node
		{
			var parent = ParentNode;
			while (parent != null)
			{
				var ancestor = parent as TAncestor;
				if (ancestor != null)
					yield return ancestor;
				parent = parent.ParentNode;
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
Simple desktop application for notification about new messages on [http://diary.ru](http://diary.ru) - Russian blog service.

## Motivation

I want a faster notification application for Windows. And want to recall my C# skills.

## Skills:
-  JSON parsing (deserialization)
-  WebRequest
-  Work with cookies and serialization (and deserialization)
-  Encoding request content in windows-1251
-  async await (also how it safe using in constructor of Window class)
-  Resources (for icons)
-  WPF (styles, ComboBox)
-  Simple storing user settings with ApplicationSettingsBase class (but it do my application some slow while starting)

## Uses
-  Visual Studio 2012
-  .NET 4.0


text:
require 'chatterbox'
require 'chatterbox/services/email/mailer'

module Chatterbox::Services
  class Email
    attr_reader :options
    # Return default configuration - defaults to empty hash
    def self.default_configuration
      @default_configuration ||= {}
    end

    # Configure Email service with default options
    def self.configure(config_options)
      @default_configuration = config_options.with_indifferent_access
    end

    # Deliver the a notification via email
    #
    # ==== Options
    #
    # * :summary - The subject of the message - required.
    # * :body - The body of the email - if none provided, you will just send an email with a blank body.
    # * :config - A sub-hash of configuration options.
    #   Optional if you have configured a default configuration with #configure.
    #   Config can contain any of the following options, all of which are pretty self explanatory:
    #
    #     :to
    #     :from
    #     :content_type
    #     :reply_to
    #     :bcc
    #     :cc
    def self.deliver(options = {})
      new(options).deliver
    end

    # Creates a new Email service with provided options.
    # See Email::deliver for the valid options
    def initialize(options = {})
      @options = options
      merge_configs
      merge_message
      validate_options
    end

    # Deliver a notificaiton -- normally you should just use the class level method Email::deliver
    def deliver
      Mailer.deliver_message(options)
    end

    private

    def merge_message
      if @options[:message]
        @options.merge!(@options[:message])
      end
    end

    def merge_configs
      @options[:config] ||= {}
      @options[:config] = self.class.default_configuration.merge(options[:config])
    end

    def validate_options
      require_summary

      require_config
      require_config_keys(:to, :from)
    end

    def require_config
      raise(ArgumentError, "Must configure with a :config or set default_configuration") unless options.key?(:config)
    end

    def require_config_keys(*keys)
      Array(keys).each do |key|
        raise(ArgumentError, "Must provide #{key.inspect} in the :config - you provided:\n#{options.inspect}") unless options[:config].key?(key)
      end
    end

    def require_summary
      raise(ArgumentError, "Must provide a :summary for your message - you provided:\n#{options.inspect}") unless options.key?(:summary)
    end
  end
end


text:
#include "stdafx.h"

#define new DEBUG_NEW

/////////////////////////////////////////////////////////////////////////////
// COleDataObject constructors

COleDataObject::COleDataObject()
{
	m_lpEnumerator = NULL;
	m_lpDataObject = NULL;
	m_bAutoRelease = TRUE;
	m_bClipboard = FALSE;
}

void COleDataObject::Attach(LPDATAOBJECT lpDataObject, BOOL bAutoRelease)
{
	ASSERT(lpDataObject != NULL);

	Release();  // detach previous
	m_lpDataObject = lpDataObject;
	m_bAutoRelease = bAutoRelease;
}

void COleDataObject::Release()
{
	RELEASE(m_lpEnumerator);

	if (m_lpDataObject != NULL)
	{
		if (m_bAutoRelease)
			m_lpDataObject->Release();
		m_lpDataObject = NULL;
	}
	m_bClipboard = FALSE;
}

LPDATAOBJECT COleDataObject::Detach()
{
	EnsureClipboardObject();

	LPDATAOBJECT lpDataObject = m_lpDataObject;
	m_lpDataObject = NULL;  // detach without Release
	m_bClipboard = FALSE;

	return lpDataObject;
}

LPDATAOBJECT COleDataObject::GetIDataObject(BOOL bAddRef)
{
	EnsureClipboardObject();

	LPDATAOBJECT lpDataObject = m_lpDataObject;
	if (bAddRef && lpDataObject != NULL)
		lpDataObject->AddRef();

	return lpDataObject;
}

/////////////////////////////////////////////////////////////////////////////
// COleDataObject attributes

void COleDataObject::BeginEnumFormats()
{
	EnsureClipboardObject();
	ASSERT(m_bClipboard || m_lpDataObject != NULL);

	// release old enumerator
	RELEASE(m_lpEnumerator);
	if (m_lpDataObject == NULL)
		return;

	// get the new enumerator
	SCODE sc = m_lpDataObject->EnumFormatEtc(DATADIR_GET, &m_lpEnumerator);
	ASSERT(sc != S_OK || m_lpEnumerator != NULL);
}

BOOL COleDataObject::GetNextFormat(LPFORMATETC lpFormatEtc)
{
	ASSERT(m_bClipboard || m_lpDataObject != NULL);
	ASSERT(AfxIsValidAddress(lpFormatEtc, sizeof(FORMATETC), FALSE));

	// return FALSE if enumerator is already NULL
	if (m_lpEnumerator == NULL)
		return FALSE;

	// attempt to retrieve the next format with the enumerator
	SCODE sc = m_lpEnumerator->Next(1, lpFormatEtc, NULL);

	// if enumerator fails, stop the enumeration
	if (sc != S_OK)
	{
		RELEASE(m_lpEnumerator);
		return FALSE;   // enumeration has ended
	}
	// otherwise, continue
	return TRUE;
}

CFile* COleDataObject::GetFileData(CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtc)
{
	EnsureClipboardObject();
	ASSERT(m_bClipboard || m_lpDataObject != NULL);
	if (m_lpDataObject == NULL)
		return NULL;

	ASSERT(lpFormatEtc == NULL ||
		AfxIsValidAddress(lpFormatEtc, sizeof(FORMATETC), FALSE));

	// fill in FORMATETC struct
	FORMATETC formatEtc;
	lpFormatEtc = _AfxFillFormatEtc(lpFormatEtc, cfFormat, &formatEtc);
	formatEtc.tymed = TYMED_FILE|TYMED_MFPICT|TYMED_HGLOBAL|TYMED_ISTREAM;

	// attempt to get the data
	STGMEDIUM stgMedium;
	SCODE sc = m_lpDataObject->GetData(lpFormatEtc, &stgMedium);
	if (FAILED(sc))
		return FALSE;

	// STGMEDIUMs with pUnkForRelease need to be copied first
	if (stgMedium.pUnkForRelease != NULL)
	{
		STGMEDIUM stgMediumDest;
		stgMediumDest.tymed = TYMED_NULL;
		stgMediumDest.pUnkForRelease = NULL;
		if (lpFormatEtc==NULL || !_AfxCopyStgMedium(lpFormatEtc->cfFormat, &stgMediumDest, &stgMedium))
		{
			::ReleaseStgMedium(&stgMedium);
			return FALSE;
		}
		// release original and replace with new
		::ReleaseStgMedium(&stgMedium);
		stgMedium = stgMediumDest;
	}

	// convert it to a file, depending on data
	CString strFileName;
	CFile* pFile = NULL;
	TRY
	{
		switch (stgMedium.tymed)
		{
		case TYMED_FILE:
			strFileName = stgMedium.lpszFileName;
			pFile = new CFile;
			if (!pFile->Open(strFileName,
				CFile::modeReadWrite|CFile::shareExclusive))
			{
				delete pFile;
				pFile = NULL;
				break;
			}
			// caller is responsible for deleting the actual file,
			//  but we free the file name.
			CoTaskMemFree(stgMedium.lpszFileName);
			break;

		case TYMED_MFPICT:
		case TYMED_HGLOBAL:
			pFile = new CSharedFile;
			((CSharedFile*)pFile)->SetHandle(stgMedium.hGlobal);
			break;

		case TYMED_ISTREAM:
			pFile = new COleStreamFile(stgMedium.pstm);
			break;

		default:
			// type not supported, so return error
			::ReleaseStgMedium(&stgMedium);
			break;
		}
	}
	CATCH_ALL(e)
	{
		delete pFile;
		pFile = NULL;
		DELETE_EXCEPTION(e);
	}
	END_CATCH_ALL

	// store newly created CFile* and return
	return pFile;
}

HGLOBAL COleDataObject::GetGlobalData(CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtc)
{
	EnsureClipboardObject();
	ASSERT(m_bClipboard || m_lpDataObject != NULL);
	if (m_lpDataObject == NULL)
		return NULL;

	ASSERT(lpFormatEtc == NULL ||
		AfxIsValidAddress(lpFormatEtc, sizeof(FORMATETC), FALSE));

	// fill in FORMATETC struct
	FORMATETC formatEtc;
	BOOL bFillFormatEtc = (lpFormatEtc == NULL);
	lpFormatEtc = _AfxFillFormatEtc(lpFormatEtc, cfFormat, &formatEtc);
	if (bFillFormatEtc)
	{
		lpFormatEtc->tymed = TYMED_HGLOBAL|TYMED_MFPICT;
	}
	ASSERT((lpFormatEtc->tymed & (TYMED_HGLOBAL|TYMED_MFPICT)) != 0);

	// attempt to get the data
	STGMEDIUM stgMedium;
	SCODE sc = m_lpDataObject->GetData(lpFormatEtc, &stgMedium);
	if (FAILED(sc))
		return FALSE;

	// handle just hGlobal types
	switch (stgMedium.tymed)
	{
	case TYMED_MFPICT:
	case TYMED_HGLOBAL:
		if (stgMedium.pUnkForRelease == NULL)
			return stgMedium.hGlobal;

		STGMEDIUM stgMediumDest;
		stgMediumDest.tymed = TYMED_NULL;
		stgMediumDest.pUnkForRelease = NULL;
		if (!_AfxCopyStgMedium(lpFormatEtc->cfFormat, &stgMediumDest, &stgMedium))
		{
			::ReleaseStgMedium(&stgMedium);
			return NULL;
		}
		::ReleaseStgMedium(&stgMedium);
		return stgMediumDest.hGlobal;

	// default -- falls through to error condition...
	}

	::ReleaseStgMedium(&stgMedium);
	return NULL;
}

BOOL COleDataObject::GetData(CLIPFORMAT cfFormat, LPSTGMEDIUM lpStgMedium,
	LPFORMATETC lpFormatEtc)
{
	EnsureClipboardObject();
	ASSERT(m_bClipboard || m_lpDataObject != NULL);
	if (m_lpDataObject == NULL)
		return FALSE;

	ASSERT(AfxIsValidAddress(lpStgMedium, sizeof(STGMEDIUM), FALSE));

	// fill in FORMATETC struct
	FORMATETC formatEtc;
	lpFormatEtc = _AfxFillFormatEtc(lpFormatEtc, cfFormat, &formatEtc);

	// attempt to get the data
	SCODE sc = m_lpDataObject->GetData(lpFormatEtc, lpStgMedium);
	if (FAILED(sc))
		return FALSE;

	return TRUE;
}

BOOL COleDataObject::IsDataAvailable(CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtc)
{
	if (m_bClipboard)
	{
		// it is faster and more reliable to ask the real Win32 clipboard
		//  instead of the OLE clipboard.
		return ::IsClipboardFormatAvailable(cfFormat);
	}
	else
	{
		ASSERT(m_lpDataObject != NULL);
		ASSERT(lpFormatEtc == NULL ||
			AfxIsValidAddress(lpFormatEtc, sizeof(FORMATETC), FALSE));

		// fill in FORMATETC struct
		FORMATETC formatEtc;
		lpFormatEtc = _AfxFillFormatEtc(lpFormatEtc, cfFormat, &formatEtc);

		// attempt to get the data
		return m_lpDataObject->QueryGetData(lpFormatEtc) == S_OK;
	}
}

/////////////////////////////////////////////////////////////////////////////
// clipboard API wrappers

BOOL COleDataObject::AttachClipboard()
{
	ASSERT(AfxIsValidAddress(this, sizeof(COleDataObject)));
	ASSERT(m_lpDataObject == NULL); // need to call release?
	ASSERT(!m_bClipboard); // already attached to clipboard?

	// set special "clipboard" flag for optimizations
	m_bClipboard = TRUE;
	return TRUE;
}

void COleDataObject::EnsureClipboardObject()
{
	ASSERT(AfxIsValidAddress(this, sizeof(COleDataObject)));

	if (m_bClipboard && m_lpDataObject == NULL)
	{
		// get clipboard using OLE API
		LPDATAOBJECT lpDataObject;
		SCODE sc = ::OleGetClipboard(&lpDataObject);

		// attach COleDataObject wrapper to IDataObject from clipboard
		if (sc == S_OK)
			Attach(lpDataObject, TRUE);
	}
}

/////////////////////////////////////////////////////////////////////////////


text:
'use strict'

const { Router } = require('express')

const { wrap } = require('./utils')

// load controller
const statusController = require('./status')
const appRouter = Router()

// register route
appRouter.get('/status', wrap(statusController.getStatus))
appRouter.get('/metrics/codimd', wrap(statusController.getMetrics))

exports.router = appRouter


text:
<?php

namespace MicroDebug;

use Micro\Application\Package as BasePackage;

class Package extends BasePackage
{
    public function boot()
    {
        (new Handler\FirePHP)->boot();
        (new Handler\Performance)->boot();

        if (!$this->container['request']->isAjax()) {
            (new Handler\DevTools)->boot();
        }
    }
}


text:
<!DOCTYPE html>

  <title>HTML5 Menu Test</title>

<menu type="toolbar">

    <menu label="File">
      <button type="button" onclick="newa()">New...</button>
      <button type="button" onclick="save()">Save...</button>
    </menu>

    <menu label="Edit">
      <button type="button" onclick="cut()">Cut...</button>
      <button type="button" onclick="copy()">Copy...</button>
      <button type="button" onclick="paste()">Paste...</button>
    </menu>

</menu>

<menu type="context" id="supermenu">
  <menuitem label="rotate" onclick="rotate()" icon="http://cdn1.iconfinder.com/data/icons/silk2/arrow_rotate_clockwise.png"></menuitem>
  <menuitem label="resize" onclick="resize()" icon="http://cdn3.iconfinder.com/data/icons/fugue/icon/image-resize.png"></menuitem>
  <menu label="share">
    <menuitem label="twitter" onclick="alert('foo')"></menuitem>
    <menuitem label="facebook" onclick="alert('bar')"></menuitem>
  </menu>
</menu>


text:
require 'test_helper'
require 'json'

class PersonTest < ActiveSupport::TestCase

  def setup
    begin  #this is done to have compatibility with both Rails 2.1 and 2.2
      @error_messages = I18n.translate('activerecord.errors.messages')
    rescue Exception => e
      @error_messages = ActiveRecord::Errors.default_error_messages
    end
    @valid_person = people(:valid_person)
    @invalid_person = people(:invalid_person)
    @valid_person_name = person_names(:valid_person_name)
    @valid_avatar = images(:jpg)
  end

  # This person should be valid by construction.
  def test_person_validity
    assert people(:valid_person).valid?
  end

  # This person should be invalid by construction.
  def test_person_invalidity
     assert !@invalid_person.valid?
     attributes = [:username, :email]
     attributes.each do |attribute|
       assert @invalid_person.errors[attribute].any?
     end
   end

  # Check uniqueness of username, must be case insesitive.
  def test_uniqueness_of_username
    person_repeat = Person.new(:username => @valid_person.username.upcase)
    assert !person_repeat.valid?
    assert_equal @error_messages[:taken], person_repeat.errors[:username][0], "Test must be case sensitive."
  end

  # Check uniqueness of email.
  def test_uniqueness_of_email
    person_repeat = Person.new(:email => @valid_person.email.upcase)
    assert !person_repeat.valid?
    assert_equal @error_messages[:taken], person_repeat.errors[:email][0], "Test must be case sensitive."
  end

  # Check that username is not too long or too short.
  def test_username_length_boundaries
    assert_length :min, @valid_person, :username, Person::USERNAME_MIN_LENGTH
    assert_length :max, @valid_person, :username, Person::USERNAME_MAX_LENGTH
  end

  # This is not in use because password lenght is validated only on create and update, not on model level, as normal
  # Password constraints are tested in people_controller_test (func)

  # Check that password is not too long or too short.
  # def test_password_length_boundaries
  #   just_created_person = Person.new(:email => "valid@example.com", :username => "passwdtester", :password => "firstProperValue") #password length is only checked if encrypted password is not already set
  #   assert_length :min, just_created_person, :password, Person::PASSWORD_MIN_LENGTH
  #   assert_length :max, just_created_person, :password, Person::PASSWORD_MAX_LENGTH
  # end

  # Test the validations involving username with valid examples.
  def test_username_with_valid_examples
    person = @valid_person
    valid_usernames = %w{juho kusti juho_kusti enu}
    valid_usernames.each do |username|
      person.username = username
      assert person.valid?, "#{username} should pass validation, but doesn't"
    end
  end

  # Test the validations involving username with invalid examples.
  def test_username_with_invalid_examples
    person = @valid_person
    invalid_usernames = %w{rails/rocks web2.0 javscript:something ME}
    invalid_usernames.each do |username|
      person.username = username
      assert !person.valid?, "#{username} shouldn't pass validation, but does"
    end
  end

  # Test the email validator against valid email addresses.
  def test_email_with_valid_examples
    person = @valid_person
    valid_endings = %w{com org net edu es jp info}
    valid_emails = valid_endings.collect do |ending|
      "foo.bar_1-9@baz-quux0.example.#{ending}"
    end
    valid_emails.each do |email|
      person.email = email
      assert person.valid?, "#{email} must be a valid email address"
    end
  end

  # Test the email validator against invalid email addresses.
  def test_email_with_invalid_examples
    person = @valid_person
    invalid_emails = %w{foobar@example.c @example.com f@com foo@bar..com
                        foobar@example.infod foobar.example.com
                        foo,@example.com foo@ex(ample.com foo@example,com}
    invalid_emails.each do |email|
      person.email = email
      assert !person.valid?, "#{email} tests as valid but shouldn't be"
      assert_equal "is invalid", person.errors[:email][0]
    end
  end

  def test_to_json
    person = @valid_person
    person.name = @valid_person_name
    avatar = @valid_avatar
    avatar.person = @valid_person

    person.rules.each { |r| r.destroy }
    person.reload

    raw_json = person.to_json(person, person.roles[0].client)

    assert_equal raw_json.gsub("gender", ""), raw_json.sub("gender", ""), "Duplicate gender key"

    json = JSON.parse(raw_json)

    assert_not_nil json["id"]
    assert_not_nil json["username"]
    assert_not_nil json["email"]
    assert_not_nil json["name"]
    assert_not_nil json["name"]["unstructured"]
    assert_not_nil json["name"]["given_name"]
    assert_not_nil json["name"]["family_name"]
    assert_nil json["password"]

    #special check for status, because response json is different from model structure
    assert_not_nil json["connection"]

    spec_fields = PersonSpec::ALL_FIELDS
    spec_fields.delete("status_message")

    assert_not_nil json["status"]["message"]
    spec_fields.delete("status_message_changed")
    assert_not_nil json["status"]["changed"]

    assert_not_nil(json["location"])
    assert_not_nil(json["location"]["label"])
    assert(json["location"]["latitude"]<=90)
    assert(json["location"]["latitude"]>=-90)

    assert_not_nil json["role"], "Role is missing"

    assert_not_nil json["updated_at"], "updated_at"

    spec_fields.each do |value|
        assert_not_nil json[value] , "#{value} was nil."
    end
  end

  def test_privacy
    person = @valid_person
    json = JSON.parse(person.to_json)
    assert_nil json["email"], "Email is not private"
    assert_nil json["location"], "Location is not private"
  end

  def test_name_update
    p = Person.new
    p.create_name(:given_name => "Mikko")
    p.name.update_attributes({ :family_name => "Virtanen" })
    assert_equal "Mikko", p.name.given_name
  end

  def test_association_info
    p = @valid_person
    p.is_association = true
    p.description = "Otaniemi Underground Fishing Academy"
    p.website = "http://oufa.tky.fi"
    assert p.save
  end

  def test_association_json
    p = @valid_person
    p.is_association = true
    p.description = "Otaniemi Underground Fishing Academy"
    p.website = "http://oufa.tky.fi"
    json = JSON.parse(p.to_json)

    assert_equal true, json["is_association"], "Association status"
    assert_equal "Otaniemi Underground Fishing Academy", json["description"], "Description"
    assert_equal "http://oufa.tky.fi", json["website"], "Website"
  end

  def test_self_connection
    p = @valid_person
    json = JSON.parse(p.to_json(p, clients(:one)))
    assert_equal "you", json["connection"]
  end

  def test_friend_connection
    p = @valid_person
    json = JSON.parse(p.to_json(p.contacts[0], clients(:one)))
    assert_equal "friend", json["connection"]
  end

  def test_kassi_email_kludge
    p = @valid_person
    json = JSON.parse(p.to_json)
    assert_nil json["email"]

    json = JSON.parse(p.to_json(nil, clients(:kassi)))
    assert_equal p.email, json["email"]
  end

  def test_description_length
    p = @valid_person
    p.description = (1..1000).map.join
    assert p.save
    p.reload
    assert_equal (1..1000).map.join, p.description
  end

  def test_password_validation
    p = Person.create(:username => "foo", :email => "bar@c.com", :password => "")
    assert_equal 1, p.errors.full_messages.size

    p = Person.create(:username => "foo", :email => "bar@c.com", :password => "\x19\x19\x19\x19\x19\x19\x19\x19")
    assert_equal 1, p.errors.full_messages.size
  end

end


text:
#ifndef DAN_AA_H
#define DAN_AA_H

#ifdef __cplusplus
extern "C" {
#else
#include <stdbool.h>
#endif

typedef struct dan_aa_node_struct* dan_aa_tree;

struct dan_aa_node_struct
{
    dan_aa_tree left;
    dan_aa_tree right;
    int level;
};
typedef struct dan_aa_node_struct dan_aa_node;

extern dan_aa_node dan_aa_bottom;
#define DAN_AA_TREE_INIT &dan_aa_bottom

#define DAN_AA_NODE_INIT \
{ .left = &dan_aa_bottom, .right = &dan_aa_bottom, .level = 0 }

typedef bool (*dan_aa_less)(dan_aa_node* a, dan_aa_node* b);

dan_aa_node* dan_aa_insert(dan_aa_node* x, dan_aa_tree* t, dan_aa_less less);
dan_aa_node* dan_aa_remove(dan_aa_node* x, dan_aa_tree* t, dan_aa_less less);
dan_aa_node* dan_aa_find(dan_aa_node* x, dan_aa_tree t, dan_aa_less less);

#ifdef __cplusplus
} // extern "C"
#endif

#endif


text:
<?php

namespace Dompdf;

use Dompdf\Css\Style;
use Dompdf\Frame\FrameList;

/**
 * @package dompdf
 * @link    http://dompdf.github.com/
 * @author  Benj Carson <benjcarson@digitaljunkies.ca>
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 */

/**
 * The main Frame class
 *
 * This class represents a single HTML element.  This class stores
 * positioning information as well as containing block location and
 * dimensions. Style information for the element is stored in a {@link
 * Style} object. Tree structure is maintained via the parent & children
 * links.
 *
 * @package dompdf
 */
class Frame
{
    const WS_TEXT = 1;
    const WS_SPACE = 2;

    /**
     * The DOMElement or DOMText object this frame represents
     *
     * @var \DOMElement|\DOMText
     */
    protected $_node;

    /**
     * Unique identifier for this frame.  Used to reference this frame
     * via the node.
     *
     * @var string
     */
    protected $_id;

    /**
     * Unique id counter
     */
    public static $ID_COUNTER = 0; /*protected*/

    /**
     * This frame's calculated style
     *
     * @var Style
     */
    protected $_style;

    /**
     * This frame's original style.  Needed for cases where frames are
     * split across pages.
     *
     * @var Style
     */
    protected $_original_style;

    /**
     * This frame's parent in the document tree.
     *
     * @var Frame
     */
    protected $_parent;

    /**
     * This frame's children
     *
     * @var Frame[]
     */
    protected $_frame_list;

    /**
     * This frame's first child.  All children are handled as a
     * doubly-linked list.
     *
     * @var Frame
     */
    protected $_first_child;

    /**
     * This frame's last child.
     *
     * @var Frame
     */
    protected $_last_child;

    /**
     * This frame's previous sibling in the document tree.
     *
     * @var Frame
     */
    protected $_prev_sibling;

    /**
     * This frame's next sibling in the document tree.
     *
     * @var Frame
     */
    protected $_next_sibling;

    /**
     * This frame's containing block (used in layout): array(x, y, w, h)
     *
     * @var float[]
     */
    protected $_containing_block;

    /**
     * Position on the page of the top-left corner of the margin box of
     * this frame: array(x,y)
     *
     * @var float[]
     */
    protected $_position;

    /**
     * Absolute opacity of this frame
     *
     * @var float
     */
    protected $_opacity;

    /**
     * This frame's decorator
     *
     * @var \Dompdf\FrameDecorator\AbstractFrameDecorator
     */
    protected $_decorator;

    /**
     * This frame's containing line box
     *
     * @var LineBox
     */
    protected $_containing_line;

    /**
     * @var array
     */
    protected $_is_cache = array();

    /**
     * Tells wether the frame was already pushed to the next page
     *
     * @var bool
     */
    public $_already_pushed = false;

    /**
     * @var bool
     */
    public $_float_next_line = false;

    /**
     * Tells wether the frame was split
     *
     * @var bool
     */
    public $_splitted;

    /**
     * @var int
     */
    public static $_ws_state = self::WS_SPACE;

    /**
     * Class constructor
     *
     * @param \DOMNode $node the DOMNode this frame represents
     */
    public function __construct(\DOMNode $node)
    {
        $this->_node = $node;

        $this->_parent = null;
        $this->_first_child = null;
        $this->_last_child = null;
        $this->_prev_sibling = $this->_next_sibling = null;

        $this->_style = null;
        $this->_original_style = null;

        $this->_containing_block = array(
            "x" => null,
            "y" => null,
            "w" => null,
            "h" => null,
        );

        $this->_containing_block[0] =& $this->_containing_block["x"];
        $this->_containing_block[1] =& $this->_containing_block["y"];
        $this->_containing_block[2] =& $this->_containing_block["w"];
        $this->_containing_block[3] =& $this->_containing_block["h"];

        $this->_position = array(
            "x" => null,
            "y" => null,
        );

        $this->_position[0] =& $this->_position["x"];
        $this->_position[1] =& $this->_position["y"];

        $this->_opacity = 1.0;
        $this->_decorator = null;

        $this->set_id(self::$ID_COUNTER++);
    }

    /**
     * WIP : preprocessing to remove all the unused whitespace
     */
    protected function ws_trim()
    {
        if ($this->ws_keep()) {
            return;
        }

        if (self::$_ws_state === self::WS_SPACE) {
            $node = $this->_node;

            if ($node->nodeName === "#text" && !empty($node->nodeValue)) {
                $node->nodeValue = preg_replace("/[ \t\r\n\f]+/u", " ", trim($node->nodeValue));
                self::$_ws_state = self::WS_TEXT;
            }
        }
    }

    /**
     * @return bool
     */
    protected function ws_keep()
    {
        $whitespace = $this->get_style()->white_space;

        return in_array($whitespace, array("pre", "pre-wrap", "pre-line"));
    }

    /**
     * @return bool
     */
    protected function ws_is_text()
    {
        $node = $this->get_node();

        if ($node->nodeName === "img") {
            return true;
        }

        if (!$this->is_in_flow()) {
            return false;
        }

        if ($this->is_text_node()) {
            return trim($node->nodeValue) !== "";
        }

        return true;
    }

    /**
     * "Destructor": forcibly free all references held by this frame
     *
     * @param bool $recursive if true, call dispose on all children
     */
    public function dispose($recursive = false)
    {
        if ($recursive) {
            while ($child = $this->_first_child) {
                $child->dispose(true);
            }
        }

        // Remove this frame from the tree
        if ($this->_prev_sibling) {
            $this->_prev_sibling->_next_sibling = $this->_next_sibling;
        }

        if ($this->_next_sibling) {
            $this->_next_sibling->_prev_sibling = $this->_prev_sibling;
        }

        if ($this->_parent && $this->_parent->_first_child === $this) {
            $this->_parent->_first_child = $this->_next_sibling;
        }

        if ($this->_parent && $this->_parent->_last_child === $this) {
            $this->_parent->_last_child = $this->_prev_sibling;
        }

        if ($this->_parent) {
            $this->_parent->get_node()->removeChild($this->_node);
        }

        $this->_style->dispose();
        $this->_style = null;
        unset($this->_style);

        $this->_original_style->dispose();
        $this->_original_style = null;
        unset($this->_original_style);

    }

    /**
     * Re-initialize the frame
     */
    public function reset()
    {
        $this->_position["x"] = null;
        $this->_position["y"] = null;

        $this->_containing_block["x"] = null;
        $this->_containing_block["y"] = null;
        $this->_containing_block["w"] = null;
        $this->_containing_block["h"] = null;

        $this->_style = null;
        unset($this->_style);
        $this->_style = clone $this->_original_style;
    }

    /**
     * @return \DOMElement|\DOMText
     */
    public function get_node()
    {
        return $this->_node;
    }

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

    /**
     * @return Style
     */
    public function get_style()
    {
        return $this->_style;
    }

    /**
     * @return Style
     */
    public function get_original_style()
    {
        return $this->_original_style;
    }

    /**
     * @return Frame
     */
    public function get_parent()
    {
        return $this->_parent;
    }

    /**
     * @return \Dompdf\FrameDecorator\AbstractFrameDecorator
     */
    public function get_decorator()
    {
        return $this->_decorator;
    }

    /**
     * @return Frame
     */
    public function get_first_child()
    {
        return $this->_first_child;
    }

    /**
     * @return Frame
     */
    public function get_last_child()
    {
        return $this->_last_child;
    }

    /**
     * @return Frame
     */
    public function get_prev_sibling()
    {
        return $this->_prev_sibling;
    }

    /**
     * @return Frame
     */
    public function get_next_sibling()
    {
        return $this->_next_sibling;
    }

    /**
     * @return FrameList|Frame[]
     */
    public function get_children()
    {
        if (isset($this->_frame_list)) {
            return $this->_frame_list;
        }

        $this->_frame_list = new FrameList($this);

        return $this->_frame_list;
    }

    // Layout property accessors

    /**
     * Containing block dimensions
     *
     * @param $i string The key of the wanted containing block's dimension (x, y, w, h)
     *
     * @return float[]|float
     */
    public function get_containing_block($i = null)
    {
        if (isset($i)) {
            return $this->_containing_block[$i];
        }

        return $this->_containing_block;
    }

    /**
     * Block position
     *
     * @param $i string The key of the wanted position value (x, y)
     *
     * @return array|float
     */
    public function get_position($i = null)
    {
        if (isset($i)) {
            return $this->_position[$i];
        }

        return $this->_position;
    }

    //........................................................................

    /**
     * Return the height of the margin box of the frame, in pt.  Meaningless
     * unless the height has been calculated properly.
     *
     * @return float
     */
    public function get_margin_height()
    {
        $style = $this->_style;

        return (float)$style->length_in_pt(array(
            $style->height,
            $style->margin_top,
            $style->margin_bottom,
            $style->border_top_width,
            $style->border_bottom_width,
            $style->padding_top,
            $style->padding_bottom
        ), $this->_containing_block["h"]);
    }

    /**
     * Return the width of the margin box of the frame, in pt.  Meaningless
     * unless the width has been calculated properly.
     *
     * @return float
     */
    public function get_margin_width()
    {
        $style = $this->_style;

        return (float)$style->length_in_pt(array(
            $style->width,
            $style->margin_left,
            $style->margin_right,
            $style->border_left_width,
            $style->border_right_width,
            $style->padding_left,
            $style->padding_right
        ), $this->_containing_block["w"]);
    }

    /**
     * @return float
     */
    public function get_break_margins()
    {
        $style = $this->_style;

        return (float)$style->length_in_pt(array(
            //$style->height,
            $style->margin_top,
            $style->margin_bottom,
            $style->border_top_width,
            $style->border_bottom_width,
            $style->padding_top,
            $style->padding_bottom
        ), $this->_containing_block["h"]);
    }

    /**
     * Return the content box (x,y,w,h) of the frame
     *
     * @return array
     */
    public function get_content_box()
    {
        $style = $this->_style;
        $cb = $this->_containing_block;

        $x = $this->_position["x"] +
            (float)$style->length_in_pt(array($style->margin_left,
                    $style->border_left_width,
                    $style->padding_left),
                $cb["w"]);

        $y = $this->_position["y"] +
            (float)$style->length_in_pt(array($style->margin_top,
                    $style->border_top_width,
                    $style->padding_top),
                $cb["h"]);

        $w = $style->length_in_pt($style->width, $cb["w"]);

        $h = $style->length_in_pt($style->height, $cb["h"]);

        return array(0 => $x, "x" => $x,
            1 => $y, "y" => $y,
            2 => $w, "w" => $w,
            3 => $h, "h" => $h);
    }

    /**
     * Return the padding box (x,y,w,h) of the frame
     *
     * @return array
     */
    public function get_padding_box()
    {
        $style = $this->_style;
        $cb = $this->_containing_block;

        $x = $this->_position["x"] +
            (float)$style->length_in_pt(array($style->margin_left,
                    $style->border_left_width),
                $cb["w"]);

        $y = $this->_position["y"] +
            (float)$style->length_in_pt(array($style->margin_top,
                    $style->border_top_width),
                $cb["h"]);

        $w = $style->length_in_pt(array($style->padding_left,
                $style->width,
                $style->padding_right),
            $cb["w"]);

        $h = $style->length_in_pt(array($style->padding_top,
                $style->height,
                $style->padding_bottom),
            $cb["h"]);

        return array(0 => $x, "x" => $x,
            1 => $y, "y" => $y,
            2 => $w, "w" => $w,
            3 => $h, "h" => $h);
    }

    /**
     * Return the border box of the frame
     *
     * @return array
     */
    public function get_border_box()
    {
        $style = $this->_style;
        $cb = $this->_containing_block;

        $x = $this->_position["x"] + (float)$style->length_in_pt($style->margin_left, $cb["w"]);

        $y = $this->_position["y"] + (float)$style->length_in_pt($style->margin_top, $cb["h"]);

        $w = $style->length_in_pt(array($style->border_left_width,
                $style->padding_left,
                $style->width,
                $style->padding_right,
                $style->border_right_width),
            $cb["w"]);

        $h = $style->length_in_pt(array($style->border_top_width,
                $style->padding_top,
                $style->height,
                $style->padding_bottom,
                $style->border_bottom_width),
            $cb["h"]);

        return array(0 => $x, "x" => $x,
            1 => $y, "y" => $y,
            2 => $w, "w" => $w,
            3 => $h, "h" => $h);
    }

    /**
     * @param null $opacity
     *
     * @return float
     */
    public function get_opacity($opacity = null)
    {
        if ($opacity !== null) {
            $this->set_opacity($opacity);
        }

        return $this->_opacity;
    }

    /**
     * @return LineBox
     */
    public function &get_containing_line()
    {
        return $this->_containing_line;
    }

    //........................................................................

    // Set methods
    /**
     * @param $id
     */
    public function set_id($id)
    {
        $this->_id = $id;

        // We can only set attributes of DOMElement objects (nodeType == 1).
        // Since these are the only objects that we can assign CSS rules to,
        // this shortcoming is okay.
        if ($this->_node->nodeType == XML_ELEMENT_NODE) {
            $this->_node->setAttribute("frame_id", $id);
        }
    }

    /**
     * @param Style $style
     */
    public function set_style(Style $style)
    {
        if (is_null($this->_style)) {
            $this->_original_style = clone $style;
        }

        //$style->set_frame($this);
        $this->_style = $style;
    }

    /**
     * @param \Dompdf\FrameDecorator\AbstractFrameDecorator $decorator
     */
    public function set_decorator(FrameDecorator\AbstractFrameDecorator $decorator)
    {
        $this->_decorator = $decorator;
    }

    /**
     * @param null $x
     * @param null $y
     * @param null $w
     * @param null $h
     */
    public function set_containing_block($x = null, $y = null, $w = null, $h = null)
    {
        if (is_array($x)) {
            foreach ($x as $key => $val) {
                $$key = $val;
            }
        }

        if (is_numeric($x)) {
            $this->_containing_block["x"] = $x;
        }

        if (is_numeric($y)) {
            $this->_containing_block["y"] = $y;
        }

        if (is_numeric($w)) {
            $this->_containing_block["w"] = $w;
        }

        if (is_numeric($h)) {
            $this->_containing_block["h"] = $h;
        }
    }

    /**
     * @param null $x
     * @param null $y
     */
    public function set_position($x = null, $y = null)
    {
        if (is_array($x)) {
            list($x, $y) = array($x["x"], $x["y"]);
        }

        if (is_numeric($x)) {
            $this->_position["x"] = $x;
        }

        if (is_numeric($y)) {
            $this->_position["y"] = $y;
        }
    }

    /**
     * @param $opacity
     */
    public function set_opacity($opacity)
    {
        $parent = $this->get_parent();
        $base_opacity = (($parent && $parent->_opacity !== null) ? $parent->_opacity : 1.0);
        $this->_opacity = $base_opacity * $opacity;
    }

    /**
     * @param LineBox $line
     */
    public function set_containing_line(LineBox $line)
    {
        $this->_containing_line = $line;
    }

    /**
     * Indicates if the margin height is auto sized
     *
     * @return bool
     */
    public function is_auto_height()
    {
        $style = $this->_style;

        return in_array(
            "auto",
            array(
                $style->height,
                $style->margin_top,
                $style->margin_bottom,
                $style->border_top_width,
                $style->border_bottom_width,
                $style->padding_top,
                $style->padding_bottom,
                $this->_containing_block["h"]
            ),
            true
        );
    }

    /**
     * Indicates if the margin width is auto sized
     *
     * @return bool
     */
    public function is_auto_width()
    {
        $style = $this->_style;

        return in_array(
            "auto",
            array(
                $style->width,
                $style->margin_left,
                $style->margin_right,
                $style->border_left_width,
                $style->border_right_width,
                $style->padding_left,
                $style->padding_right,
                $this->_containing_block["w"]
            ),
            true
        );
    }

    /**
     * Tells if the frame is a text node
     *
     * @return bool
     */
    public function is_text_node()
    {
        if (isset($this->_is_cache["text_node"])) {
            return $this->_is_cache["text_node"];
        }

        return $this->_is_cache["text_node"] = ($this->get_node()->nodeName === "#text");
    }

    /**
     * @return bool
     */
    public function is_positionned()
    {
        if (isset($this->_is_cache["positionned"])) {
            return $this->_is_cache["positionned"];
        }

        $position = $this->get_style()->position;

        return $this->_is_cache["positionned"] = in_array($position, Style::$POSITIONNED_TYPES);
    }

    /**
     * @return bool
     */
    public function is_absolute()
    {
        if (isset($this->_is_cache["absolute"])) {
            return $this->_is_cache["absolute"];
        }

        $position = $this->get_style()->position;

        return $this->_is_cache["absolute"] = ($position === "absolute" || $position === "fixed");
    }

    /**
     * @return bool
     */
    public function is_block()
    {
        if (isset($this->_is_cache["block"])) {
            return $this->_is_cache["block"];
        }

        return $this->_is_cache["block"] = in_array($this->get_style()->display, Style::$BLOCK_TYPES);
    }

    /**
     * @return bool
     */
    public function is_inline_block()
    {
        if (isset($this->_is_cache["inline_block"])) {
            return $this->_is_cache["inline_block"];
        }

        return $this->_is_cache["inline_block"] = ($this->get_style()->display === 'inline-block');
    }

    /**
     * @return bool
     */
    public function is_in_flow()
    {
        if (isset($this->_is_cache["in_flow"])) {
            return $this->_is_cache["in_flow"];
        }
        return $this->_is_cache["in_flow"] = !($this->get_style()->float !== "none" || $this->is_absolute());
    }

    /**
     * @return bool
     */
    public function is_pre()
    {
        if (isset($this->_is_cache["pre"])) {
            return $this->_is_cache["pre"];
        }

        $white_space = $this->get_style()->white_space;

        return $this->_is_cache["pre"] = in_array($white_space, array("pre", "pre-wrap"));
    }

    /**
     * @return bool
     */
    public function is_table()
    {
        if (isset($this->_is_cache["table"])) {
            return $this->_is_cache["table"];
        }

        $display = $this->get_style()->display;

        return $this->_is_cache["table"] = in_array($display, Style::$TABLE_TYPES);
    }

    /**
     * Inserts a new child at the beginning of the Frame
     *
     * @param $child       Frame The new Frame to insert
     * @param $update_node boolean Whether or not to update the DOM
     */
    public function prepend_child(Frame $child, $update_node = true)
    {
        if ($update_node) {
            $this->_node->insertBefore($child->_node, $this->_first_child ? $this->_first_child->_node : null);
        }

        // Remove the child from its parent
        if ($child->_parent) {
            $child->_parent->remove_child($child, false);
        }

        $child->_parent = $this;
        $child->_prev_sibling = null;

        // Handle the first child
        if (!$this->_first_child) {
            $this->_first_child = $child;
            $this->_last_child = $child;
            $child->_next_sibling = null;
        } else {
            $this->_first_child->_prev_sibling = $child;
            $child->_next_sibling = $this->_first_child;
            $this->_first_child = $child;
        }
    }

    /**
     * Inserts a new child at the end of the Frame
     *
     * @param $child       Frame The new Frame to insert
     * @param $update_node boolean Whether or not to update the DOM
     */
    public function append_child(Frame $child, $update_node = true)
    {
        if ($update_node) {
            $this->_node->appendChild($child->_node);
        }

        // Remove the child from its parent
        if ($child->_parent) {
            $child->_parent->remove_child($child, false);
        }

        $child->_parent = $this;
        $decorator = $child->get_decorator();
        // force an update to the cached parent
        if ($decorator !== null) {
            $decorator->get_parent(false);
        }
        $child->_next_sibling = null;

        // Handle the first child
        if (!$this->_last_child) {
            $this->_first_child = $child;
            $this->_last_child = $child;
            $child->_prev_sibling = null;
        } else {
            $this->_last_child->_next_sibling = $child;
            $child->_prev_sibling = $this->_last_child;
            $this->_last_child = $child;
        }
    }

    /**
     * Inserts a new child immediately before the specified frame
     *
     * @param $new_child   Frame The new Frame to insert
     * @param $ref         Frame The Frame after the new Frame
     * @param $update_node boolean Whether or not to update the DOM
     *
     * @throws Exception
     */
    public function insert_child_before(Frame $new_child, Frame $ref, $update_node = true)
    {
        if ($ref === $this->_first_child) {
            $this->prepend_child($new_child, $update_node);

            return;
        }

        if (is_null($ref)) {
            $this->append_child($new_child, $update_node);

            return;
        }

        if ($ref->_parent !== $this) {
            throw new Exception("Reference child is not a child of this node.");
        }

        // Update the node
        if ($update_node) {
            $this->_node->insertBefore($new_child->_node, $ref->_node);
        }

        // Remove the child from its parent
        if ($new_child->_parent) {
            $new_child->_parent->remove_child($new_child, false);
        }

        $new_child->_parent = $this;
        $new_child->_next_sibling = $ref;
        $new_child->_prev_sibling = $ref->_prev_sibling;

        if ($ref->_prev_sibling) {
            $ref->_prev_sibling->_next_sibling = $new_child;
        }

        $ref->_prev_sibling = $new_child;
    }

    /**
     * Inserts a new child immediately after the specified frame
     *
     * @param $new_child   Frame The new Frame to insert
     * @param $ref         Frame The Frame before the new Frame
     * @param $update_node boolean Whether or not to update the DOM
     *
     * @throws Exception
     */
    public function insert_child_after(Frame $new_child, Frame $ref, $update_node = true)
    {
        if ($ref === $this->_last_child) {
            $this->append_child($new_child, $update_node);

            return;
        }

        if (is_null($ref)) {
            $this->prepend_child($new_child, $update_node);

            return;
        }

        if ($ref->_parent !== $this) {
            throw new Exception("Reference child is not a child of this node.");
        }

        // Update the node
        if ($update_node) {
            if ($ref->_next_sibling) {
                $next_node = $ref->_next_sibling->_node;
                $this->_node->insertBefore($new_child->_node, $next_node);
            } else {
                $new_child->_node = $this->_node->appendChild($new_child->_node);
            }
        }

        // Remove the child from its parent
        if ($new_child->_parent) {
            $new_child->_parent->remove_child($new_child, false);
        }

        $new_child->_parent = $this;
        $new_child->_prev_sibling = $ref;
        $new_child->_next_sibling = $ref->_next_sibling;

        if ($ref->_next_sibling) {
            $ref->_next_sibling->_prev_sibling = $new_child;
        }

        $ref->_next_sibling = $new_child;
    }

    /**
     * Remove a child frame
     *
     * @param Frame $child
     * @param boolean $update_node Whether or not to remove the DOM node
     *
     * @throws Exception
     * @return Frame The removed child frame
     */
    public function remove_child(Frame $child, $update_node = true)
    {
        if ($child->_parent !== $this) {
            throw new Exception("Child not found in this frame");
        }

        if ($update_node) {
            $this->_node->removeChild($child->_node);
        }

        if ($child === $this->_first_child) {
            $this->_first_child = $child->_next_sibling;
        }

        if ($child === $this->_last_child) {
            $this->_last_child = $child->_prev_sibling;
        }

        if ($child->_prev_sibling) {
            $child->_prev_sibling->_next_sibling = $child->_next_sibling;
        }

        if ($child->_next_sibling) {
            $child->_next_sibling->_prev_sibling = $child->_prev_sibling;
        }

        $child->_next_sibling = null;
        $child->_prev_sibling = null;
        $child->_parent = null;

        return $child;
    }

    //........................................................................

    // Debugging function:
    /**
     * @return string
     */
    public function __toString()
    {
        // Skip empty text frames
//     if ( $this->is_text_node() &&
//          preg_replace("/\s/", "", $this->_node->data) === "" )
//       return "";

        $str = "<b>" . $this->_node->nodeName . ":</b><br/>";
        //$str .= spl_object_hash($this->_node) . "<br/>";
        $str .= "Id: " . $this->get_id() . "<br/>";
        $str .= "Class: " . get_class($this) . "<br/>";

        if ($this->is_text_node()) {
            $tmp = htmlspecialchars($this->_node->nodeValue);
            $str .= "<pre>'" . mb_substr($tmp, 0, 70) .
                (mb_strlen($tmp) > 70 ? "..." : "") . "'</pre>";
        } elseif ($css_class = $this->_node->getAttribute("class")) {
            $str .= "CSS class: '$css_class'<br/>";
        }

        if ($this->_parent) {
            $str .= "\nParent:" . $this->_parent->_node->nodeName .
                " (" . spl_object_hash($this->_parent->_node) . ") " .
                "<br/>";
        }

        if ($this->_prev_sibling) {
            $str .= "Prev: " . $this->_prev_sibling->_node->nodeName .
                " (" . spl_object_hash($this->_prev_sibling->_node) . ") " .
                "<br/>";
        }

        if ($this->_next_sibling) {
            $str .= "Next: " . $this->_next_sibling->_node->nodeName .
                " (" . spl_object_hash($this->_next_sibling->_node) . ") " .
                "<br/>";
        }

        $d = $this->get_decorator();
        while ($d && $d != $d->get_decorator()) {
            $str .= "Decorator: " . get_class($d) . "<br/>";
            $d = $d->get_decorator();
        }

        $str .= "Position: " . Helpers::pre_r($this->_position, true);
        $str .= "\nContaining block: " . Helpers::pre_r($this->_containing_block, true);
        $str .= "\nMargin width: " . Helpers::pre_r($this->get_margin_width(), true);
        $str .= "\nMargin height: " . Helpers::pre_r($this->get_margin_height(), true);

        $str .= "\nStyle: <pre>" . $this->_style->__toString() . "</pre>";

        if ($this->_decorator instanceof FrameDecorator\Block) {
            $str .= "Lines:<pre>";
            foreach ($this->_decorator->get_line_boxes() as $line) {
                foreach ($line->get_frames() as $frame) {
                    if ($frame instanceof FrameDecorator\Text) {
                        $str .= "\ntext: ";
                        $str .= "'" . htmlspecialchars($frame->get_text()) . "'";
                    } else {
                        $str .= "\nBlock: " . $frame->get_node()->nodeName . " (" . spl_object_hash($frame->get_node()) . ")";
                    }
                }

                $str .=
                    "\ny => " . $line->y . "\n" .
                    "w => " . $line->w . "\n" .
                    "h => " . $line->h . "\n" .
                    "left => " . $line->left . "\n" .
                    "right => " . $line->right . "\n";
            }
            $str .= "</pre>";
        }

        $str .= "\n";
        if (php_sapi_name() === "cli") {
            $str = strip_tags(str_replace(array("<br/>", "<b>", "</b>"),
                array("\n", "", ""),
                $str));
        }

        return $str;
    }
}


text:
<?php
/**
 * Login Exception Stub
 *
 * Generic parent class for login exceptions.
 *
 * @package    Elgg.Core
 * @subpackage Exceptions.Stub
 */
class LoginException extends Exception {}


text:
#include <nan.h>
#include "sol-js-gpio.h"
#include "../common.h"

using namespace v8;

bool c_sol_gpio_config(v8::Local<v8::Object> jsGPIOConfig,
    sol_gpio_data *gpio_data, sol_gpio_config *config) {
    SOL_SET_API_VERSION(config->api_version = SOL_GPIO_CONFIG_API_VERSION; )

    VALIDATE_AND_ASSIGN((*config), dir, sol_gpio_direction, IsUint32,
                        "(GPIO direction)", false, jsGPIOConfig,
                        Uint32Value);

    VALIDATE_AND_ASSIGN((*config), drive_mode, sol_gpio_drive, IsUint32,
                        "(GPIO pull-up/pull-down resistor)", false, jsGPIOConfig,
                        Uint32Value);

    VALIDATE_AND_ASSIGN((*config), active_low, bool, IsBoolean,
                        "(GPIO active_low state)", false, jsGPIOConfig,
                        BooleanValue);

    if (config->dir == SOL_GPIO_DIR_IN) {
        Local<Value> poll_timeout =
            Nan::Get(jsGPIOConfig, Nan::New("poll_timeout").ToLocalChecked())
                .ToLocalChecked();
        VALIDATE_VALUE_TYPE(poll_timeout, IsUint32, "GPIO in poll_timeout",
            false);
        config->in.poll_timeout = (uint32_t)poll_timeout->Uint32Value();

        Local<Value> trigger_mode =
            Nan::Get(jsGPIOConfig, Nan::New("trigger_mode").ToLocalChecked())
                .ToLocalChecked();
        VALIDATE_VALUE_TYPE(trigger_mode, IsString, "GPIO in trigger_mode",
            false);
        config->in.trigger_mode = (sol_gpio_edge)sol_gpio_edge_from_str(
            (const char *)*(String::Utf8Value(trigger_mode)));

        Local<Value> read_cb = Nan::Get(jsGPIOConfig,
            Nan::New("callback").ToLocalChecked()).ToLocalChecked();

        if (read_cb->IsFunction()) {
            Nan::Callback *callback =
                new Nan::Callback(Local<Function>::Cast(read_cb));
            gpio_data->callback = callback;
            config->in.user_data = gpio_data;
        }
    }

    return true;
}


text:
import * as Rx from 'rx';

import {RESTResource} from './rest_resource';
import {Connection} from '../../connection';
import * as types from '../../types/rest';

/**
 * Storage resource class for dealing with storage endpoint.
 */
export class StorageResource extends RESTResource<types.Storage> {

    constructor(connection: Connection) {
        super('storage', connection);
    }

    public getStorageLink(primaryKey: number | string): string {
        return this.connection.createUriFromPath(this.getDetailPath(primaryKey), { format: 'json' });
    }

    public query(query: types.Query = {}): Rx.Observable<types.Storage[]> {
        throw new Error('query method not supported');
    }

    public queryOne(query: types.Query = {}): Rx.Observable<types.Storage> {
        throw new Error('queryOne method not supported');
    }

    public create(data: Object): Rx.Observable<types.Storage> {
        throw new Error('create method not supported');
    }

    public update(primaryKey: number | string, data: Object): Rx.Observable<types.Storage> {
        throw new Error('update method not supported');
    }

    public replace(primaryKey: number | string, data: Object): Rx.Observable<types.Storage> {
        throw new Error('replace method not supported');
    }

    public delete(primaryKey: number | string): Rx.Observable<Object> {
        throw new Error('delete method not supported');
    }
}


text:
@interface UIWindow (EYAdditions)
+ (BOOL)isKeyboardVisible; // Determines if the keyboard is visible.
- (UIView *)findFirstResponder; // Searches the view hierarchy recursively for the first responder, starting with this window.
- (UIView *)findFirstResponderInView:(UIView *)topView; // Searches the view hierarchy recursively for the first responder, starting with topView.
@end


text:
/*
 * Created by IntelliJ IDEA.
 * User: Alexey
 * Date: 25.11.2006
 * Time: 15:39:27
 */
package com.intellij.codeInsight.daemon.impl;

import com.intellij.codeHighlighting.Pass;
import com.intellij.codeHighlighting.TextEditorHighlightingPass;
import com.intellij.codeHighlighting.TextEditorHighlightingPassFactory;
import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar;
import com.intellij.openapi.components.AbstractProjectComponent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author cdr
*/
public class ShowAutoImportPassFactory extends AbstractProjectComponent implements TextEditorHighlightingPassFactory {
  public ShowAutoImportPassFactory(Project project, TextEditorHighlightingPassRegistrar highlightingPassRegistrar) {
    super(project);
    highlightingPassRegistrar.registerTextEditorHighlightingPass(this, new int[]{Pass.UPDATE_ALL,}, null, false, -1);
  }

  @NonNls
  @NotNull
  public String getComponentName() {
    return "ShowAutoImportPassFactory";
  }

  @Nullable
  public TextEditorHighlightingPass createHighlightingPass(@NotNull PsiFile file, @NotNull final Editor editor) {
    return new ShowAutoImportPass(myProject, file, editor);
  }
}


text:
.sphinxsidebarwrapper {
	overflow: hidden;
}

.sphinxsidebarwrapper:before {
    content: "";
    display: block;
    background: url("favicon-96x96.png") no-repeat;
    background-size: 100% auto;
    width: 48px;
    height: 48px;
}


text:
(function() {
	var spritesCreated = false;

	function createSprites() {
		if (!spritesCreated) {
			spritesCreated = true;
			Crafty.sprite(breakout.TILE_SIZE, 'aprilfools-2015/media/tiles.png', {
				countdown: [0, 6, 2, 3]
			});
		}
	}

	Crafty.c('Countdown', {
		init: function() {
			createSprites();
			this.requires('SpriteAnimation, countdown, Center');
			this._lastFrame = 0;

		},
		countdown: function(duration, callback) {
			return this.reel('countdown', duration, [[0, 6], [2, 6], [4, 6]])
				.animate('countdown', 0)
				.bind('FrameChange', function() {
					if (this._currentReel.currentFrame !== this._lastFrame) {
						Crafty.audio.play('countdownBlip', 1, 0.3);
					}
					this._lastFrame = this._currentReel.currentFrame;
				})
				.bind('AnimationEnd', function() {
					Crafty.audio.play('countdownBlip', 1, 0.3);
					this.destroy();
					callback();
				});
		}
	});
})();


text:
using System.Data;

public static partial class Extensions
{
    /// <summary>
    ///     An IDataReader extension method that gets value to.
    /// </summary>
    /// <typeparam name="T">Generic type parameter.</typeparam>
    /// <param name="this">The @this to act on.</param>
    /// <param name="index">Zero-based index of the.</param>
    /// <returns>The value to.</returns>
    public static T GetValueTo<T>(this IDataReader @this, int index)
    {
        return @this.GetValue(index).To<T>();
    }

    /// <summary>
    ///     An IDataReader extension method that gets value to.
    /// </summary>
    /// <typeparam name="T">Generic type parameter.</typeparam>
    /// <param name="this">The @this to act on.</param>
    /// <param name="columnName">Name of the column.</param>
    /// <returns>The value to.</returns>
    public static T GetValueTo<T>(this IDataReader @this, string columnName)
    {
        return @this.GetValue(@this.GetOrdinal(columnName)).To<T>();
    }
}


text:
define("view/project/list/close", ["require", "exports", "module", "lang/index", "hbs!template/project_item_close"],
function(e, t) {
  e("lang/index");
  t.View = Backbone.View.extend({
    id: "l-closed-toggle",
    tagName: "a",
    template: e("hbs!template/project_item_close"),
    events: {
      click: "slideToggleClosed"
    },
    initialize: function(e) {
      this.render(),
      this.initDomAttr()
    },
    initDomAttr: function() {
      this.$count = this.$(".count")
    },
    render: function() {
      this.$el.html(this.template()),
      $(".list-closed").prepend(this.$el),
      $("#close-project-ul").hide()
    },
    slideToggleClosed: function(e) {
      e = e || window.event;
      var t = $(e.currentTarget);
      t.toggleClass("open");
      var i = this;
      $("#close-project-ul").slideToggle(120,
      function() {
        i.$count.text($("#close-project-ul").find("li.project").length)
      })
    }
  })
})


text:
from oslo.config import cfg

from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import availability_zones
from nova import db
from nova import servicegroup

CONF = cfg.CONF

authorize_list = extensions.extension_authorizer('compute',
                                                 'availability_zone:list')
authorize_detail = extensions.extension_authorizer('compute',
                                                   'availability_zone:detail')

def make_availability_zone(elem):
    elem.set('name', 'zoneName')

    zoneStateElem = xmlutil.SubTemplateElement(elem, 'zoneState',
                                               selector='zoneState')
    zoneStateElem.set('available')

    hostsElem = xmlutil.SubTemplateElement(elem, 'hosts', selector='hosts')
    hostElem = xmlutil.SubTemplateElement(hostsElem, 'host',
                                          selector=xmlutil.get_items)
    hostElem.set('name', 0)

    svcsElem = xmlutil.SubTemplateElement(hostElem, 'services', selector=1)
    svcElem = xmlutil.SubTemplateElement(svcsElem, 'service',
                                         selector=xmlutil.get_items)
    svcElem.set('name', 0)

    svcStateElem = xmlutil.SubTemplateElement(svcElem, 'serviceState',
                                              selector=1)
    svcStateElem.set('available')
    svcStateElem.set('active')
    svcStateElem.set('updated_at')

    # Attach metadata node
    elem.append(common.MetadataTemplate())

class AvailabilityZonesTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('availabilityZones')
        zoneElem = xmlutil.SubTemplateElement(root, 'availabilityZone',
                                              selector='availabilityZoneInfo')
        make_availability_zone(zoneElem)
        return xmlutil.MasterTemplate(root, 1, nsmap={
            Availability_zone.alias: Availability_zone.namespace})

class AvailabilityZoneController(wsgi.Controller):
    """The Availability Zone API controller for the OpenStack API."""

    def __init__(self):
        super(AvailabilityZoneController, self).__init__()
        self.servicegroup_api = servicegroup.API()

    def _get_filtered_availability_zones(self, zones, is_available):
        result = []
        for zone in zones:
            # Hide internal_service_availability_zone
            if zone == CONF.internal_service_availability_zone:
                continue
            result.append({'zoneName': zone,
                           'zoneState': {'available': is_available},
                           "hosts": None})
        return result

    def _describe_availability_zones(self, context, **kwargs):
        ctxt = context.elevated()
        available_zones, not_available_zones = \
            availability_zones.get_availability_zones(ctxt)

        filtered_available_zones = \
            self._get_filtered_availability_zones(available_zones, True)
        filtered_not_available_zones = \
            self._get_filtered_availability_zones(not_available_zones, False)
        return {'availabilityZoneInfo': filtered_available_zones +
                                        filtered_not_available_zones}

    def _describe_availability_zones_verbose(self, context, **kwargs):
        ctxt = context.elevated()
        available_zones, not_available_zones = \
            availability_zones.get_availability_zones(ctxt)

        # Available services
        enabled_services = db.service_get_all(context, False)
        enabled_services = availability_zones.set_availability_zones(context,
                enabled_services)
        zone_hosts = {}
        host_services = {}
        for service in enabled_services:
            zone_hosts.setdefault(service['availability_zone'], [])
            if service['host'] not in zone_hosts[service['availability_zone']]:
                zone_hosts[service['availability_zone']].append(
                    service['host'])

            host_services.setdefault(service['availability_zone'] +
                    service['host'], [])
            host_services[service['availability_zone'] + service['host']].\
                    append(service)

        result = []
        for zone in available_zones:
            hosts = {}
            for host in zone_hosts.get(zone, []):
                hosts[host] = {}
                for service in host_services[zone + host]:
                    alive = self.servicegroup_api.service_is_up(service)
                    hosts[host][service['binary']] = {'available': alive,
                                      'active': True != service['disabled'],
                                      'updated_at': service['updated_at']}
            result.append({'zoneName': zone,
                           'zoneState': {'available': True},
                           "hosts": hosts})

        for zone in not_available_zones:
            result.append({'zoneName': zone,
                           'zoneState': {'available': False},
                           "hosts": None})
        return {'availabilityZoneInfo': result}

    @wsgi.serializers(xml=AvailabilityZonesTemplate)
    def index(self, req):
        """Returns a summary list of availability zone."""
        context = req.environ['nova.context']
        authorize_list(context)

        return self._describe_availability_zones(context)

    @wsgi.serializers(xml=AvailabilityZonesTemplate)
    def detail(self, req):
        """Returns a detailed list of availability zone."""
        context = req.environ['nova.context']
        authorize_detail(context)

        return self._describe_availability_zones_verbose(context)

class Availability_zone(extensions.ExtensionDescriptor):
    """1. Add availability_zone to the Create Server v1.1 API.
       2. Add availability zones describing.
    """

    name = "AvailabilityZone"
    alias = "os-availability-zone"
    namespace = ("http://docs.openstack.org/compute/ext/"
                 "availabilityzone/api/v1.1")
    updated = "2012-12-21T00:00:00+00:00"

    def get_resources(self):
        resources = []

        res = extensions.ResourceExtension('os-availability-zone',
                                       AvailabilityZoneController(),
                                       collection_actions={'detail': 'GET'})
        resources.append(res)

        return resources


text:
/**
 * Created for testing Bank class.
 * Created on 28.04.2017.
 * @author Matevosyan Vardan
 * @version 1.0
 */

package ru.matevosyan;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Arq. Inst. Biol. Veget. Rio de Janeiro 3(1): 91-98 (1936)

#### Original name
Cercospora passiflorae A.S. Mull. & Chupp

### Remarks
null


text:
package fr.adrienbrault.idea.symfony2plugin.navigation;

import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.FoldingBuilderEx;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.php.lang.psi.PhpFile;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import fr.adrienbrault.idea.symfony2plugin.Settings;
import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;
import fr.adrienbrault.idea.symfony2plugin.config.SymfonyPhpReferenceContributor;
import fr.adrienbrault.idea.symfony2plugin.routing.PhpRouteReferenceContributor;
import fr.adrienbrault.idea.symfony2plugin.routing.Route;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil;
import fr.adrienbrault.idea.symfony2plugin.util.MethodMatcher;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class PhpFoldingBuilder extends FoldingBuilderEx {

    @NotNull
    @Override
    public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement psiElement, @NotNull Document document, boolean b) {

        if (!Symfony2ProjectComponent.isEnabled(psiElement) || !(psiElement instanceof PhpFile)) {
            return new FoldingDescriptor[0];
        }

        boolean codeFoldingPhpRoute = Settings.getInstance(psiElement.getProject()).codeFoldingPhpRoute;
        boolean codeFoldingPhpModel = Settings.getInstance(psiElement.getProject()).codeFoldingPhpModel;
        boolean codeFoldingPhpTemplate = Settings.getInstance(psiElement.getProject()).codeFoldingPhpTemplate;

        // we dont need to do anything
        if(!codeFoldingPhpRoute && !codeFoldingPhpModel && !codeFoldingPhpTemplate) {
            return new FoldingDescriptor[0];
        }

        List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>();

        Collection<StringLiteralExpression> stringLiteralExpressiones = PsiTreeUtil.findChildrenOfType(psiElement, StringLiteralExpression.class);
        for(StringLiteralExpression stringLiteralExpression: stringLiteralExpressiones) {

            if(codeFoldingPhpModel) {
                attachModelShortcuts(descriptors, stringLiteralExpression);
            }

            if(codeFoldingPhpTemplate) {
                attachTemplateShortcuts(descriptors, stringLiteralExpression);
            }

        }

        // strip ".[php|html].twig"
        if(codeFoldingPhpRoute) {
            attachRouteShortcuts(descriptors, stringLiteralExpressiones);
        }

        return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
    }

    private void attachRouteShortcuts(List<FoldingDescriptor> descriptors, Collection<StringLiteralExpression> stringLiteralExpressions) {

        Map<String,Route> routes = null;

        for(StringLiteralExpression stringLiteralExpression: stringLiteralExpressions) {

            if (MethodMatcher.getMatchedSignatureWithDepth(stringLiteralExpression, PhpRouteReferenceContributor.GENERATOR_SIGNATURES) != null) {

                // cache routes if we need them
                if(routes == null) {
                    routes = RouteHelper.getAllRoutes(stringLiteralExpression.getProject());
                }

                String contents = stringLiteralExpression.getContents();
                if(contents.length() > 0 && routes.containsKey(contents)) {
                    final Route route = routes.get(contents);

                    final String url = RouteHelper.getRouteUrl(route);
                    if(url != null) {
                        descriptors.add(new FoldingDescriptor(stringLiteralExpression.getNode(),
                            new TextRange(stringLiteralExpression.getTextRange().getStartOffset() + 1, stringLiteralExpression.getTextRange().getEndOffset() - 1)) {
                            @Nullable
                            @Override
                            public String getPlaceholderText() {
                                return url;
                            }
                        });
                    }
                }
            }

        }

    }

    private void attachModelShortcuts(List<FoldingDescriptor> descriptors, final StringLiteralExpression stringLiteralExpression) {

        if (MethodMatcher.getMatchedSignatureWithDepth(stringLiteralExpression, SymfonyPhpReferenceContributor.REPOSITORY_SIGNATURES) == null) {
            return;
        }

        String content = stringLiteralExpression.getContents();

        for(String lastChar: new String[] {":", "\\"}) {
            if(content.contains(lastChar)) {
                final String replace = content.substring(content.lastIndexOf(lastChar) + 1);
                if(replace.length() > 0) {
                    descriptors.add(new FoldingDescriptor(stringLiteralExpression.getNode(),
                        new TextRange(stringLiteralExpression.getTextRange().getStartOffset() + 1, stringLiteralExpression.getTextRange().getEndOffset() - 1)) {
                        @Nullable
                        @Override
                        public String getPlaceholderText() {
                            return replace;
                        }
                    });
                }

                return;
            }
        }

    }

    private void attachTemplateShortcuts(List<FoldingDescriptor> descriptors, final StringLiteralExpression stringLiteralExpression) {

        if (MethodMatcher.getMatchedSignatureWithDepth(stringLiteralExpression, SymfonyPhpReferenceContributor.TEMPLATE_SIGNATURES) == null) {
            return;
        }

        String content = stringLiteralExpression.getContents();

        String templateShortcutName = TwigUtil.getFoldingTemplateName(content);
        if(templateShortcutName == null) {
            return;
        }

        final String finalTemplateShortcutName = templateShortcutName;
        descriptors.add(new FoldingDescriptor(stringLiteralExpression.getNode(),
            new TextRange(stringLiteralExpression.getTextRange().getStartOffset() + 1, stringLiteralExpression.getTextRange().getEndOffset() - 1)) {
            @Nullable
            @Override
            public String getPlaceholderText() {
                return finalTemplateShortcutName;
            }
        });

    }

    @Nullable
    @Override
    public String getPlaceholderText(@NotNull ASTNode astNode) {
        return "...";
    }

    @Override
    public boolean isCollapsedByDefault(@NotNull ASTNode astNode) {
        return true;
    }
}


text:
![](images/CTD-logo-v5-02.png)

[ConnectTheDots.io](http://connectthedots.io) is an open source project created by Microsoft to help you get tiny devices connected to Microsoft Azure IoT and to implement great IoT solutions taking advantage of Microsoft Azure advanced analytic services such as Azure Stream Analytics and Azure Machine Learning.

The project is built with the assumption that the sensors get the raw data and format it into a JSON string. That string is then sent to Azure IoT Hub, from which a Web app gathers the data and displays it as a chart.
Optional other functions of the Azure cloud include detecting and displaying alerts and averages, however this is not required.

The JSON string is sent to Azure IoT Hub whether directly by the sensor device if it is capable of connecting to Azure IoT Hub or through a multi-protocol Gateway, which is how the [Getting Started with Pi and Arduino](GettingStarted.md) sample does it.
More details on each of those options are below.

![](images/ConnectTheDots-architecture.png)

In this project there are code samples, configuration scripts and guides that will help you set up devices and sensors, and configure Microsoft Azure services to view and analyze the data produced by those devices. Some of these samples have been provided by Microsoft, others by third parties; we encourage everyone to submit code samples or configuration documentation to grow this project.

This project contains several device samples all aimed at helping you connect your devices to Azure IoT, as well as visualize and gain insight from your data.  Check out all the samples below, or follow the getting started walkthrough to learn more. Then, add some of your devices to the project!

We encourage the community to contribute to the project! See [Contribute](Contribute.md) page for details.

## What's new in the V2? ##

Plenty!
The main change is the use of Azure IoT Hub instead of Event Hubs for connecting devices to the Cloud, but here is a list of what's new in V2

- Migrated from Event Hubs to Azure IoT Hub for the devices connectivity to Azure IoT: IoT Hub offers a better security with a per device authentication, along with a bidirectional messaging infrastructure.
- Replaced the Azure Prep tool with an ARM Template: you can now deploy the whole solution (including the WebSite) from a command line not only on Windows, but also no a Mac or a Linux machine!
- Updated devices samples
    - Updated all the node.js samples to use the Azure IoT Hub SDK
    - Removed old devices samples (Galileo, .Net Micro Framework)
    - Updated the Gateway code to use Azure IoT Hub device SDK
    - Upgraded WP8 samples (Simulated Sensors and MS Band) to Windows 10 UWP apps
    - Added Xamarin samples
    - Added a sample for ESP8266 chips

## Where is the V1 if I still want to use the old fashion way (using Event Hub)? ##
The V1 has been tagged and you can find the release as a binary [here](https://github.com/Azure/connectthedots/releases/tag/1.0)
We also created a [branch](https://github.com/Azure/connectthedots/tree/V1) that we will not make additions to any more but will definitively track to merge your contributions.

## Device basics ##

### Data format ###
ConnectTheDots is built on the assumption that data from sensors is sent to Azure IoT Hub in a prescribed JSON format. The minimum structure, with required attribute names, is

```
{
    "guid":	"string",
    "organization":	"string",
    "displayname": "string",
    "location": "string",
    "measurename": "string",
    "unitofmeasure": "string",
    "timecreated": "string",
    "value": double/float/integer
}
```

This should all be sent as one string message to IoT Hub, for example as the following strings:

    {"guid":"62X74059-A444-4797-8A7E-526C3EF9D64B","organization":"My Org Name","displayname":"Sensor Name","location":"Sensor Location","measurename":"Temperature","unitofmeasure":"F","timecreated":"1975-09-16T12:00:00Z", "value":74}

or

    {"guid":"62X74059-A444-4797-8A7E-526C3EF9D64B","organization":"my org name","displayname":"sensor name","location":"sensor location","measurename":"Temperature","unitofmeasure":"F","timecreated":"1975-09-16T12:00:00Z", "value":74.0001}

Furthermore, the project is built upon the assumption that the *sensors* create and format this JSON string.
For example, if using a sensor attached to an Arduino, the code running on the Arduino would send successive JSON strings, CRLF ended, out the serial port to a gateway such as a Raspberry Pi or Windows Tablet. The gateway does nothing other than receive the JSON string, package that into the right message format, adds the timecreated time stamp, and send it to Azure.

In the case of a directly connected device, the latest needs to send the JSON package to the IoT Hub leveraging one of the existing Azure IoT Hub device client SDKs.

All the device code included in this project, or submitted for inclusion, must conform to the JSON format requirement above.

### Devices and Gateway ###
ConnectTheDots provides a Multi-protocol Gateway to collect data from devices that cannot, or should not, target the cloud directly. The Gateway code is tested on Mono for Linux and on the .NET Framework on Windows and is located in the source tree under [Devices/Gateways/GatewayService](Devices/Gateways/GatewayService/), and is a simple system service.

To send data from a device to a gateway, you can just use the same exact data format and a device protocol adapter to implement any transport of your choice. The device protocol adapter is an assembly that implements the DeviceAdapterAbstract type to collect data from the device and enqueue them to the gateway for upload to the cloud. The Gateway automatically loads the device adapters from the Gateway binary directory, so deployment is extremely simple.
You can find some examples under [Devices/Gateways/GatewayService/DeviceAdapters](Devices/Gateways/GatewayService/DeviceAdapters), and the matching devices under  [Devices/GatewayConnectedDevices](Devices/GatewayConnectedDevices).

We even have some devices running in separate processes as a Python script, sending data to an adapter Gateway on a socket or a serial port connection. It does not get any easier than that!

## Software prerequisites ##
In order to reproduce one of the ConnectTheDots.io scenarios, you will need the following:

1. Microsoft Azure subscription ([free trial subscription](http://azure.microsoft.com/en-us/pricing/free-trial/) is sufficient)
1. [optional] Visual Studio 2013 or above – [Community Edition](http://www.visualstudio.com/downloads/download-visual-studio-vs) is sufficient. Note that if you are not planning to use the Gateway nor making changes to the dashboard, you will NOT need Visual Studio.
1. [optional] [WiX Toolset](http://wixtoolset.org) - if you want to build installer of Gateway for Windows

## Getting Started ##

To get started with ConnectTheDots, you will beed to go through the following basic steps:

1. [Deploying services](Azure/ARMTemplate/Readme.md): this is easily done using the automated deployment script.
2. [Setup devices](Devices/readme.md): follow these instructions to provision devices in the IoT Hub and modify and deploy code sample

## Available Devices ##
For a full list of devices and code samples check out the ever growing list of [supported gateways and sensors](SupportedDevices.md).


text:
<script src="<?php echo base_url(); ?>assets/libs/jquery/bootstrap/dist/js/bootstrap.js"></script>
<script src="<?php echo base_url(); ?>assets/js/ui-load.js"></script>
<script src="<?php echo base_url(); ?>assets/js/ui-jp.config.js"></script>
<script src="<?php echo base_url(); ?>assets/js/ui-jp.js"></script>
<script src="<?php echo base_url(); ?>assets/js/ui-nav.js"></script>
<script src="<?php echo base_url(); ?>assets/js/ui-toggle.js"></script>
<script src="<?php echo base_url(); ?>assets/js/ui-client.js"></script>
<script src="<?php echo base_url(); ?>assets/js/myscript.js?t=<?php echo time();?>"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.1/jquery-confirm.min.js"></script>


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.XR.iOS;
using UnityEngine.EventSystems;

public class laptopHit : MonoBehaviour {

	public GameObject screen1;
	public GameObject screen2;
	public GameObject screen3;
	//public GameObject bubblePrefab;
	private static GameObject laptopSelect = null;
	private static GameObject screenTwoSelect = null;

//	private bool secondActive = false;

	// Update is called once per frame
	void Update () {

		Debug.Log (Input.touchCount);

		int fingerCount = 0;
		foreach (Touch touch in Input.touches) {
			if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
				fingerCount++;
		}

		if (fingerCount > 0)
			print("User has " + fingerCount + " finger(s) touching the screen");

		if (Input.touchCount > 0) {

			Touch touch = Input.GetTouch (0);
			if (touch.phase == TouchPhase.Began  && !EventSystem.current.IsPointerOverGameObject(0)) {

				Ray ray = Camera.main.ScreenPointToRay (touch.position);
				RaycastHit hit;

				if (Physics.Raycast (ray, out hit, 100)) {

                    if (hit.transform.gameObject.tag == "laptop"){
						Debug.Log ("plz");

						laptopSelect = hit.transform.gameObject;
						screen1.SetActive (false);
						screen2.SetActive (true);

                    }

					else if (hit.transform.gameObject.tag == "screen2"){
						Debug.Log ("popp");
						screenTwoSelect = hit.transform.gameObject;
						screen2.SetActive (false);
						screen3.SetActive (true);
					}

				}
			}
		}

//		if (screen2.activeInHierarchy && hit.transform.gameObject.tag == "laptop"){
//			laptopSelect = hit.transform.gameObject;
//			//						Destroy(laptopSelect);
//			screen2.SetActive (false);
//			screen3.SetActive (true);
//		}
//		if (Input.touchCount > 1) {
//
//			Touch touch = Input.GetTouch (0);
//			if (touch.phase == TouchPhase.Began  && !EventSystem.current.IsPointerOverGameObject(0)) {
//				Ray ray = Camera.main.ScreenPointToRay (touch.position);
//				RaycastHit hit;
//
//				if (Physics.Raycast (ray, out hit, 100)) {
//
//					if (hit.transform.gameObject.tag == "laptop"){
//						laptopSelect = hit.transform.gameObject;
//						//						Destroy(laptopSelect);
//						screen2.SetActive (false);
//						screen3.SetActive (true);
//					}
//
//				}
//			}
//		}
	}
}