text:
		<link rel="stylesheet" type="/text/css" href="css/style.css">
		<link rel="stylesheet" href="/css/foundation.css">
  		<link rel="stylesheet" href="/css/app.css">

meetme

Menu

Plan a New Meeting!

Log Out

						Menu

Log Out

Add a Meeting

					    <form id="add-form">
					        Meeting Name: <input type="text" id="meeting_name">

					        Date:
Month/Day/Year ex)04/09/2015
<input type="text" id="date">

					        Time:
ex) 7 PM
<input type="text" id="time">

					        Location: <input type="text" id="location">

					        Description: <input type="text" id="description">

					        <button type="submit" class="button tiny" value="Submit">Submit</button>

					    </form>

Update Group

					<form id="update-form">
					    Meeting Name: <input type="text" id="meeting_name_update">

					    Date:
Month/Day/Year ex)04/09/2015
<input type="text" id="date_update">

					    Time:
ex) 7 PM
<input type="text" id="time_update">

					    Location: <input type="text" id="location_update">

					    Description: <input type="text" id="description_update">

					    <button type="submit" class="button tiny" value="Submit">Submit</buton>
					</form>


text:
using System.Collections.Generic;

namespace Paydock_dotnet_sdk.Models
{
    public abstract class ChargeRequestBase
    {
        public decimal amount { get; set; }
        public string currency { get; set; }
        public string token { get; set; }
        public string reference { get; set; }
        public string reference2 { get; set; }
        public string description { get; set; }
        public string descriptor { get; set; }
        public string customer_id { get; set; }
		public string payment_source_id { get; set; }
        public string fraud_charge_id { get; set; }
        public bool? bypass_3ds { get; set; }
        public Customer customer { get; set; }
        public ThreeDSecure  _3ds { get; set; }
        public FraudData fraud { get; set; }
        public ShippingData shipping { get; set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.gemstone.gemfire.internal.cache;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import com.gemstone.gemfire.internal.offheap.OffHeapRegionEntryHelper;
import com.gemstone.gemfire.internal.offheap.annotations.Released;
import com.gemstone.gemfire.internal.offheap.annotations.Retained;
import com.gemstone.gemfire.internal.offheap.annotations.Unretained;
import com.gemstone.gemfire.internal.util.concurrent.CustomEntryConcurrentHashMap.HashEntry;
// macros whose definition changes this class:
// disk: DISK
// lru: LRU
// stats: STATS
// versioned: VERSIONED
// offheap: OFFHEAP
// One of the following key macros must be defined:
// key object: KEY_OBJECT
// key int: KEY_INT
// key long: KEY_LONG
// key uuid: KEY_UUID
// key string1: KEY_STRING1
// key string2: KEY_STRING2
/**
 * Do not modify this class. It was generated.
 * Instead modify LeafRegionEntry.cpp and then run
 * bin/generateRegionEntryClasses.sh from the directory
 * that contains your build.xml.
 */
public class VMThinRegionEntryOffHeapObjectKey extends VMThinRegionEntryOffHeap {
  public VMThinRegionEntryOffHeapObjectKey (RegionEntryContext context, Object key,
      @Retained
      Object value
      ) {
    super(context,
          value
        );
    // DO NOT modify this class. It was generated from LeafRegionEntry.cpp
    this.key = key;
  }
  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp
  // common code
  protected int hash;
  private HashEntry<Object, Object> next;
  @SuppressWarnings("unused")
  private volatile long lastModified;
  private static final AtomicLongFieldUpdater<VMThinRegionEntryOffHeapObjectKey> lastModifiedUpdater
    = AtomicLongFieldUpdater.newUpdater(VMThinRegionEntryOffHeapObjectKey.class, "lastModified");
  /**
   * All access done using ohAddrUpdater so it is used even though the compiler can not tell it is.
   */
  @SuppressWarnings("unused")
  @Retained @Released private volatile long ohAddress;
  /**
   * I needed to add this because I wanted clear to call setValue which normally can only be called while the re is synced.
   * But if I sync in that code it causes a lock ordering deadlock with the disk regions because they also get a rw lock in clear.
   * Some hardware platforms do not support CAS on a long. If gemfire is run on one of those the AtomicLongFieldUpdater does a sync
   * on the re and we will once again be deadlocked.
   * I don't know if we support any of the hardware platforms that do not have a 64bit CAS. If we do then we can expect deadlocks
   * on disk regions.
   */
  private final static AtomicLongFieldUpdater<VMThinRegionEntryOffHeapObjectKey> ohAddrUpdater = AtomicLongFieldUpdater.newUpdater(VMThinRegionEntryOffHeapObjectKey.class, "ohAddress");
  @Override
  public Token getValueAsToken() {
    return OffHeapRegionEntryHelper.getValueAsToken(this);
  }
  @Override
  protected Object getValueField() {
    return OffHeapRegionEntryHelper._getValue(this);
  }
  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp
  @Override
  @Unretained
  protected void setValueField(@Unretained Object v) {
    OffHeapRegionEntryHelper.setValue(this, v);
  }
  @Override
  @Retained
  public Object _getValueRetain(RegionEntryContext context, boolean decompress) {
    return OffHeapRegionEntryHelper._getValueRetain(this, decompress, context);
  }
  @Override
  public long getAddress() {
    return ohAddrUpdater.get(this);
  }
  @Override
  public boolean setAddress(long expectedAddr, long newAddr) {
    return ohAddrUpdater.compareAndSet(this, expectedAddr, newAddr);
  }
  @Override
  @Released
  public void release() {
    OffHeapRegionEntryHelper.releaseEntry(this);
  }
  @Override
  public void returnToPool() {
    // Deadcoded for now; never was working
//    if (this instanceof VMThinRegionEntryLongKey) {
//      factory.returnToPool((VMThinRegionEntryLongKey)this);
//    }
  }
  protected long getlastModifiedField() {
    return lastModifiedUpdater.get(this);
  }
  protected boolean compareAndSetLastModifiedField(long expectedValue, long newValue) {
    return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
  }
  /**
   * @see HashEntry#getEntryHash()
   */
  public final int getEntryHash() {
    return this.hash;
  }
  protected void setEntryHash(int v) {
    this.hash = v;
  }
  /**
   * @see HashEntry#getNextEntry()
   */
  public final HashEntry<Object, Object> getNextEntry() {
    return this.next;
  }
  /**
   * @see HashEntry#setNextEntry
   */
  public final void setNextEntry(final HashEntry<Object, Object> n) {
    this.next = n;
  }
  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp
  // key code
  private final Object key;
  @Override
  public final Object getKey() {
    return this.key;
  }
  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Style">
        <attr name="menu_action_bar" format="color"/>
        <attr name="menu_text_color" format="color"/>
        <attr name="menu_text_color_disabled" format="color"/>
        <attr name="menu_background" format="color"/>
        <attr name="menu_active_background" format="color"/>
        <attr name="background" format="color"/>
        <attr name="holo_green" format="reference|color"/>
        <attr name="holo_orange" format="reference|color"/>
        <attr name="holo_red" format="reference|color"/>
        <attr name="holo_blue" format="reference|color"/>
        <attr name="text_color" format="color"/>
        <attr name="button_stateful" format="reference"/>
    </declare-styleable>
</resources>


text:
package main

import (
	"context"
	"flag"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/node"
	"github.com/ethereum/go-ethereum/p2p/enode"
	"github.com/ethereum/go-ethereum/p2p/simulations"
	"github.com/ethereum/go-ethereum/p2p/simulations/adapters"

	colorable "github.com/mattn/go-colorable"

	"./protocol"
	"./resource"
	"./service"
)

const (
	defaultMaxDifficulty   = 24
	defaultMinDifficulty   = 8
	defaultSubmitDelay     = time.Millisecond * 100
	defaultDataSize        = 32
	defaultMaxTime         = time.Second * 10
	defaultSimDuration     = time.Second * 5
	defaultMaxJobs         = 100
	defaultResourceApiHost = "http://localhost:8500"
)

var (
	loglevel      = flag.Bool("v", false, "loglevel")
	useResource   = flag.Bool("r", false, "use resource sink")
	ensAddr       = flag.String("e", "", "ens name to post resource update")
	maxDifficulty uint8
	minDifficulty uint8
	maxTime       time.Duration
	maxJobs       int
)

func init() {
	flag.Parse()
	if *loglevel {
		log.PrintOrigins(true)
		log.Root().SetHandler(log.LvlFilterHandler(log.LvlDebug, log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
	}

	maxDifficulty = defaultMaxDifficulty
	minDifficulty = defaultMinDifficulty
	maxTime = defaultMaxTime
	maxJobs = defaultMaxJobs

	adapters.RegisterServices(newServices())
}

func main() {
	a := adapters.NewSimAdapter(newServices())

	n := simulations.NewNetwork(a, &simulations.NetworkConfig{
		ID:             "protocol-demo",
		DefaultService: "demo",
	})
	defer n.Shutdown()

	var nids []enode.ID
	for i := 0; i < 5; i++ {
		c := adapters.RandomNodeConfig()
		nod, err := n.NewNodeWithConfig(c)
		if err != nil {
			log.Error(err.Error())
			return
		}
		nids = append(nids, nod.ID())
	}

	// TODO: need better assertion for network readiness
	n.StartAll()
	for i, nid := range nids {
		if i == 0 {
			continue
		}
		n.Connect(nids[0], nid)
	}

	go http.ListenAndServe(":8888", simulations.NewServer(n))

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

	quitC := make(chan struct{})
	trigger := make(chan enode.ID)
	events := make(chan *simulations.Event)
	sub := n.Events().Subscribe(events)
	// event sink on quit
	defer func() {
		sub.Unsubscribe()
		close(quitC)
		select {
		case <-events:
		default:
		}
		return
	}()

	action := func(ctx context.Context) error {
		for i, nid := range nids {
			if i == 0 {
				log.Info("appointed worker node", "node", nid.String())
				go func(nid enode.ID) {
					trigger <- nid
				}(nid)
				continue
			}
			client, err := n.GetNode(nid).Client()
			if err != nil {
				return err
			}
			err = client.Call(nil, "demo_setDifficulty", 0)
			if err != nil {
				return err
			}

			go func(nid enode.ID) {
				timer := time.NewTimer(defaultSimDuration)
				for {
					select {
					case <-events:
						continue
					case <-quitC:
						return
					case <-ctx.Done():
						return
					case <-timer.C:
					}
					log.Debug("stop sending", "node", nid)
					trigger <- nid
					return
				}
			}(nid)
		}
		return nil
	}
	check := func(ctx context.Context, nid enode.ID) (bool, error) {
		select {
		case <-ctx.Done():
		default:
		}
		log.Warn("ok", "nid", nid)
		return true, nil
	}

	ctx, cancel = context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()
	sim := simulations.NewSimulation(n)
	step := sim.Run(ctx, &simulations.Step{
		Action:  action,
		Trigger: trigger,
		Expect: &simulations.Expectation{
			Nodes: nids,
			Check: check,
		},
	})
	if step.Error != nil {
		log.Error(step.Error.Error())
	}
	for i, nid := range nids {
		if i == 0 {
			continue
		}
		log.Debug("stopping node", "nid", nid)
		n.Stop(nid)

	}
	sigC := make(chan os.Signal)
	signal.Notify(sigC, syscall.SIGINT)

	<-sigC

	return
}

func newServices() adapters.Services {
	haveWorker := false
	return adapters.Services{
		"demo": func(node *adapters.ServiceContext) (node.Service, error) {
			var resourceEnsName string
			if *ensAddr != "" {
				resourceEnsName = *ensAddr
			} else {
				resourceEnsName = fmt.Sprintf("%x.mutable.test", node.Config.ID[:])
			}
			resourceapi := resource.NewClient(defaultResourceApiHost, resourceEnsName)
			var sinkFunc service.ResultSinkFunc
			if *useResource {
				sinkFunc = resourceapi.ResourceSinkFunc()
			}
			params := service.NewDemoParams(sinkFunc, saveFunc)
			params.MaxJobs = maxJobs
			params.MaxTimePerJob = maxTime
			if !haveWorker {
				params.MaxDifficulty = maxDifficulty
				haveWorker = true
			}
			params.SubmitDelay = defaultSubmitDelay
			params.SubmitDataSize = defaultDataSize
			params.MaxSubmitDifficulty = defaultMaxDifficulty
			params.MinSubmitDifficulty = defaultMinDifficulty

			params.Id = node.Config.ID[:]
			return service.NewDemo(params)
		},
	}
}

func saveFunc(nid []byte, id protocol.ID, difficulty uint8, data []byte, nonce []byte, hash []byte) {
	fmt.Fprintf(os.Stdout, "RESULT >> %x/%x : %x@%d|%x => %x\n", nid[:8], id, data, difficulty, nonce, hash)
}


text:
#include "apr_buckets.h"

static apr_status_t socket_bucket_read(apr_bucket *a, const char **str,
                                       apr_size_t *len, apr_read_type_e block)
{
    apr_socket_t *p = a->data;
    char *buf;
    apr_status_t rv;
    apr_interval_time_t timeout;

    if (block == APR_NONBLOCK_READ) {
        apr_socket_timeout_get(p, &timeout);
        apr_socket_timeout_set(p, 0);
    }

    *str = NULL;
    *len = APR_BUCKET_BUFF_SIZE;
    buf = apr_bucket_alloc(*len, a->list); /* XXX: check for failure? */

    rv = apr_socket_recv(p, buf, len);

    if (block == APR_NONBLOCK_READ) {
        apr_socket_timeout_set(p, timeout);
    }

    if (rv != APR_SUCCESS && rv != APR_EOF) {
        apr_bucket_free(buf);
        return rv;
    }
    /*
     * If there's more to read we have to keep the rest of the socket
     * for later. XXX: Note that more complicated bucket types that
     * refer to data not in memory and must therefore have a read()
     * function similar to this one should be wary of copying this
     * code because if they have a destroy function they probably
     * want to migrate the bucket's subordinate structure from the
     * old bucket to a raw new one and adjust it as appropriate,
     * rather than destroying the old one and creating a completely
     * new bucket.
     *
     * Even if there is nothing more to read, don't close the socket here
     * as we have to use it to send any response :)  We could shut it
     * down for reading, but there is no benefit to doing so.
     */
    if (*len > 0) {
        apr_bucket_heap *h;
        /* Change the current bucket to refer to what we read */
        a = apr_bucket_heap_make(a, buf, *len, apr_bucket_free);
        h = a->data;
        h->alloc_len = APR_BUCKET_BUFF_SIZE; /* note the real buffer size */
        *str = buf;
        APR_BUCKET_INSERT_AFTER(a, apr_bucket_socket_create(p, a->list));
    }
    else {
        apr_bucket_free(buf);
        a = apr_bucket_immortal_make(a, "", 0);
        *str = a->data;
    }
    return APR_SUCCESS;
}

APU_DECLARE(apr_bucket *) apr_bucket_socket_make(apr_bucket *b, apr_socket_t *p)
{
    /*
     * XXX: We rely on a cleanup on some pool or other to actually
     * destroy the socket. We should probably explicitly call apr to
     * destroy it instead.
     *
     * Note that typically the socket is allocated from the connection pool
     * so it will disappear when the connection is finished.
     */
    b->type        = &apr_bucket_type_socket;
    b->length      = (apr_size_t)(-1);
    b->start       = -1;
    b->data        = p;

    return b;
}

APU_DECLARE(apr_bucket *) apr_bucket_socket_create(apr_socket_t *p,
                                                   apr_bucket_alloc_t *list)
{
    apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);

    APR_BUCKET_INIT(b);
    b->free = apr_bucket_free;
    b->list = list;
    return apr_bucket_socket_make(b, p);
}

APU_DECLARE_DATA const apr_bucket_type_t apr_bucket_type_socket = {
    "SOCKET", 5, APR_BUCKET_DATA,
    apr_bucket_destroy_noop,
    socket_bucket_read,
    apr_bucket_setaside_notimpl,
    apr_bucket_split_notimpl,
    apr_bucket_copy_notimpl
};


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>AmaranJS Examples</title>
	<link rel="stylesheet" href="http://www.amaranjs.com/AmaranJS/dist/css/amaran.min.css">
    <link rel="stylesheet" href="http://www.amaranjs.com/AmaranJS/dist/css/animate.min.css">
    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="global.css"/>

			<button id="start">Start</button>

Slide out effects are similar to slide in effects.

I will use fade effect  for 'in-effects' most of the examples.Dont forget to wait 3sec or you can click on notification.

$('#start').on('click',function(){
    $.amaran({
        'message'   :'My positioning example.',
        'position'  :'top left',
        'outEffect'  :'slideRight'
    });
});


text:
ReflectionProperty::__construct(): ensure inherited private props can't be accessed through ReflectionProperty.
--FILE--
<?php

class C {
	private $p = 1;

	static function testFromC() {
		try {
		  $rp = new ReflectionProperty("D", "p");
		  var_dump($rp);
		} catch (Exception $e) {
			echo $e->getMessage();
		}
	}
}

class D extends C{
	static function testFromD() {
		try {
		  $rp = new ReflectionProperty("D", "p");
		  var_dump($rp);
		} catch (Exception $e) {
			echo $e->getMessage();
		}
	}
}

echo "--> Reflect inherited private from global scope:\n";
try {
  $rp = new ReflectionProperty("D", "p");
  var_dump($rp);
} catch (Exception $e) {
	echo $e->getMessage();
}

echo "\n\n--> Reflect inherited private from declaring scope:\n";
C::testFromC();

echo "\n\n--> Reflect inherited private from declaring scope via subclass:\n";
D::testFromC();

echo "\n\n--> Reflect inherited private from subclass:\n";
D::testFromD();
?>
--EXPECTF--
--> Reflect inherited private from global scope:
Property D::$p does not exist

--> Reflect inherited private from declaring scope:
Property D::$p does not exist

--> Reflect inherited private from declaring scope via subclass:
Property D::$p does not exist

--> Reflect inherited private from subclass:
Property D::$p does not exist


text:
"""
Classes and interfaces for identifying non-overlapping linguistic
groups (such as base noun phrases) in unrestricted text.  This task is
called "chunk parsing" or "chunking", and the identified groups are
called "chunks".  The chunked text is represented using a shallow
tree called a "chunk structure."  A chunk structure is a tree
containing tokens and chunks, where each chunk is a subtree containing
only tokens.  For example, the chunk structure for base noun phrase
chunks in the sentence "I saw the big dog on the hill" is::

  (SENTENCE:
    (NP: <I>)
    <saw>
    (NP: <the> <big> <dog>)
    <on>
    (NP: <the> <hill>))

To convert a chunk structure back to a list of tokens, simply use the
chunk structure's ``leaves()`` method.

This module defines ``ChunkParserI``, a standard interface for
chunking texts; and ``RegexpChunkParser``, a regular-expression based
implementation of that interface. It also defines ``ChunkScore``, a
utility class for scoring chunk parsers.

RegexpChunkParser
=================

``RegexpChunkParser`` is an implementation of the chunk parser interface
that uses regular-expressions over tags to chunk a text.  Its
``parse()`` method first constructs a ``ChunkString``, which encodes a
particular chunking of the input text.  Initially, nothing is
chunked.  ``parse.RegexpChunkParser`` then applies a sequence of
``RegexpChunkRule`` rules to the ``ChunkString``, each of which modifies
the chunking that it encodes.  Finally, the ``ChunkString`` is
transformed back into a chunk structure, which is returned.

``RegexpChunkParser`` can only be used to chunk a single kind of phrase.
For example, you can use an ``RegexpChunkParser`` to chunk the noun
phrases in a text, or the verb phrases in a text; but you can not
use it to simultaneously chunk both noun phrases and verb phrases in
the same text.  (This is a limitation of ``RegexpChunkParser``, not of
chunk parsers in general.)

RegexpChunkRules
----------------

A ``RegexpChunkRule`` is a transformational rule that updates the
chunking of a text by modifying its ``ChunkString``.  Each
``RegexpChunkRule`` defines the ``apply()`` method, which modifies
the chunking encoded by a ``ChunkString``.  The
``RegexpChunkRule`` class itself can be used to implement any
transformational rule based on regular expressions.  There are
also a number of subclasses, which can be used to implement
simpler types of rules:

    - ``ChunkRule`` chunks anything that matches a given regular
      expression.
    - ``ChinkRule`` chinks anything that matches a given regular
      expression.
    - ``UnChunkRule`` will un-chunk any chunk that matches a given
      regular expression.
    - ``MergeRule`` can be used to merge two contiguous chunks.
    - ``SplitRule`` can be used to split a single chunk into two
      smaller chunks.
    - ``ExpandLeftRule`` will expand a chunk to incorporate new
      unchunked material on the left.
    - ``ExpandRightRule`` will expand a chunk to incorporate new
      unchunked material on the right.

Tag Patterns
~~~~~~~~~~~~

A ``RegexpChunkRule`` uses a modified version of regular
expression patterns, called "tag patterns".  Tag patterns are
used to match sequences of tags.  Examples of tag patterns are::

     r'(<DT>|<JJ>|<NN>)+'
     r'<NN>+'
     r'<NN.*>'

The differences between regular expression patterns and tag
patterns are:

    - In tag patterns, ``'<'`` and ``'>'`` act as parentheses; so
      ``'<NN>+'`` matches one or more repetitions of ``'<NN>'``, not
      ``'<NN'`` followed by one or more repetitions of ``'>'``.
    - Whitespace in tag patterns is ignored.  So
      ``'<DT> | <NN>'`` is equivalant to ``'<DT>|<NN>'``
    - In tag patterns, ``'.'`` is equivalant to ``'[^{}<>]'``; so
      ``'<NN.*>'`` matches any single tag starting with ``'NN'``.

The function ``tag_pattern2re_pattern`` can be used to transform
a tag pattern to an equivalent regular expression pattern.

Efficiency
----------

Preliminary tests indicate that ``RegexpChunkParser`` can chunk at a
rate of about 300 tokens/second, with a moderately complex rule set.

There may be problems if ``RegexpChunkParser`` is used with more than
5,000 tokens at a time.  In particular, evaluation of some regular
expressions may cause the Python regular expression engine to
exceed its maximum recursion depth.  We have attempted to minimize
these problems, but it is impossible to avoid them completely.  We
therefore recommend that you apply the chunk parser to a single
sentence at a time.

Emacs Tip
---------

If you evaluate the following elisp expression in emacs, it will
colorize a ``ChunkString`` when you use an interactive python shell
with emacs or xemacs ("C-c !")::

    (let ()
      (defconst comint-mode-font-lock-keywords
        '(("<[^>]+>" 0 'font-lock-reference-face)
          ("[{}]" 0 'font-lock-function-name-face)))
      (add-hook 'comint-mode-hook (lambda () (turn-on-font-lock))))

You can evaluate this code by copying it to a temporary buffer,
placing the cursor after the last close parenthesis, and typing
"``C-x C-e``".  You should evaluate it before running the interactive
session.  The change will last until you close emacs.

Unresolved Issues
-----------------

If we use the ``re`` module for regular expressions, Python's
regular expression engine generates "maximum recursion depth
exceeded" errors when processing very large texts, even for
regular expressions that should not require any recursion.  We
therefore use the ``pre`` module instead.  But note that ``pre``
does not include Unicode support, so this module will not work
with unicode strings.  Note also that ``pre`` regular expressions
are not quite as advanced as ``re`` ones (e.g., no leftward
zero-length assertions).

:type CHUNK_TAG_PATTERN: regexp
:var CHUNK_TAG_PATTERN: A regular expression to test whether a tag
     pattern is valid.
"""

from nltk.data import load

from nltk.chunk.api import ChunkParserI
from nltk.chunk.util import (ChunkScore, accuracy, tagstr2tree, conllstr2tree,
                             tree2conlltags, tree2conllstr, tree2conlltags,
                             ieerstr2tree)
from nltk.chunk.regexp import RegexpChunkParser, RegexpParser

# Standard treebank POS tagger
_BINARY_NE_CHUNKER = 'chunkers/maxent_ne_chunker/english_ace_binary.pickle'
_MULTICLASS_NE_CHUNKER = 'chunkers/maxent_ne_chunker/english_ace_multiclass.pickle'

def ne_chunk(tagged_tokens, binary=False):
    """
    Use NLTK's currently recommended named entity chunker to
    chunk the given list of tagged tokens.
    """
    if binary:
        chunker_pickle = _BINARY_NE_CHUNKER
    else:
        chunker_pickle = _MULTICLASS_NE_CHUNKER
    chunker = load(chunker_pickle)
    return chunker.parse(tagged_tokens)

def batch_ne_chunk(tagged_sentences, binary=False):
    """
    Use NLTK's currently recommended named entity chunker to chunk the
    given list of tagged sentences, each consisting of a list of tagged tokens.
    """
    if binary:
        chunker_pickle = _BINARY_NE_CHUNKER
    else:
        chunker_pickle = _MULTICLASS_NE_CHUNKER
    chunker = load(chunker_pickle)
    return chunker.batch_parse(tagged_sentences)


text:
Chicago
=======

Chicago is a small-scale data warehouse library written in Ruby.

This library focuses on the following:

* Defining a model that represents a Star Schema.
* Creation of migrations to manipulate one or more concrete database
  schemas to reflect the model.
* Querying data in a Star Schema.

It heavily uses and is influenced by the
[sequel](http://sequel.jeremyevans.net/) library. This library itself provides no ETL functionality; there is a highly unfinished/experimental library for this at [chicago-etl](http://github.com/notonthehighstreet/chicago-etl)

Installation
------------

    gem install chicagowarehouse

Star Schema Features
--------------------

If you are new to star schemas in general, I recommend reading [The
Data Warehouse
Toolkit](http://www.amazon.co.uk/The-Data-Warehouse-Toolkit-Dimensional/dp/0471200247)
by Ralph Kimball & Margy Ross. Briefly though, a star schema is a
sem-denormalised style of database design optimized for
reporting-style queries. In a star schema, there are two types of
tables:

* **Fact tables** store *measures* that can be summed or averaged,
    together with keys to Dimensions.
* **Dimension tables** store denormalised data with which you may want
    to group or filter facts.

Generally speaking, the only links are between 1 fact table and
several dimension tables: facts are not joined to facts, dimensions
are not joined to dimensions - this gives the star schema its name, as
you can see in the picture below:

![Star Schema](/docimages/starschema.png?raw=true)

Not all standard star schema features are implemented yet - probably
the most important ommission is that Type II and Type III dimensions
are not supported (dimensions that retain historic information).

Features that *are* supported include:

* Fact & Type I Dimensions tables
* Measures, additive & semi-additive
* Degenerate Dimensions
* Null Records
* Dimensions with predetermined values
* Key tables for ETL processes, supporting both single integer keys
  and hash keys for dimensions without an original primary key
* Calculated columns

Example Usage
-------------

Defining models:

```ruby
require 'chicago'

SCHEMA = Chicago::StarSchema.new

SCHEMA.define_dimension(:product) do
  columns do
    integer :original_id
    string :name, :default => "Unknown Product"
    money :price
    # ...
  end

  identified_by :name
  natural_key :original_id
  null_record :original_id => 0
end

# ...

SCHEMA.define_fact(:sales) do
  dimensions :product, :customer

  degenerate_dimensions do
    integer :order_id
  end

  measures do
    money :total
    integer :number_of_items
  end
end
```

Once you have a schema defined, you can use the inbuilt tasks to
create the underlying database schema in your Rakefile:

```ruby
DB = Sequel.connect() # with your db connection parameters
Chicago::RakeTasks.new(SCHEMA, :staging_db => DB)
```

Which gives the following tasks:

* `db:write_migrations` - creates migration files in a migrations
  directory - use the standard Sequel migration tool to run them;
* `db:create_null_records` - creates null records in the database.

After you have some data, you can query your schema like so:

```ruby
query = {
  :table_name => "sales",
  :query_type => "fact",
  :columns => ["sales.product.name",
               {:column => "sales.total", :op => "sum"}]
}

sequel_dataset = Chicago::Query.new(SCHEMA, query).dataset

# Do whatever you like with this dataset, for example just returning
# all records:
sequel_dataset.all
```

The query hash is intended to be easy to represent in JSON. Notice how
unlike just using base Sequel, you didn't have to define any `JOIN` or
`GROUP BY` parts to the query - these are inferred from the model.

Contributing
------------

To get specs passing, you'll need to create a test myqsl database, and
copy spec/database.yml.dist to spec/database.yml and populate it
appropriately.


text:
<?php

namespace Galerie\Mail;

use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
use Zend\Mail\Message;

use Zend\Mime\Part as MimePart;
use Zend\Mime\Mime as Mime;
use Zend\Mime\Message as MimeMessage;

class MailSender
{

    protected static $transport = null;

    public static function initialize($params)
    {
        static::$transport = new SmtpTransport();
        $smtpOption=new SmtpOptions();

        $smtpOption->setHost($params['host'])
                    ->setConnectionClass($params['auth'])
                    ->setName($params['host'])
                    ->setConnectionConfig(array(
                        'username' => $params['username'],
                        'password' => $params['password'],
                        'ssl' => $params['ssl'],
                    ));

        static::$transport->setOptions($smtpOption);
    }

    public function send(
        $sender, $sender_name, $to, $to_name, $subject, $text_body, $html_body, $logo
    ) {
        // Création de la partie texte
        $text = new MimePart($text_body);
        $text->type = Mime::TYPE_TEXT;

        // Création de la partie HTML
        $html = new MimePart($html_body);
        $html->type = Mime::TYPE_HTML;

        // Création du message
        $body = new MimeMessage();
        $body->setParts(array($text, $html));

        $mail = new Message();
        $mail->setBody($body);
        $mail->setFrom($sender, $sender_name);
        $mail->addTo($to, $to_name);
        $mail->setSubject($subject);

        static::$transport->send($mail);
    }

}


text:
module ActiveStorage
  class Downloader #:nodoc:
    def initialize(blob, tempdir: nil)
      @blob    = blob
      @tempdir = tempdir
    end

    def download_blob_to_tempfile
      open_tempfile do |file|
        download_blob_to file
        verify_integrity_of file
        yield file
      end
    end

    private
      attr_reader :blob, :tempdir

      def open_tempfile
        file = Tempfile.open([ "ActiveStorage-#{blob.id}-", blob.filename.extension_with_delimiter ], tempdir)

        begin
          yield file
        ensure
          file.close!
        end
      end

      def download_blob_to(file)
        file.binmode
        blob.download { |chunk| file.write(chunk) }
        file.flush
        file.rewind
      end

      def verify_integrity_of(file)
        unless Digest::MD5.file(file).base64digest == blob.checksum
          raise ActiveStorage::IntegrityError
        end
      end
  end
end


text:
package org.netbeans.cubeon.debugger.bridge;

import org.netbeans.api.debugger.Breakpoint;
import org.netbeans.api.debugger.DebuggerManager;
import org.netbeans.api.debugger.DebuggerManagerAdapter;
import org.netbeans.cubeon.tasks.core.api.CubeonContext;
import org.netbeans.cubeon.tasks.core.api.CubeonContextListener;
import org.netbeans.cubeon.tasks.spi.task.TaskElement;
import org.openide.modules.ModuleInstall;
import org.openide.util.Lookup;

/**
 * Manages a module's lifecycle. Remember that an installer is optional and
 * often not needed at all.
 */
public class Installer extends ModuleInstall {

    @Override
    public void restored() {
        final DebuggerManager debuggerManager = DebuggerManager.getDebuggerManager();
        final CubeonContext context = Lookup.getDefault().lookup(CubeonContext.class);
        assert context != null;

        context.addContextListener(new CubeonContextListener() {

            public void taskActivated(TaskElement task) {
                Breakpoint[] breakpoints = debuggerManager.getBreakpoints();
                for (Breakpoint breakpoint : breakpoints) {
                    if (isAssosoateBreakPoint(task, breakpoint)) {
                        breakpoint.enable();
                    }
                }
            }

            public void taskDeactivated(TaskElement task) {
                Breakpoint[] breakpoints = debuggerManager.getBreakpoints();
                for (Breakpoint breakpoint : breakpoints) {
                    if (isAssosoateBreakPoint(task, breakpoint)) {
                        breakpoint.disable();
                    }
                }
            }
        });

        debuggerManager.addDebuggerListener(new DebuggerManagerAdapter() {

            @Override
            public void breakpointAdded(Breakpoint breakpoint) {
                if (context.getActive() != null) {

                    breakpoint.setGroupName(encodeGroupName(context.getActive()));
                }
            }
        });

    }

    private boolean isAssosoateBreakPoint(TaskElement task, Breakpoint breakpoint) {
        String displayName = task.getDisplayName();
        String decodeGroupName = decodeGroupName(task);
        //check for both decode group name and display name to backward compatibility
        return breakpoint.getGroupName().startsWith(decodeGroupName) || displayName.equals(breakpoint.getGroupName());
    }

    private String encodeGroupName(TaskElement task) {

        String groupName = decodeGroupName(task) +
                " - " + task.getDescription();

        return groupName.trim();

    }

    private String decodeGroupName(TaskElement task) {
        String repoId = task.getTaskRepository().getId();
        return repoId + ":" + task.getId();
    }
}


text:
"""
The ActionChains implementation
"""
from selenium.webdriver.remote.command import Command
from selenium.webdriver.common.keys import Keys

class ActionChains(object):
    """
    Generate user actions.
    All actions are stored in the ActionChains object. Call perform() to fire
    stored actions.
    """

    def __init__(self, driver):
        """
        Creates a new ActionChains.

        :Args:
         - driver: The WebDriver instance which performs user actions.
        """
        self._driver = driver
        self._actions = []

    def perform(self):
        """
        Performs all stored actions.
        """
        for action in self._actions:
            action()

    def click(self, on_element=None):
        """
        Clicks an element.

        :Args:
         - on_element: The element to click.
           If None, clicks on current mouse position.
        """
        if on_element: self.move_to_element(on_element)
        self._actions.append(lambda:
            self._driver.execute(Command.CLICK, {'button': 0}))
        return self

    def click_and_hold(self, on_element):
        """
        Holds down the left mouse button on an element.

        :Args:
         - on_element: The element to mouse down.
           If None, clicks on current mouse position.
        """
        if on_element: self.move_to_element(on_element)
        self._actions.append(lambda:
            self._driver.execute(Command.MOUSE_DOWN, {}))
        return self

    def context_click(self, on_element):
        """
        Performs a context-click (right click) on an element.

        :Args:
         - on_element: The element to context-click.
           If None, clicks on current mouse position.
        """
        if on_element: self.move_to_element(on_element)
        self._actions.append(lambda:
            self._driver.execute(Command.CLICK, {'button': 2}))
        return self

    def double_click(self, on_element):
        """
        Double-clicks an element.

        :Args:
         - on_element: The element to double-click.
           If None, clicks on current mouse position.
        """
        if on_element: self.move_to_element(on_element)
        self._actions.append(lambda:
            self._driver.execute(Command.DOUBLE_CLICK, {}))
        return self

    def drag_and_drop(self, source, target):
        """Holds down the left mouse button on the source element,
           then moves to the target element and releases the mouse button.

        :Args:
         - source: The element to mouse down.
         - target: The element to mouse up.
        """
        self.click_and_hold(source)
        self.release(target)
        return self

    def drag_and_drop_by_offset(self, source, xoffset, yoffset):
        """
        Holds down the left mouse button on the source element,
           then moves to the target element and releases the mouse button.

        :Args:
         - source: The element to mouse down.
         - xoffset: X offset to move to.
         - yoffset: Y offset to move to.
        """
        self.click_and_hold(source)
        self.move_by_offset(xoffset, yoffset)
        self.release(source)
        return self

    def key_down(self, value, element=None):
        """Sends a key press only, without releasing it.
        Should only be used with modifier keys (Control, Alt and Shift).

        :Args:
         - key: The modifier key to send. Values are defined in Keys class.
         - target: The element to send keys.
           If None, sends a key to current focused element.
        """
        typing = []
        for val in value:
            if isinstance(val, Keys):
                typing.append(val)
            elif isinstance(val, int):
                val = str(val)
                for i in range(len(val)):
                    typing.append(val[i])
            else:
                for i in range(len(val)):
                    typing.append(val[i])

        if element: self.click(element)
        self._actions.append(lambda:
            self._driver.execute(Command.SEND_KEYS_TO_ACTIVE_ELEMENT, {
                "value": typing }))
        return self

    def key_up(self, value, element=None):
        """
        Releases a modifier key.

        :Args:
         - key: The modifier key to send. Values are defined in Keys class.
         - target: The element to send keys.
           If None, sends a key to current focused element.
        """
        typing = []
        for val in value:
            if isinstance(val, Keys):
                typing.append(val)
            elif isinstance(val, int):
                val = str(val)
                for i in range(len(val)):
                    typing.append(val[i])
            else:
                for i in range(len(val)):
                    typing.append(val[i])

        if element: self.click(element)
        self._actions.append(lambda:
            self._driver.execute(Command.SEND_KEYS_TO_ACTIVE_ELEMENT, {
                "value": typing }))
        return self

    def move_by_offset(self, xoffset, yoffset):
        """
        Moving the mouse to an offset from current mouse position.

        :Args:
         - xoffset: X offset to move to.
         - yoffset: Y offset to move to.
        """
        self._actions.append(lambda:
            self._driver.execute(Command.MOVE_TO, {
                'xoffset': xoffset,
                'yoffset': yoffset}))
        return self

    def move_to_element(self, to_element):
        """
        Moving the mouse to the middle of an element.

        :Args:
         - to_element: The element to move to.
        """
        self._actions.append(lambda:
            self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
        return self

    def move_to_element_with_offset(self, to_element, xoffset, yoffset):
        """
        Move the mouse by an offset of the specificed element.
        Offsets are relative to the top-left corner of the element.

        :Args:
         - to_element: The element to move to.
         - xoffset: X offset to move to.
         - yoffset: Y offset to move to.
        """
        self._actions.append(lambda:
            self._driver.execute(Command.MOVE_TO, {
                'element': to_element.id,
                'xoffset': xoffset,
                'yoffset': yoffset}))
        return self

    def release(self, on_element):
        """
        Releasing a held mouse button.

        :Args:
         - on_element: The element to mouse up.
        """
        if on_element: self.move_to_element(on_element)
        self._actions.append(lambda:
            self._driver.execute(Command.MOUSE_UP, {}))
        return self

    def send_keys(self, *keys_to_send):
        """Sends keys to current focused element.

        :Args:
         - keys_to_send: The keys to send.
        """
        self._actions.append(lambda:
            self._driver.switch_to_active_element().send_keys(*keys_to_send))
        return self

    def send_keys_to_element(self, element, *keys_to_send):
        """
        Sends keys to an element.

        :Args:
         - element: The element to send keys.
         - keys_to_send: The keys to send.
        """
        self._actions.append(lambda:
            element.send_keys(*keys_to_send))
        return self


text:
#ifndef _ASM_SCORE_RESOURCE_H
#define _ASM_SCORE_RESOURCE_H

#include <asm-generic/resource.h>

#endif /* _ASM_SCORE_RESOURCE_H */


text:
module.exports = function() {
  if(arguments.length < 1) {
    return null;
  }

  var args = [];
  if(arguments.length > 1) {
    args = Array.prototype.slice.apply(arguments).slice(0, arguments.length-1);
  }

  var callback = arguments[ arguments.length-1 ];
  return callback.apply(this, args);
};


text:
'use strict'

const util = require('util')
const Readable = require('stream').Readable
const check = require('check-types')

util.inherits(BfjStream, Readable)

module.exports = BfjStream

function BfjStream (read, options) {
  if (check.not.instanceStrict(this, BfjStream)) {
    return new BfjStream(read)
  }

  check.assert.function(read, 'Invalid read implementation')

  this._read = function () { // eslint-disable-line no-underscore-dangle
    read()
  }

  return Readable.call(this, options)
}


text:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>Test Page for sap.m.Button</title>
<script id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal"
	type="text/javascript" data-sap-ui-noConflict="true" data-sap-ui-language="en"
	data-sap-ui-libs="sap.m" src="../../../../resources/sap-ui-core.js">
</script>

<link rel="stylesheet" href="../../../../resources/sap/ui/thirdparty/qunit.css" type="text/css" media="screen">
<script type="text/javascript" src="../../../../resources/sap/ui/thirdparty/qunit.js"></script>
<script type="text/javascript" src="../../../../resources/sap/ui/qunit/qunit-junit.js"></script>
<script type="text/javascript" src="../../../../resources/sap/ui/qunit/qunit-coverage.js"></script>
<script type="text/javascript" src="../../../../resources/sap/ui/qunit/QUnitUtils.js"></script>
<script src="../../../../resources/sap/ui/thirdparty/sinon.js"></script>
<script src="../../../../resources/sap/ui/thirdparty/sinon-qunit.js"></script>

<style type="text/css">
.ButtonSpace {
	margin-top: 10px;
}
</style>

<script type="text/javascript">
	sinon.config.useFakeTimers = true;

	var b1, b2, b4, b5, b6, b7, b8, b9, b10, msg;

	var sText = "Button Text",
		sButtonTypeDefault = sap.m.ButtonType.Default,
		sButtonTypeBack = sap.m.ButtonType.Back,
		sButtonTypeAccept = sap.m.ButtonType.Accept,
		sButtonTypeReject = sap.m.ButtonType.Reject,
		sButtonTypeTransparent = sap.m.ButtonType.Transparent,
		sButtonTypeUp = sap.m.ButtonType.Up,
		sButtonTypeUnstyled = sap.m.ButtonType.Unstyled,
		sWidth = "200px",
		bEnabled = true,
		bDisabled = false,
		sIcon = "../images/analytics_64.png",
		sPressMessage = "Button Tapped Event!";

	function tabEventHandler1() {
		throw sPressMessage + " - Exception"
	}

	function tabEventHandler2() {
		msg = sPressMessage
	}

	// Default Button
	var oBtnDefault = new sap.m.Button("b1");
	oBtnDefault.setText(sText);
	oBtnDefault.setType(sButtonTypeDefault);
	oBtnDefault.setEnabled(bEnabled);
	oBtnDefault.attachPress(tabEventHandler1);
	oBtnDefault.placeAt("contentBtnDefault");

	// Back Button
	var oBtnBack = new sap.m.Button("b2");
	oBtnBack.setText("Back Button");
	oBtnBack.setType(sButtonTypeBack);
	oBtnBack.setEnabled(bEnabled);
	oBtnBack.attachPress(tabEventHandler2);
	oBtnBack.placeAt("contentBtnBack");

	// Accept Button
	var oBtnAccept = new sap.m.Button("b4");
	oBtnAccept.setText("Accept Button");
	oBtnAccept.setType(sButtonTypeAccept);
	oBtnAccept.setEnabled(bEnabled);
	oBtnAccept.attachPress(tabEventHandler2);
	oBtnAccept.placeAt("contentBtnAccept");

	// Reject Button
	var oBtnReject = new sap.m.Button("b5");
	oBtnReject.setText("Reject Button");
	oBtnReject.setType(sButtonTypeReject);
	oBtnReject.setEnabled(bEnabled);
	oBtnReject.attachPress(tabEventHandler2);
	oBtnReject.placeAt("contentBtnReject");

	// Transparent Button
	var oBtnTransparent = new sap.m.Button("b6");
	oBtnTransparent.setText("Transparent Button");
	oBtnTransparent.setType(sButtonTypeTransparent);
	oBtnTransparent.setEnabled(bEnabled);
	oBtnTransparent.attachPress(tabEventHandler2);
	oBtnTransparent.placeAt("contentBtnTransparent");

	// Button Width
	var oBtnWidth = new sap.m.Button("b7");
	oBtnWidth.setText("Button with 200 pixel");
	oBtnWidth.setType(sButtonTypeDefault);
	oBtnWidth.setEnabled(bEnabled);
	oBtnWidth.setWidth(sWidth);
	oBtnWidth.attachPress(tabEventHandler2);
	oBtnWidth.placeAt("contentBtnWidth");

	// Disabled Button
	var oBtnDisabled = new sap.m.Button("b8");
	oBtnDisabled.setText("Disabled Button");
	oBtnDisabled.setType(sButtonTypeDefault);
	oBtnDisabled.setEnabled(bDisabled);
	oBtnDisabled.setWidth(sWidth);
	oBtnDisabled.attachPress(tabEventHandler2);
	oBtnDisabled.placeAt("contentBtnDisabled");

	// Icon Button
	var oBtnIcon = new sap.m.Button("b9");
	oBtnIcon.setText("Icon Button");
	oBtnIcon.setType(sButtonTypeDefault);
	oBtnIcon.setEnabled(bEnabled);
	oBtnIcon.setIcon(sIcon);
	oBtnIcon.attachPress(tabEventHandler2);
	oBtnIcon.placeAt("contentBtnIcon");

	// Up Button
	var oBtnUp = new sap.m.Button("b10");
	oBtnUp.setText("Up Button");
	oBtnUp.setType(sButtonTypeUp);
	oBtnUp.setEnabled(bEnabled);
	oBtnUp.attachPress(tabEventHandler2);
	oBtnUp.placeAt("contentBtnUp");

	// Unstyled Button
	var oBtnUp = new sap.m.Button("b11");
	oBtnUp.setText("Unstyled Button");
	oBtnUp.setType(sButtonTypeUnstyled);
	oBtnUp.setEnabled(bEnabled);
	oBtnUp.attachPress(tabEventHandler2);
	oBtnUp.placeAt("contentBtnUnstyled");

	// Invisible Button
	var oBtnUp = new sap.m.Button("b12");
	oBtnUp.setText("Invisible Button");
	oBtnUp.setVisible(false);
	oBtnUp.placeAt("contentBtnInvisible");

	// RTL Button
	var oBtnRtl = new sap.m.Button("b13");
	oBtnRtl.setText("Button TextDirection RTL");
	oBtnRtl.setIcon(sap.ui.core.IconPool.getIconURI("employee"));
	oBtnRtl.setTextDirection(sap.ui.core.TextDirection.RTL);
	oBtnRtl.placeAt("contentBtnTextDirectionRTL");

	// LTR Button
	var oBtnLtr = new sap.m.Button("b14");
	oBtnLtr.setText("Button TextDirection LTR");
	oBtnLtr.setIcon(sap.ui.core.IconPool.getIconURI("employee"));
	oBtnLtr.setTextDirection(sap.ui.core.TextDirection.LTR);
	oBtnLtr.placeAt("contentBtnTextDirectionLTR");

	qutils.delayTestStart();

	module("Basic", {
		beforeEach : function() {
			b1 = sap.ui.getCore().byId("b1");
			b2 = sap.ui.getCore().byId("b2");
			b4 = sap.ui.getCore().byId("b4");
			b5 = sap.ui.getCore().byId("b5");
			b6 = sap.ui.getCore().byId("b6");
			b7 = sap.ui.getCore().byId("b7");
			b8 = sap.ui.getCore().byId("b8");
			b9 = sap.ui.getCore().byId("b9");
			b10 = sap.ui.getCore().byId("b10");
			b11 = sap.ui.getCore().byId("b11");
			b12 = sap.ui.getCore().byId("b12");
			b13 = sap.ui.getCore().byId("b13");
			b14 = sap.ui.getCore().byId("b14");
		},
		afterEach : function() {
			b1 = null;
			b2 = null;
			b4 = null;
			b5 = null;
			b6 = null;
			b7 = null;
			b8 = null;
			b9 = null;
			b10 = null;
			b11 = null;
			b12 = null;
			b13 = null;
			b14 = null;
		}
	});

	// test property accessor methods
	test("TextOk", function() {
		equals(b1.getText(), sText, "Text - button1 is correct using 'equals()'!");
	});

	test("TypeOk", function() {
		equals(b1.getType(), sButtonTypeDefault, "Button Type: Default - button1 is correct using 'equals()'!");
		equals(b2.getType(), sButtonTypeBack, "Button Type: Back - button2 is correct using 'equals()'!");
		equals(b4.getType(), sButtonTypeAccept, "Button Type: Accept - button4 is correct using 'equals()'!");
		equals(b5.getType(), sButtonTypeReject, "Button Type: Reject - button5 is correct using 'equals()'!");
		equals(b6.getType(), sButtonTypeTransparent, "Button Type: Transparent - button6 is correct using 'equals()'!");
		equals(b10.getType(), sButtonTypeUp, "Button Type: Up - button10 is correct using 'equals()'!");
		equals(b11.getType(), sButtonTypeUnstyled, "Button Type: Uunstyle - button11 is correct using 'equals()'!");
	});

	test("ButtonEnabledOk", function() {
		equals(b1.getEnabled(), bEnabled, "Button is enabled - button1 is correct using 'equals()'!");
		equals(b2.getEnabled(), bEnabled, "Button is enabled - button2 is correct using 'equals()'!");
		equals(b4.getEnabled(), bEnabled, "Button is enabled - button4 is correct using 'equals()'!");
		equals(b5.getEnabled(), bEnabled, "Button is enabled - button5 is correct using 'equals()'!");
		equals(b6.getEnabled(), bEnabled, "Button is enabled - button6 is correct using 'equals()'!");
		equals(b7.getEnabled(), bEnabled, "Button is enabled - button7 is correct using 'equals()'!");
		equals(b8.getEnabled(), bDisabled, "Button is disabled - button8 is correct using 'equals()'!");
		equals(b9.getEnabled(), bEnabled, "Button is enabled - button9 is correct using 'equals()'!");
		equals(b10.getEnabled(), bEnabled, "Button is enabled - button10 is correct using 'equals()'!");
	});

	test("ButtonWidthOk", function() {
		equals(b7.getWidth(), sWidth, "Button width - button7 is correct using 'equals()'!");
	});

	test("IconOk", function() {
		equals(b9.getIcon(), sIcon, "Icon for button9 is correct using 'equals()'!");
	});

	test("TextDirectionRtlOk", function() {
		var $btnText = jQuery(b13.getDomRef()).find('.sapMBtnContent');
		equals($btnText.attr("dir"), "rtl", "Control text has 'dir' property set to right-to-left");
	});

	test("TextDirectionLtrOk", function() {
		var $btnText = jQuery(b14.getDomRef()).find('.sapMBtnContent');
		equals($btnText.attr("dir"), "ltr", "Control text has 'dir' property set to left-to-right");
	});

	test("PressOk", function() {
		try {
			b1.firePress();
			ok(false,"Exception should have been thrown!");
		} catch (e) {
			ok(e == sPressMessage + " - Exception","Button1 - Exception was thrown correctly!");
			equals(e,sPressMessage + " - Exception","Button1 - Exception was thrown correctly!")
		}
		b2.firePress();
		ok(msg == sPressMessage, "Button2 - Event was fired correctly!");
		equals(msg, sPressMessage, "Button2 - Event was fired correctly!!");
		b4.firePress();
		ok(msg == sPressMessage, "Button4 - Event was fired correctly!");
		equals(msg, sPressMessage, "Button4 - Event was fired correctly!!");
		b5.firePress();
		ok(msg == sPressMessage, "Button5 - Event was fired correctly!");
		equals(msg, sPressMessage, "Button5 - Event was fired correctly!!");
		b6.firePress();
		ok(msg == sPressMessage, "Button6 - Event was fired correctly!");
		equals(msg, sPressMessage, "Button6 - Event was fired correctly!!");
		b7.firePress();
		ok(msg == sPressMessage, "Button7 - Event was fired correctly!");
		equals(msg, sPressMessage, "Button7 - Event was fired correctly!!");
	});

	test("Visibility", function(){
		ok(!jQuery.sap.domById("b12"), "Button12 should not be rendered");
	});

	function hoverableTestCase (oTestDescription) {
		this.stub(sap.ui.Device, "system", { desktop : oTestDescription.desktop });

		// System under Test
		var oButton = new sap.m.Button({
			enabled : oTestDescription.enabled
		});
		oButton.placeAt("qunit-fixture");
		sap.ui.getCore().applyChanges();

		// Act
		var bHoverable = oButton._isHoverable();

		// Assert
		strictEqual(bHoverable, oTestDescription.shouldBeHoverable, "The button determined wether is should be hoverable");
		strictEqual(oButton.$("inner").hasClass("sapMBtnHoverable"), oTestDescription.shouldHaveCssClass, "The button determined wether is should be hoverable");
	}

	test("Should be hoverable if the button is enabled and in desktop", function() {
		hoverableTestCase.call(this, {
			enabled : true,
			desktop : true,
			shouldBeHoverable : true,
			shouldHaveCssClass : true
		});
	});

	test("Should not be hoverable if the button is disabled and in desktop", function() {
		hoverableTestCase.call(this, {
			enabled : false,
			desktop : true,
			shouldBeHoverable : false,
			shouldHaveCssClass : false
		});
	});

	test("Should not be hoverable if the button is enabled and not desktop", function() {
		hoverableTestCase.call(this, {
			enabled : true,
			desktop : false,
			shouldBeHoverable : false,
			shouldHaveCssClass : false
		});
	});

	test("Should not be hoverable if the button is disabled and not desktop", function() {
		hoverableTestCase.call(this, {
			enabled : false,
			desktop : false,
			shouldBeHoverable : false,
			shouldHaveCssClass : false
		});
	});

	test("Should not re-render the button if the text is changed", function() {
		// Arrange
		var sTextToSet = "<script>alert(\"HAACKED\");<\/script>",
			oRenderSpy,
			oResult,
			oConstructor = { text : "No empty text"};

		// System under Test
		var oButton = new sap.m.Button(oConstructor).placeAt("qunit-fixture");
		sap.ui.getCore().applyChanges();

		oRenderSpy = this.spy(oButton, "invalidate");

		// Act
		oResult = oButton.setText(sTextToSet);
		sap.ui.getCore().applyChanges();

		// Assert
		strictEqual(oResult, oButton, "Should be able to chain");
		strictEqual(oRenderSpy.callCount, 0, "Did not re-render");
		ok(!/.*<script>.*/.test(oButton.$("content").html()), "Did not contain a unescaped script tag");
		strictEqual(oButton.getText(), sTextToSet, "Did set the non encoded string as value");

		// Cleanup
		oButton.destroy();
	});

	test("Tap event should not be fired when the button is set to invisible", function() {
		// Arrange
		var oRenderSpy,
			oConstructor = { visible : false };

		// System under Test
		var oButton = new sap.m.Button(oConstructor).placeAt("qunit-fixture");

		oRenderSpy = this.spy(oButton, "fireTap");

		// Act
		oButton.ontap({ setMarked:  jQuery.noop });

		// Assert
		strictEqual(oRenderSpy.callCount, 0, "Tap event not fired");

		// Cleanup
		oButton.destroy();
	});

	test("For safari the button should gain explicitly focus on touch start", function() {
		// Arrange
		// stub the browser to be only safari
		this.stub(sap.ui.Device, "browser", {
			safari: true
		});

		var oButton = new sap.m.Button({text: "MyText", icon: "sap-icon://search"}).placeAt("qunit-fixture");
		oRenderSpy = this.spy(oButton, "focus");
		sap.ui.getCore().applyChanges();

		// Act
		oButton.ontouchstart({ setMarked: jQuery.noop, preventDefault: jQuery.noop, targetTouches: { length: 1 }, originalEvent: { type: "mousedown" }});
		this.clock.tick(1000);

		// Assert
		strictEqual(oRenderSpy.callCount, 1, "The button is focused on touch start");

		// Cleanup
		oButton.destroy();
	});

	test("Check type conversation if text property is changed (non-string value)", function() {
		// Arrange
		var oRenderSpy,
			oConstructor = { text : "Check type conversation (text)", enabled : true};

		// System under Test
		var oButton = new sap.m.Button(oConstructor).placeAt("qunit-fixture");
		sap.ui.getCore().applyChanges();

		oRenderSpy = this.spy(oButton, "invalidate");

		// Act
		oButton.setText(2);
		sap.ui.getCore().applyChanges();

		// Assert
		strictEqual(oRenderSpy.callCount, 0, "No conversation error");

		// Cleanup
		oButton.destroy();
	});

	test("Should not re-render the button if icon property is changed", function() {
		// Arrange
		var oRenderSpy,
			oConstructor = { text : "Re-render Check (icon)", enabled : true, icon : sap.ui.core.IconPool.getIconURI("employee") , iconFirst : true};

		// System under Test
		var oButton = new sap.m.Button(oConstructor).placeAt("qunit-fixture");
		sap.ui.getCore().applyChanges();

		oRenderSpy = this.spy(oButton, "invalidate");

		// Act
		oButton.setIcon(sap.ui.core.IconPool.getIconURI("notes"));
		sap.ui.getCore().applyChanges();

		// Assert
		strictEqual(oRenderSpy.callCount, 0, "Did not rerender");

		// Cleanup
		oButton.destroy();
	});

	test("Tooltip is recognized", function() {

		// Arrange
		var oButton = new sap.m.Button({text: "MyText",
			icon: "sap-icon://search"});

		strictEqual(oButton._getTooltip(), undefined, "Should not return tooltip");

		// Act
		oButton.setTooltip("MyTooltip");

		// Assert
		strictEqual(oButton._getTooltip(), "MyTooltip", "Should return the tooltip");

		// Cleanup
		oButton.destroy();
	});

	test("Tooltip is derived for icon-only buttons", function() {

		// Arrange
		var oButton = new sap.m.Button({tooltip: "MyTooltip",
			icon: "sap-icon://search"});

		strictEqual(oButton._getTooltip(), "MyTooltip", "Should return the primary tooltip");

		// Act
		oButton.setTooltip(null);

		// Assert
		strictEqual(oButton._getTooltip(), "Search", "Should return the derived tooltip");

		// Cleanup
		oButton.destroy();
	});

	test("getAccessibilityInfo", function() {
		var oButton = new sap.m.Button({tooltip: "Tooltip"});
		ok(!!oButton.getAccessibilityInfo, "Button has a getAccessibilityInfo function");
		var oInfo = oButton.getAccessibilityInfo();
		ok(!!oInfo, "getAccessibilityInfo returns a info object");
		strictEqual(oInfo.role, "button", "AriaRole");
		strictEqual(oInfo.type, sap.ui.getCore().getLibraryResourceBundle("sap.m").getText("ACC_CTR_TYPE_BUTTON"), "Type");
		strictEqual(oInfo.description, "Tooltip", "Description");
		strictEqual(oInfo.focusable, true, "Focusable");
		strictEqual(oInfo.enabled, true, "Enabled");
		ok(oInfo.editable === undefined || oInfo.editable === null, "Editable");
		oButton.setText("Text");
		oButton.setEnabled(false);
		oInfo = oButton.getAccessibilityInfo();
		strictEqual(oInfo.description, "Text", "Description");
		strictEqual(oInfo.focusable, false, "Focusable");
		strictEqual(oInfo.enabled, false, "Enabled");
		oButton.setText(null);
		oButton.setTooltip(null);
		oButton.setIcon("sap-icon://search");
		oInfo = oButton.getAccessibilityInfo();
		strictEqual(oInfo.description, "Search", "Description");
		oButton.destroy();
	});

	// check if we have reference added to the text content of the button
	// so it can be read otherwise it causes the issue reported in BCP: 1680223321
	test("AriaLabeledBy when the Button is associated with Label and the button has text", function(assert) {
		var sTextSpanId = "-content";
		var oLabel = new sap.m.Label("L1", {
			text:'Label'
		});
		var oButton = new sap.m.Button("B1",{
			text:'Hello World',
			ariaLabelledBy: "L1"
		});

		oLabel.placeAt("qunit-fixture");
		oButton.placeAt("qunit-fixture");
		sap.ui.getCore().applyChanges();

		equals(oButton.$().attr("aria-labelledby"), "L1 B1" + sTextSpanId, "Label id and Button content id are written inside aria-labelledby attribute");

		oLabel.destroy();
		oButton.destroy();
	});

	// in case of icon only button we souldn't have self reference otherwise
	// it causes issue reported in BCP: 1780428239
	test("AriaLabeledBy when the Button is associated with Label and the button has icon only", function(assert) {
		var oLabel = new sap.m.Label("L1", {
			text:'Label'
		});
		var oButton = new sap.m.Button("B1",{
			icon: "sap-icon://edit",
			ariaLabelledBy: "L1"
		});

		oLabel.placeAt("qunit-fixture");
		oButton.placeAt("qunit-fixture");
		sap.ui.getCore().applyChanges();

		equals(oButton.$().attr("aria-labelledby"), "L1", "Only Label id is written inside aria-labelledby attribute");

		oLabel.destroy();
		oButton.destroy();
	});

	test("_activeButton _inactiveButton", function() {
		//sut
		var sIconURI = 'sap-icon://slim-arrow-down',
			sActiveIconURI = 'sap-icon://slim-arrow-up',
			oButton = new sap.m.Button({
				icon: sIconURI,
				activeIcon: sActiveIconURI
			});

		oButton.placeAt("qunit-fixture");
		sap.ui.getCore().applyChanges();

		//act
		oButton._activeButton();

		//assert
		ok(oButton.$("inner").hasClass("sapMBtnActive"), 'button is styled as active');
		equals(oButton._image.getSrc(), sActiveIconURI);

		//act
		oButton._inactiveButton();

		//assert
		ok(!oButton.$("inner").hasClass("sapMBtnActive"), 'button is styled as inactive');
		equals(oButton._image.getSrc(), sIconURI);

		//clean
		oButton.destroy();
	});

	test("tabindex", function() {
		equal(b1.$().attr("tabindex"), undefined, "By default the button(root) should have no tabindex");
		equal(b1.$("inner").attr("tabindex"), undefined, "By default the button(inner) should have no tabindex");

		//Act
		b1._bExcludeFromTabChain = true;

		b1.invalidate();
		sap.ui.getCore().applyChanges();

		//Assert
		equal(b1.$().attr("tabindex"), "-1", "Button(root) should have negative tabindex when requested via _bExcludeFromTabChain");
		equal(b1.$("inner").attr("tabindex"), "-1", "Button(inner) should have negative tabindex when requested via _bExcludeFromTabChain");
	});

	QUnit.test("Enter event should fire press on keydown", function(assert) {
		// System under Test
		var pressSpy = this.spy();
			oButton = new sap.m.Button({
				press: pressSpy
			}).placeAt("qunit-fixture");

		sap.ui.getCore().applyChanges();

		// Action
		qutils.triggerKeydown(oButton.getDomRef(), jQuery.sap.KeyCodes.ENTER);

		// Assert
		assert.equal(pressSpy.callCount, 1, "Press event should be fired once");

		// Cleanup
		oButton.destroy();
	});

	QUnit.test("Enter event should not fire press on keyup", function(assert) {
		// System under Test
		var pressSpy = this.spy(),
			oButton = new sap.m.Button({
				press: pressSpy
			}).placeAt("qunit-fixture");

		sap.ui.getCore().applyChanges();

		// Action
		qutils.triggerKeyup(oButton.getDomRef(), jQuery.sap.KeyCodes.ENTER);

		// Assert
		assert.equal(pressSpy.callCount, 0, "Press event should not be fired");

		// Cleanup
		oButton.destroy();
	});

	QUnit.test("Space event should not fire press on keydown", function(assert) {
		// System under Test
		var pressSpy = this.spy(),
			oButton = new sap.m.Button({
				press: pressSpy
			}).placeAt("qunit-fixture");

		sap.ui.getCore().applyChanges();

		// Action
		qutils.triggerKeydown(oButton.getDomRef(), jQuery.sap.KeyCodes.SPACE);

		// Assert
		assert.equal(pressSpy.callCount, 0, "Press event should not be fired");

		// Cleanup
		oButton.destroy();
	});

	QUnit.test("Space event should fire press on keyup", function(assert) {
		// System under Test
		var pressSpy = this.spy(),
			oButton = new sap.m.Button({
				press: pressSpy
			}).placeAt("qunit-fixture");

		sap.ui.getCore().applyChanges();

		// Action
		qutils.triggerKeyup(oButton.getDomRef(), jQuery.sap.KeyCodes.SPACE);

		// Assert
		assert.equal(pressSpy.callCount, 1, "Press event should be fired once");

		// Cleanup
		oButton.destroy();
	});

</script>

</head>
<body>
	<h1 id="qunit-header">QUnit page for sap.m.Button</h1>
	<h2 id="qunit-banner"></h2>
	<h2 id="qunit-userAgent"></h2>
	<div id="qunit-testrunner-toolbar"></div>
	<div id="qunit-fixture">test markup, will be hidden</div>
	<ol id="qunit-tests"></ol>
	<div id="contentBtnDefault" class="ButtonSpace"></div>
	<div id="contentBtnBack" class="ButtonSpace"></div>
	<div id="contentBtnAccept" class="ButtonSpace"></div>
	<div id="contentBtnReject" class="ButtonSpace"></div>
	<div id="contentBtnTransparent" class="ButtonSpace"></div>
	<div id="contentBtnWidth" class="ButtonSpace"></div>
	<div id="contentBtnDisabled" class="ButtonSpace"></div>
	<div id="contentBtnIcon" class="ButtonSpace"></div>
	<div id="contentBtnUp" class="ButtonSpace"></div>
	<div id="contentBtnUnstyled" class="ButtonSpace"></div>
	<div id="contentBtnInvisible" class="ButtonSpace"></div>
	<div id="contentBtnTextDirectionRTL" class="ButtonSpace"></div>
	<div id="contentBtnTextDirectionLTR" class="ButtonSpace"></div>
</body>
</html>


text:
<jqa:jqassistant-rules xmlns:jqa="http://www.buschmais.com/jqassistant/core/analysis/rules/schema/v1.0">

    <concept id="module-api:Module">
        <description>Labels the module com.buschmais.xo.api as MODULE and CDO_API.</description>
        <cypher><![CDATA[
			MATCH
				(package:PACKAGE)
			WHERE
				package.FQN = "com.buschmais.xo.api"
			SET
			    package:MODULE:CDO_API
			RETURN
				package
        ]]></cypher>
    </concept>

    <constraint id="module-api:Dependency">
        <requiresConcept refId="modules:TypesOfModule"/>
        <requiresConcept refId="dependency:Type"/>
        <description>The module API must have no dependencies to other modules.</description>
        <cypher><![CDATA[
			MATCH
			    (module:MODULE:CDO_API)-[:CONTAINS]->(type:TYPE),
                (otherModule:MODULE)-[:CONTAINS]->(otherType:TYPE),
				(type)-[:DEPENDS_ON]->(otherType:TYPE)
			WHERE
			    module<>otherModule
			RETURN
                type as Type, otherType as OtherType
        ]]></cypher>
    </constraint>

</jqa:jqassistant-rules>


text:
package com.graphhopper.routing.util;

import com.graphhopper.util.PMap;

import static com.graphhopper.util.Helper.toLowerCase;

/**
 * @author Peter Karich
 */
public class HintsMap extends PMap {
    public HintsMap() {
    }

    public HintsMap(int capacity) {
        super(capacity);
    }

    /**
     * Convenient constructor if only one parameter is provided
     */
    public HintsMap(String weighting) {
        super(5);
        setWeighting(weighting);
    }

    public HintsMap(PMap map) {
        super(map);
    }

    public HintsMap(HintsMap map) {
        super(map.toMap());
    }

    @Override
    public HintsMap put(String key, Object str) {
        super.put(key, str);
        return this;
    }

    public String getWeighting() {
        return toLowerCase(super.get("weighting", ""));
    }

    public HintsMap setWeighting(String w) {
        if (w != null)
            super.put("weighting", w);
        return this;
    }

    public String getVehicle() {
        return toLowerCase(super.get("vehicle", ""));
    }

    public HintsMap setVehicle(String v) {
        if (v != null)
            super.put("vehicle", v);
        return this;
    }
}


text:
#ifndef JEMALLOC_STDBOOL_H
#define JEMALLOC_STDBOOL_H

#ifdef _MSC_VER

#include <wtypes.h>
#include <windef.h>

#ifdef __cplusplus
extern "C" {
#endif

/* MSVC doesn't define _Bool or bool in C, but does have BOOL */
/* Note this doesn't pass autoconf's test because (bool) 0.5 != true */
#if defined(_MSC_VER) && (_MSC_VER < 1700)
typedef BOOL    _Bool;
#endif

#define bool    _Bool

#define true    1
#define false   0

#define __bool_true_false_are_defined 1

#ifdef __cplusplus
}
#endif

#endif  /* _MSC_VER */

#endif  /* JEMALLOC_STDBOOL_H */


text:
layout:     post
title:      "Machine Learning Exam Review"
subtitle:   ""
date:       2016-02-23 14:30:00
author:     "Beld"
header-img: "img/post-bg-ml.png"
tags:
    - Machine Learning
---

##### Name and describe the categories of learning. Name two concrete examples for learning algorithms.

- Unsupervised Learning: clustering, density estimation
- Supervised Learning: Regression, SVM, HMM, Boosting
- discriminant function (no prob. Learn a function), discriminant model(estimate the posterior for each class), and generative model (likelihoods and Bayes rule for prosterior.)
- Reinforcement Learning: no supervision, but a reward function.
- Generative model: kNN: given data points, assign each new data to its K nearest neighbors in feature space. Compute posteriors and MAP.

##### What is the purpose of regression and what is the general principle?

- Given a set of objects and a set of object categories (classes), regression learns a mapping function, then it can predict the categories of new object.

- General principle: first, extract the features of the input data using basis functions, then choose a regression model to take the features as input and compute the output. Next we compare the output of the model and desired output to evaluate the regression model, for example, use sum of square errors. and revise the model to fit out training data. But we need to avoid the overfitting.

##### Explain linear regression and what exactly is linear there.

The basis functions are nonlinear with respect to the input variables. But linear regression models are linear combination of nonlinear basis functions, so the model is linear to the parameters of the basis functions.

To evaluate the function, we need an error function, for example the sum of squared errors. Then we want to find the optimal parameters to minimize the error function by deriving the function w.r.t parameters. After obtaining the parameters, we can use the model to predict the target value of new input data.

##### What is a pseudoinverse matrix?

Pseudoinverse matrix is a generalization matrix inverse to nonsquare matrices. Every matrix has a pseudoinverse matrix, but only when the matrix is square and invertable, the pseudoinverse matrix equals to the inverse of the matrix.
Φ† ≡ (ΦTΦ) −1 ΦT
It can be computed using the singular value decomposition.

##### Name two types of basis functions and explain how they should be used.

- Gaussian basis function:

- Sigmoidal basis function: using logistic sigmoid function / 'tanh' function, the μj govern the locations of the basis functions in input space, and the parameter s governs their spatial scale. It is no need to normalize these basis function.

##### Explain regularization in the context of regression. Why is this useful?

After training the model on the training dataset, there will be the overfitting problem when to predict the new data. For example, the polynomials coefficients will become very large. The model gains the memory ability but decreases the ability of generalization. We can add a penalty term of the coefficients to the error function to avoid overfitting. This technique is called regularization.

##### What is the probabilistic formulation of regression? What is the equivalent of maximum-likelihood and maximum-a-posteriori?

We can assume that y is affected by Gaussian noise, the we can the likelihood of the measured data given a model. We want to find the model parameters to maximize the prob.
Maximum likelihood under Gaussian noise is equivalent to sum of square errors regression.
Maximum-a-posteriori assuming a Gaussian prior is equivalent to the regularized regression.
Sequential data: use the old data to calculate the posteriori as the prior of the new data to iteratively compute the parameters by MLE.
Predictive model: use the old data to calculate the posteriori as the prior of the new data to predict by integrating over all possible parameters.

##### Name the different kinds of Probabilistic Graphical Models and draw two examples. What do they represent?

Bayesian Network: directed graphical model
 p(a, b, c) = p(c | a, b) p(b | a) p(a).
absence of edges  independence.  One-to-one mapping, causal relationships
Markov Random Fields: undirected graphical models
 A ⊥ B | C.

##### What is a perfect map between a graphical model and a joint probability distribution?

I-map: Every D-separation  a conditional independence (fully connected)
D-Map: every conditional independence  D-separation
Perfect-Map: one-to-one mapping
every conditional independence property of the distribution is reflected in the graph, and vice versa, then the graph is said to be a perfect map for that distribution
What is D-separation?

(independence does not imply conditional independence)
Conditional independence properties of the joint distribution can be read directly from the directed acyclic graph by using D-separation.
There are three cases:
(a) the arrows on the path meet either head-to-tail or tail-to-tail at the node, and the node is in the set C, or
(b) the arrows meet head-to-head at the node, and neither the node, nor any of its descendants, is in the set C.
If all paths are blocked, then A is said to be d-separated from B by C, and the joint distribution over all of the variables in the graph will satisfy A ⊥ B | C.

##### What is the definition of the Markov blanket and how can it be computed in directed and undirected graphical models?

Markov blanket is the minimal set of observed nodes to obtain conditional independence.
For an undirected graph, it is dependent only on the neighbouring nodes.
For directed graph, the Markov blanket comprises the set of parents, children and co-parents of the node.

##### What is a Markov Random Field?

Markov Random Field is an undirected graph model to check conditional independence. Its node represents a variables or group of variables. It is defined as a factorization over clique potentials and normalized globally.

Two nodes are not connected in MRF  conditional independent given all other nodes.
Clique: fully connected subgraph.
Maximal clique: can not be extended without loosing fully connectivity.

##### How does the expressiveness of directed and undirected graphical models compare?

Directed graphs are useful for expressing causal relationships between random variables, whereas undirected graphs are better suited to expressing soft constraints between random variables without ordering, for example, the pixels in a camera image. Undirected graph is simpler and more intuitive to express conditional independence.

##### What is "explaining away" in the context of graphical models?

For head-to-head case, observations of child nodes will not block paths to the co-parents. We must observe the co-parent nodes also.

##### How to convert directed graphs to undirected graphs?
Conditional distributions in the directed graph are mapped to cliques in the undirected graph and connect all parents of head-to-head nodes.
Problem: remove conditional independence relations. There is no one-to-one mapping.

##### What is the general idea of the inference on an undirected Markov Chain?

When computing the local marginal distribution using the joint probability, we can rearrange the summation order of the production. Then we can recursively compute and store the all forward and backward messages. Next we can compute the normalizing factor for any node to get the marginal for this node.
It is a special case of sum-product algorithm.

##### What is a factor graph?

A generalization of directed and undirected graph by introducing additional nodes for the factors. It allows more explicit details of factorization.

Max-sum algorithm: to find the setting that maximize the joint probability and the maximal value. Max operator is distributive so we can exchange the order of it with production. Two problems: 1. Lots multiplication  log space. 2. Multiple configurations  keep track of them
CRF: Conditional Random Fields
For classification, discriminative model
Training: MAP, approximate likelihood using Markov blanket (Pseudo likelihood)
Potential function: positive, log-linear

##### What does the sum-product algorithm compute and how?

Sum-product algorithm computes the marginal distribution at a given node.
1.	It considers the node as a root node.
2.	Then initialize leaf node either 1 if variable or f(x) if factor.
3.	Propagate the message from the leaves to the root
4.	Then propagate the message from the root to the leaves
5.	Then we can get the marginal at every node by multiplying all incoming messages.

##### What is the definition of a Hidden Markov Model?

Sequential data, stationary = same generative distribution = i.i.d
By the introduction of discrete latent variables  HMM
Assume that it is the latent variables that form a Markov chain
It contains 1. discrete observation variables and state variables each with K states. 2. Transition model, first order Markov chain. 3. Observation model.

application: 1. Likelihood 2. Filtering and smoothing given observations 3.  Best sequence given observation 4. Optimal model parameters.
Filtering: forward algorithm
Smoothing: forward and backward algorithm
Most likely states: Viterbi
Optimal parameters: Baum-Welch or EM

##### How does the Viterbi algorithm work?
It is same with max-sum algorithm if treat HMM as a directed tree.
From 1 to N time step, we assume at time step t, state j is the most probable path, denoted as μ_t(j). It can be compute from step t-1, μ_t-1(i) multiply transition probability and emission probability. At the same time, we compute the argmax of i.
On termination, we can get the maximal value of joint probability and we can backtrack the state setting for this sequence.

Baum-Welsh (EM): use k-means to initialize parameters. In E-step to compute the Q, and M-step to maximize Q. in each iteration, forward-backward algorithm is used. Result gives a local optimum.

##### How does k-means clustering work?
Given data set and number of cluster K. k-means can get the optimal assignments of each point and the cluster centers by minimizing the sum of square errors. It iteratively computes center μ and the point assignments r. At first, it initializes fixes the centers and find the optimal assignments. Then using these assignments to update the cluster centers. Repeat until convergence.

##### Name the definition of a Gaussian Mixture Model. What are the individual components and where can it be used?

Assume that data consists of K clusters and each cluster is Gaussian. And each data point is softly assigned into a cluster with a probability and a latent variable to indicate whether it is in a cluster or not.
Each individual component is a Gaussian.
It can be used for clustering in speech recognition.

##### What are the differences and similarities between k-means and Expectation Maximization in Gaussian Mixture Models?

k-means is a special case of GMM. They both contains expectation step and maximization step. And they both only find the local maximum.
But in k-means, the points are assigned to only one cluster. It is hard assignment. While in GMM, the points are assigned with probabilities. It is soft assignment.
In GMM, the covariance is also estimated by EM.
The number of iterations of EM in GMM is much higher and it needs more computation. So k-means can be used to initialize GMM.

##### What is the complete-data log-likelihood and how is it used in EM?

We assume that we can observe the latent variables Z, then we call the data set of X and Z is complete. The complete-date log-likelihood is about the joint distribution of X and Z.
Advantage is that the log-likelihood is much simpler, the log is inside the sum and rearrange the sums to reduce computation.
But in EM, we don't know about the latent variables. So we consider the expectation of joint log-likelihood under the latent variable distribution. And the expectation of latent variables for one point is the responsibilities of that point. Then we can replace the expectation of the latent variables with their responsibilities. Finally we can use EM to maximizes the expected complete date log-likelihood.

##### What exactly is optimized in EM and how?

We want to maximize the log-likelihood but it is very difficult, the sum is in log. But we can introduce the latent variables and consider the marginalizing over the latent variables of joint distribution of x and latent variable. The log form is much simpler.
Then iteratively find the optimal parameters.
For E-step, it only increases the lower bound. We try to find the maximal lower bound of the functional of proposal distribution q based on the old parameters to get a new q and the same time to minimize the KL-divergence. Q equals to posterior of Z.
In M-step, fix the proposal distribution Q and update the parameters. It makes KL again larger than zero and the log-likelihood is also maximized.
Name examples for applications of the EM algorithm.

It can be used to find the parameters of HMM.

##### Name 3 different activation functions used in Neural Networks. What is the advantage of ReLU over sigmoids?

1.	Threshold activation, it is a binary classifier
2.	Sigmoid activation, it is used to model probability and its gradient is less than 1.
3.	Rectified Linear Unit activation, max(0,phi), it can be used to model positive real numbers and its gradient is either 0 or 1. It can reduce sparsity and doesn't have the vanishing problem when propagate the gradient. It is faster and more efficient.

##### What is the name of the training procedure in Neural Networks? How does it work?

Back Propagation:
Forward the input to generate the output and propagate the errors backwards to evaluate the derivatives of the error function with respect to the weights. The derivatives are used to compute the adjustments using gradient descent.

##### Name the advantages of CNNs over fully connected NNs.
It is sparse and weight sharing, so it is easier to train and have many fewer parameters than fully connected networks with the same number of hidden units.

It is invariant to certain transformation of the inputs. It is suitable for 2D structure, like image and speech.
Fully-connected does not take into account the spatial structure of the images.
Sketch a perceptron for binary classification with n inputs.

##### What is the principle of the AdaBoost algorithm?

Use a weak classifier and turn it into a strong one with arbitrarily small training error.
Sequentially fit classifiers by minimizing the exponential loss and compute the weights of classifiers and update the weights of wrong data points.
Name the definition of a weak and a strong classifier. Give examples for each.

Weak:
Decision stumps: axis-aligned hyper-plane that minimize the class error
Decision trees: decision is made at every node.
Strong: Adaboost

##### What other variants of AdaBoost exist?

LogitBoost uses logistic function and weighted least-squares regression.
GentleBoost
Gradient Boost uses the general form of loss function. In each iteration, it calculates the gradient w.r.t classifier function and try to find a basis function that is close to the gradient residual. Then add it to the former classifier.

##### How can AdaBoost be used for face detection?

Extract the features like haar-like features
Training the adaboost using the weak classifers. The weak classifier contains a threshold to tell the belief of a feature.
Because the scale of the image is different. So we gradually increase the scale in each loop.

##### What is a kernel function?

Kernel function maps two arguments into a real number to measure their similarity without any feature.
Name the Theorem of Mercer and explain the kernel trick.

If a kernel is symmetric and positive definite, there exists a mapping into a feature space so that the kernel represents an inner product in this higher dimensional space.
Kernel trick is to express similarities of data points in term of an inner product and replace all inner products by the kernel function
It means that we don't need to find the specific basis functions. We only need to find some kernel functions corresponding to some basis functions in feature space.

##### How can kernelization be applied to k-means clustering?

We can replace each point as basis function, and rewrite the center also.
The square error can be rewrited with kernels.

##### What is the principle of kernel PCA?

PCA: project data onto a subspace of lower dimension so that the variance is maximized, decorrelation.
Reconstruction: minimize the squared error. Substract mean, project into eigenvectors and back project and add mean.
For data is non-linearly distributed along the principle component, we use non-linear kernel to map into a space we can do PCA.
Construct the inner products of the basis functions and replace the basis functions by kernels.

##### What is a Support Vector Machine?

SVM is a binary classifier that learn a linear discriminant function which is a decision hyper-plane that maximize the margin to separate the data points.

Support vectors has minimal distance to decision plane and the distance of support vectors is rescaled to 1.
Use Lagrange constrained optimization to derive the dual formulation and then replace with kernel to get the optimal solutions. The trick is we can replace the kernel by any other valid kernel and obtain again an optimal solution.
For prediction process, we only need to compute new data point with support vectors.
For multiple classes, one-to-many classification.
For non-separable problem, we allow data points that located within margins with slack variables to classify them as correct classified ones or misclassified ones.

##### Name the definition of a Gaussian process. What specifies a GP? Draw an example.
A Gaussian process is a collection of random variables, any finite number of which have a joint Gaussian distribution. A GP is a Gaussian distribution over functions.
To specify a GP: mean function and covariance function.
How to handle infinity? Split into a finite part and an infinite part and marginalize the infinite part.

##### How can a function be sampled from a Gaussian Process?

1.	Choose some input points
2.	Compute the covariance matrix K of the input points using the kernel function
3.	Generate a random	Gaussian vector from the GP, zero mean, K covariance
4.	Plot the x and y.

##### What are the hyperparameters of the squared exponential kernel?

Many names: squared exponential, radial basis function, Gaussian kernel
Signal variance
Length scale: range between points, influence distance
Noise variance

##### What is Automatic Relevance Determination?

During the optimization process to learn the hyper-parameters, the reciprocal length scale in the squared exponential kernel can be interpreted as the weight for each feature dimension. So during the training process, the relevance is automatically determined.

##### What is the main problem in Gaussian Process classification in contrast to regression and how can it be solved?

When computing the predictive distribution, we marginalize over the latent functions from the training data. If using the Bayes rules to transform the posterior of the latent functions, the likelihood is a sigmoid function not a Gaussian. We can not compute in closed form.
We only can approximate the posterior. We could use Laplace approximation, expectation propagation or Variational methods.
Laplace approximation is based on the second-order Taylor expansion to find the mean and variance of the Gaussian.

##### Name and describe briefly 4 different sampling methods.

1.	Probability transformation:
a.	inverse of cumulative distribution function
need to calculate and inverse.
2.	Rejection sampling:
a.	Find a proposal distribution which is easy to sample.
b.	Find a number k, let kq>=p. p is target distribution that is under kq.
c.	Sample from x-axis uniformly get a x0.
d.	Sample from 0 to kq(x0).
e.	Accept or reject.
Inefficient. Might always reject in high dimensional space.
3.	Importance sampling:
a.	Assign an importance weight to each sample from q.
b.	The probability of certain sample is in the interval A is the area under the curve p.
c.	This equals to the expectation of the indicator function under the curve p.
d.	The trick to replace this expectation under the distribution q.
e.	Then use number of samples with weight to approximate.
4.	MCMC:
a.	Main idea: sample from a proposal distribution and design its transition matrix results stationary distribution to be our desired distribution.
b.	Theorem: a Markov chain with transition matrix A is irreducible and satisfies the detailed balance w.r.t pi (chain is reversible)  pi is the stationary distribution. (easy proof pi = pi * A)
c.	MH algorithm:
i.	For each state:
1.	Sample x'from q(x'|x)
2.	Compute acceptance probability
3.	Compute r=min(1,a)
4.	Sample U[0,1]
5.	Compare, less to keep and set it as next state

##### How can a Particle Filter be used for Markov Localization?

1.	Each particle is a hypothesis of position
2.	Proposal distribution is the motion model to predict
3.	The observation model is used to compute the importance weight to correct the prediction.
4.	For every sample, each loop sample a new one and compute the weights and add into the set.
5.	Resampling each sample with probability proportional to weights.
Particle filter is non-parametric implementation of Bayes filter. By a set of random state samples to represent a probability distribution  can be not Gaussian  Can model non-linear
Basic principles: set of state hypothesis, survival of the fittest.
Resample: standard n times vs. low variance sampling: only samples once
Kidnapped Robot: add new uniform samples.
What is a stationary distribution in a Markov Chain?
Each step in the chain, distribution of states is invariant.
Existence: solve the equation: the eigenvector with eigenvalue 1.  every row has such eigenvector, but may not be unique.
Uniqueness: ergodic, A  irreducible: we can reach every state from any other state in finite step with non-zero probability.

##### How does the Metropolis-Hastings algorithm work?

Main idea: construct the transition matrix and make the resulting stationary distribution is our target distribution.
For each state:
	Sample x' from q(x'|x);
		Compute the acceptance probabililty
		R = min(1, a)
		Sample from U(0,1)
		Accept as next state or reject

##### What is Gibbs Sampling?

Idea: for multiple variables, in each time step, sample each variable from the full conditional and replace the old one with this new sample. Then cycling through all variable.
It is a special case of MCMC algorithm when acceptance probability equals to 1. So it can be applied for high dimensional cases.

##### What is variational inference?

Variational inference takes functions as input and find functions to optimize a given functional. It is mainly used to find approximations to a given function.
Functional: a mapping that takes a set of functions as the input and that returns the real number of the functional as the output. E.g entropy.

##### Name the definition and the properties of the Kullback-Leibler divergence. Where is it used?

KL divergence is the average additional amount of information between q and p.
It is non-symmetric and non-negative. It only equals zero when p equals q.
Give an unknown distribution p we want to approximate that with a distribution q. It can be used to measure the difference between two probability distribution. And approximate the posterior in variational methods and EM algorithm.

##### What are the main ideas of mean field and expectation propagation?

Goal: approximate the posterior with proposal distribution q.
Mean field theory: after factorizing the proposal distribution, we optimize each factor one by one. And for each factor, the log of the optimal solution is obtained by taking the expectation w.r.t all other factors of the log-joint probability of complete data.
EP: Assuming q is from exponential family. Also choose one factor from q and remove it from q by division. Then minimize the KL divergence using moment matching (same mean and covariance) for new q. Then evaluate the new factor. Do this until convergence.

##### What is a cavity distribution?

Remove one factor of a distribution by division.

##### What is a conjugate prior?

A conjugate prior is used to solve the overfitting problem in MLE method. It has the same functional form with posterior. And the calculated posterior can be used as new prior for new data.
Such prior is called conjugate to the likelihood.
Binominal distribution  Beta-distribution.
Multinomial distribution  Dirichlet distribution

##### What is a Dirichlet Process and how can we construct one?
A Dirichlet process is a probability distribution of probability distributions G. It is only defined implicitly, we can say whether a given probability measure is sampled from a DP but we can not construct one. It contains two parameters: alpha concentration and H base measure.
A sample from Dirichlet process is an infinite and discrete distribution.
It can be constructed using the stick-breaking analogy:
A stick has the length of 1. Then select a random number beta between 0 to 1 from a Beta-distribution then break the stick at pi=beta*length. Repeat for the rest stick infinitely.

##### What is the idea of the Chinese Restaurant Process?
The restaurant has infinite tables, each with infinite seats.
Everytime a new customer comes in and sits at an occupied table with probability proportional to the number of people. So the probability to choose a new table is decreasing. The rich get richer.

##### What is the principle of Affinity Propagation?
Given a similarity matrix for all data points
To determine cluster centers (exemplars) that explain other data points in an optimal way.
Responsibility: I thinks j
Availability: j thinks itself.
Recomputed responsibilities and availabilities until convergence.
Choose the one maximize the responsibility and availability.

##### How does Spectral Clustering work?
Undirected graph, edge weights are similarities, weighted degree of a node is sum of all outgoing edges.

Given similarity matrix W and K.
Compute D: degree matrix, diagonal with sum of all outgoing weights.
Compute the graph Laplacian: L = D – W
Compute the eigenvectors of L with K smallest eigenvalues. Which means weak connection between clusters.
Treat each vector as K-dim data point and cluster them with K-means clustering.
Original data point in each vector belongs the resulting clusters.

##### What is agglomerative clustering?
Start with N clusters, each contains only one point.
At each step, merge the two most similar groups.
Repeat until there is only one single group.

Linkage:
1.	Single: closest
2.	Complete: farthest.
3.	Average: average.

Evaluation:
1.	Purity: compute the purity and normalize to choose the one that is purest.
2.	Mutual information: compare with groundtruth. Entropy like.


text:
layout: organization
category: local

title: Queens Borough Public Library - Whitestone Branch
impact_area: Human Rights
keywords:
location_services:
location_offices:
website: http://www.queenslibrary.org/branch/whitestone/?filters=ev_loc:95800000

description:
mission:

cash_grants:
grants:
service_opp:
services:

learn:
cont_relationship:

salutation:
first_name:
last_name:
title_contact_person:

city: Queens
state: NY
address: |
  151-10 14 Road
  Queens NY 11357
lat: 40.785459
lng: -73.811044
phone:
ext:
fax:
email:
preferred_contact:
contact_person_intro:
---


text:
@class SBStarkScreenController;

@interface SBWaitForCarNowPlayingActiveTransaction : BSTransaction
{
    SBStarkScreenController *_screenController;
    double _timeout;
}

- (void)_begin;
- (void)dealloc;
- (id)initWithScreenController:(id)arg1 timeout:(double)arg2;

@end


text:
"""
Send metrics to a [graphite](http://graphite.wikidot.com/) using the default
interface. Unlike GraphiteHandler, this one supports multiple graphite servers.
Specify them as a list of hosts divided by comma.
"""

from Handler import Handler
from graphite import GraphiteHandler
from copy import deepcopy

class MultiGraphiteHandler(Handler):
    """
    Implements the abstract Handler class, sending data to multiple
    graphite servers by using two instances of GraphiteHandler
    """

    def __init__(self, config=None):
        """
        Create a new instance of the MultiGraphiteHandler class
        """
        # Initialize Handler
        Handler.__init__(self, config)

        self.handlers = []

        # Initialize Options
        hosts = self.config['host']
        for host in hosts:
            config = deepcopy(self.config)
            config['host'] = host
            self.handlers.append(GraphiteHandler(config))

    def get_default_config_help(self):
        """
        Returns the help text for the configuration options for this handler
        """
        config = super(MultiGraphiteHandler, self).get_default_config_help()

        config.update({
            'host': 'Hostname, Hostname, Hostname',
            'port': 'Port',
            'proto': 'udp or tcp',
            'timeout': '',
            'batch': 'How many to store before sending to the graphite server',
            'max_backlog_multiplier': 'how many batches to store before'
                'trimming',
            'trim_backlog_multiplier': 'Trim down how many batches',
        })

        return config

    def get_default_config(self):
        """
        Return the default config for the handler
        """
        config = super(MultiGraphiteHandler, self).get_default_config()

        config.update({
            'host': ['localhost'],
            'port': 2003,
            'proto': 'tcp',
            'timeout': 15,
            'batch': 1,
            'max_backlog_multiplier': 5,
            'trim_backlog_multiplier': 4,
        })

        return config

    def process(self, metric):
        """
        Process a metric by passing it to GraphiteHandler
        instances
        """
        for handler in self.handlers:
            handler.process(metric)

    def flush(self):
        """Flush metrics in queue"""
        for handler in self.handlers:
            handler.flush()


text:
Please read the [ManageIQ guides](http://github.com/ManageIQ/guides) before contributing.

The guides contain our Ruby coding standards as well as general standards around commits, pull requests, and more.

If you wish to contribute a translation of the project in your language, please read [Internationalization Guidelines](https://www.manageiq.org/docs/guides/i18n.html) before contributing.

Thanks for your contribution!

## License

All contributions to ManageIQ are licensed under the Apache
License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html).

See [LICENSE.txt](LICENSE.txt) for more details.