text:
;(function($, undefined){
  var prefix = '', eventPrefix, endEventName, endAnimationName,
    vendors = {Webkit: 'webkit', Moz: '', O: 'o', ms: 'MS'},
    document = window.document, testEl = document.createElement('div'),
    supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i

  function downcase(str) { return str.toLowerCase() }
  function normalizeEvent(name) { return eventPrefix ? eventPrefix + name : downcase(name) }

  $.each(vendors, function(vendor, event){
    if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
      prefix = '-' + downcase(vendor) + '-'
      eventPrefix = event
      return false
    }
  })

  $.fx = {
    off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined),
    cssPrefix: prefix,
    transitionEnd: normalizeEvent('TransitionEnd'),
    animationEnd: normalizeEvent('AnimationEnd')
  }

  $.fn.animate = function(properties, duration, ease, callback){
    if ($.isObject(duration))
      ease = duration.easing, callback = duration.complete, duration = duration.duration
    if (duration) duration = duration / 1000
    return this.anim(properties, duration, ease, callback)
  }

  $.fn.anim = function(properties, duration, ease, callback){
    var transforms, cssProperties = {}, key, that = this, wrappedCallback, endEvent = $.fx.transitionEnd
    if (duration === undefined) duration = 0.4
    if ($.fx.off) duration = 0

    if (typeof properties == 'string') {
      // keyframe animation
      cssProperties[prefix + 'animation-name'] = properties
      cssProperties[prefix + 'animation-duration'] = duration + 's'
      endEvent = $.fx.animationEnd
    } else {
      // CSS transitions
      for (key in properties)
        if (supportedTransforms.test(key)) {
          transforms || (transforms = [])
          transforms.push(key + '(' + properties[key] + ')')
        }
        else cssProperties[key] = properties[key]

      if (transforms) cssProperties[prefix + 'transform'] = transforms.join(' ')
      if (!$.fx.off) cssProperties[prefix + 'transition'] = 'all ' + duration + 's ' + (ease || '')
    }

    wrappedCallback = function(event){
      if (typeof event !== 'undefined') {
        if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below"
        $(event.target).unbind(endEvent, arguments.callee)
      }
      var props = {}
      props[prefix + 'transition'] = props[prefix + 'animation-name'] = 'none'
      $(this).css(props)
      callback && callback.call(this)
    }
    if (duration > 0) this.bind(endEvent, wrappedCallback)

    setTimeout(function() {
      that.css(cssProperties)
      if (duration <= 0) setTimeout(function() {
        that.each(function(){ wrappedCallback.call(this) })
      }, 0)
    }, 0)

    return this
  }

  testEl = null
})(Zepto)


text:
  PATH="$PATH:$THIS_DIR/../my_crystal_lang/progs/latest-crystal/bin"
  PATH="$PATH:$THIS_DIR/../my_crystal_lang/progs/latest-shards/bin"

redpajama_set_name: RedPajamaGithub


text:
Petit logiciel sans prétention, conçu pour gérer les réunions

Lecture de piste depuis le numéro, lecture aléatoire pour le programme musical, mise au noir de l'écran pour la préparation vidéo-projecteur

##Pré-requis
Conçu pour une XUbuntu 14.04+, testé sans souci avec une Debian Wheezy.

Nécessite une version fonctionnelle de [Qt5](https://wiki.qt.io/Install_Qt_5_on_Ubuntu) et le paquet [feh](apt://feh) installé.

En l'état, le plus simple reste de faire la compil du projet avec un QtCreator, dans un futur proche, je fournirais un fichier bash à éxécuter


text:
var treeObj = {
  func: 'isHungry',
  isTrue: {
    func: 'hasMoney',
    isTrue: 'BOUGHT_FOOD',
    isFalse: 'STOLE_FOOD'
  },
  isFalse: 'WATCHED_TV'
};

var functionObj = {
  isHungry: function(attributes) {
    return !(attributes.foodCount > 0);
  },
  hasMoney: function(attributes) {
    if (attributes.money > 5)
      return true;
    else
      return false;
  }
};

Tinytest.add('Test first output', function (test) {
  var NextMoveForGuy = new DecisionTree(0);
  NextMoveForGuy.setTree(treeObj);
  NextMoveForGuy.setFunctions(functionObj);

  var someGuy = {
    foodCount: 0,
    money: 0
  };

  var result = NextMoveForGuy.run(someGuy);

  test.equal(result, 'STOLE_FOOD');
});

Tinytest.add('Test second output', function (test) {
  var NextMoveForGuy = new DecisionTree();
  NextMoveForGuy.setTree(treeObj);
  NextMoveForGuy.setFunctions(functionObj);

  var someGuy = {
    foodCount: 0,
    money: 6
  };

  var result = NextMoveForGuy.run(someGuy);

  test.equal(result, 'BOUGHT_FOOD');
});

Tinytest.add('Test third output', function (test) {
  var NextMoveForGuy = new DecisionTree();
  NextMoveForGuy.setTree(treeObj);
  NextMoveForGuy.setFunctions(functionObj);

  var someGuy = {
    foodCount: 1,
    money: 0
  };

  var result = NextMoveForGuy.run(someGuy);

  test.equal(result, 'WATCHED_TV');
});


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace AxiomCoders.PdfTemplateEditor.EditorStuff
{
	public class EditorUpdateAction: EditorAction
	{
		private string[] properties = null;
		private object[] oldValues;
		private object[] newValues;

		private string property;
		private object oldValue;
		private object newValue;
		private EditorItem item;

		public EditorUpdateAction(EditorItem item, string property, object oldValue, object newValue)
		{
			this.item = item;
			this.property = property;
			this.oldValue = oldValue;
			this.newValue = newValue;
		}

		public EditorUpdateAction(EditorItem item, string[] property, object[] oldValues, object[] newValues)
		{
			this.item = item;
			this.properties = property;
			this.oldValues = oldValues;
			this.newValues = newValues;
		}

		public override void Redo()
		{
			if (properties != null)
			{
				for(int i = 0; i < properties.Length; i++)
				{
					PropertyInfo pi = item.GetType().GetProperty(properties[i]);
					pi.SetValue(item, newValues[i], null);
				}
			}
			else
			{
				PropertyInfo pi = item.GetType().GetProperty(property);
				pi.SetValue(item, newValue, null);
			}
			item.DockAll();
		}

		public override void Undo()
		{
			if (properties != null)
			{
				for (int i = 0; i < properties.Length; i++)
				{
					PropertyInfo pi = item.GetType().GetProperty(properties[i]);
					pi.SetValue(item, oldValues[i], null);
				}
			}
			else
			{
				PropertyInfo pi = item.GetType().GetProperty(property);
				pi.SetValue(item, oldValue, null);
			}
			item.DockAll();
		}
	}
}


text:
package com.intellij.ide.highlighter.custom.impl;

import com.intellij.codeInsight.editorActions.BraceMatcherBasedSelectioner;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.highlighter.HighlighterIterator;
import com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.util.containers.ContainerUtil;

import java.util.List;

/**
 * @author yole
 */
public class CustomFileTypeSelectWordHandler extends BraceMatcherBasedSelectioner {
  @Override
  public boolean canSelect(PsiElement e) {
    return e.getContainingFile().getFileType() instanceof CustomSyntaxTableFileType;
  }

  @Override
  public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
    List<TextRange> superResult = super.select(e, editorText, cursorOffset, editor);

    HighlighterIterator iterator = ((EditorEx)editor).getHighlighter().createIterator(cursorOffset);
    if (CustomFileTypeQuoteHandler.isQuotedToken(iterator.getTokenType())) {
      List<TextRange> result = ContainerUtil.newArrayList();
      int start = iterator.getStart();
      int end = iterator.getEnd();
      if (end - start > 2) {
        result.add(new TextRange(start + 1, end - 1));
      }
      result.add(new TextRange(start, end));
      if (superResult != null) {
        result.addAll(superResult);
      }
      return result;
    }

    return superResult;
  }
}


text:
<?php
/**
 * @author JKetelaar
 */

namespace Parabot\BDN\BotBundle\Repository;

use Parabot\BDN\BotBundle\Entity\Types\Type;

interface TypeRepository {

    /**
     * @param boolean $stable
     *
     * @return Type[]
     */
    public function findAllByStability($stable);

    /**
     * @param boolean     $stable
     *
     * @param null|string $branch
     *
     * @return null|Type
     */
    public function findLatestByStability($stable, $branch = null);
}


text:
@interface NormalViewController ()

@end

@implementation NormalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - override
- (Class)lableClass
{
    return [MLLabel class];
}

- (NSInteger)resultCount
{
    return 5;
}

- (void)changeToResult:(int)result
{
    self.label.textColor = [UIColor redColor];
    self.label.font = [UIFont systemFontOfSize:14.0f];
    self.label.numberOfLines = 1;
    self.label.textAlignment = NSTextAlignmentCenter;
    self.label.adjustsFontSizeToFitWidth = YES;
    self.label.textInsets = UIEdgeInsetsZero;
    self.label.text = @"人生若只如初见,何事秋风悲画扇。等闲变却故人心,却道故人心易变。骊山语罢清宵半,泪雨零铃终不怨。\n何如薄幸锦衣郎,比翼连枝当日愿。";
    [self.label setDoBeforeDrawingTextBlock:nil];

    if (result==0) {
    }else if (result==1) {
        self.label.textColor = [UIColor blackColor];
        self.label.font = [UIFont systemFontOfSize:16.0f];
        self.label.numberOfLines = 2;
        self.label.adjustsFontSizeToFitWidth = YES;
        self.label.textInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    }else if (result==2) {
        self.label.textColor = [UIColor blueColor];
        self.label.numberOfLines = 0;
        self.label.textAlignment = NSTextAlignmentLeft;
        self.label.textInsets = UIEdgeInsetsMake(20, 5, 5, 5);
        self.label.adjustsFontSizeToFitWidth = NO;
    }else if (result==3){
        //测试绘制回调
        self.label.numberOfLines = 0;
        self.label.textAlignment = NSTextAlignmentLeft;
        self.label.textInsets = UIEdgeInsetsMake(0, 10, 0, 5);
        [self.label setDoBeforeDrawingTextBlock:^(CGRect rect, CGPoint beginOffset, CGSize drawSize) {
            CGContextRef ctx = UIGraphicsGetCurrentContext();
            if (!ctx) return;

            [[UIColor darkGrayColor] setFill];

            CGContextFillRect(ctx, CGRectMake(beginOffset.x-10.0f, beginOffset.y, 5.0f, drawSize.height));
        }];
    }else if (result==4){
        self.label.numberOfLines = 0;
        //测试下attrStr
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:@"人生若只如初见,何事秋风悲画扇。等闲变却故人心,却道故人心易变。骊山语罢清宵半,泪雨零铃终不怨。何如薄幸锦衣郎,比翼连枝当日愿。"];
        [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(2, 10)];
        self.label.attributedText = attrStr;
    }

    if (result!=0) {
        self.label.frameWidth = self.view.frameWidth-10.0f*2;
        [self.label sizeToFit];
    }
}
@end


text:
@interface CALBaseViewController ()

@end

@implementation CALBaseViewController

////////////////////////////////////////////////////////////////////////////////////////////////////
- (UICollectionViewController *)nextViewControllerAtPoint:(CGPoint)p
{
    return nil;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
- (UICollectionViewTransitionLayout *)collectionView:(UICollectionView *)collectionView
                        transitionLayoutForOldLayout:(UICollectionViewLayout *)fromLayout newLayout:(UICollectionViewLayout *)toLayout
{
    UICollectionViewTransitionLayout *transitionLayout = [[UICollectionViewTransitionLayout alloc] initWithCurrentLayout:fromLayout nextLayout:toLayout];
    return transitionLayout;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
@end


text:
class UpdateUsers < ActiveRecord::Migration
  def change
    add_column :users, :zip, :string, null: false, default: "94112"
    add_column :users, :email, :string
  end
end


text:
namespace Network
{
namespace Packet
{
namespace Request
{
class cReqString : public cPacketBase<cReqString, PacketId::REQ_STRING>
{
public:
    cReqString( );
    cReqString( std::string str );
    void packetImport( cNetworkHandle networkHandle, ubyte2 transferredBytes, char const* const data ) override;
    ubyte2 packetExport( char* const data ) override;
    std::string str;
};
}
}
}


text:
// ------------------------------------------------------------------------
// Muragatte - A Toolkit for Observation of Swarm Behaviour
//             Core Library
//
// Copyright (C) 2012  Jiří Vejmola.
// Developed under the MIT License. See the file license.txt for details.
//
// Muragatte on the internet: http://code.google.com/p/muragatte/
// ------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Muragatte.Core.Environment;

namespace Muragatte.Core.Storage
{
    public class SpeciesCollection : ICollection<Species>, INotifyCollectionChanged, INotifyPropertyChanged
    {
        #region Constants

        public const string DEFAULT_AGENTS_LABEL = "Agents";
        public const string DEFAULT_GOALS_LABEL = "Goals";
        public const string DEFAULT_OBSTACLES_LABEL = "Obstacles";
        public const string DEFAULT_CENTROIDS_LABEL = "Centroids";
        public const string DEFAULT_EXTRAS_LABEL = "Extras";

        #endregion

        #region Fields

        private static readonly List<string> _labels = new List<string>() { DEFAULT_AGENTS_LABEL, DEFAULT_GOALS_LABEL, DEFAULT_OBSTACLES_LABEL, DEFAULT_CENTROIDS_LABEL, DEFAULT_EXTRAS_LABEL };

        private List<Species> _items = new List<Species>();
        private Dictionary<string, Species> _defaults = new Dictionary<string, Species>();

        public event NotifyCollectionChangedEventHandler CollectionChanged;
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region Constructors

        public SpeciesCollection(bool withDefaults = false)
        {
            InitializeDefaults();
            if (withDefaults) CreateDefaults();
        }

        public SpeciesCollection(IEnumerable<Species> items)
        {
            InitializeDefaults();
            Add(items);
        }

        #endregion

        #region Properties

        public int Count
        {
            get { return _items.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public Species this[string name]
        {
            get { return _items.Find(s => s.FullName == name); }
        }

        public Species this[int index]
        {
            get { return index >= 0 && index < _items.Count ? _items[index] : null; }
        }

        public Species DefaultForAgents
        {
            get { return _defaults[DEFAULT_AGENTS_LABEL]; }
            set { SetDefaultSpecies(value, DEFAULT_AGENTS_LABEL); }
        }

        public Species DefaultForGoals
        {
            get { return _defaults[DEFAULT_GOALS_LABEL]; }
            set { SetDefaultSpecies(value, DEFAULT_GOALS_LABEL); }
        }

        public Species DefaultForObstacles
        {
            get { return _defaults[DEFAULT_OBSTACLES_LABEL]; }
            set { SetDefaultSpecies(value, DEFAULT_OBSTACLES_LABEL); }
        }

        public Species DefaultForCentroids
        {
            get { return _defaults[DEFAULT_CENTROIDS_LABEL]; }
            set { SetDefaultSpecies(value, DEFAULT_CENTROIDS_LABEL); }
        }

        public Species DefaultForExtras
        {
            get { return _defaults[DEFAULT_EXTRAS_LABEL]; }
            set { SetDefaultSpecies(value, DEFAULT_EXTRAS_LABEL); }
        }

        public IEnumerable<Species> Progenitors
        {
            get { return _items.Where(s => s.Ancestor == null); }
        }

        #endregion

        #region Methods

        public void Clear()
        {
            _items.Clear();
            InitializeDefaults();
            NotifyCollectionChanged(NotifyCollectionChangedAction.Reset, null);
            NotifyPropertyChanged("Count");
        }

        public bool Contains(Species item)
        {
            return _items.Contains(item);
        }

        public void CopyTo(Species[] array, int arrayIndex)
        {
            _items.CopyTo(array, arrayIndex);
        }

        public Species GetDefault(string label)
        {
            return _labels.Contains(label) ? _defaults[label] : null;
        }

        public void Add(Species item)
        {
            if (!_items.Contains(item))
            {
                if (item.Ancestor == null || !_items.Contains(item.Ancestor))
                {
                    AddLast(item);
                }
                else
                {
                    int i = _items.FindLastIndex(s => s.IsDescendantOf(item.Ancestor));
                    int index = (i < 0 ? _items.IndexOf(item.Ancestor) : i) + 1;
                    if (index >= _items.Count)
                    {
                        AddLast(item);
                    }
                    else
                    {
                        AddInto(item, index);
                    }
                }
                NotifyPropertyChanged("Count");
            }
        }

        private void AddLast(Species item)
        {
            _items.Add(item);
            NotifyCollectionChanged(NotifyCollectionChangedAction.Add, item);
            Add(item.Children);
        }

        private void AddInto(Species item, int index)
        {
            _items.Insert(index, item);
            NotifyCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
            foreach (Species s in item.Children)
            {
                Add(s);
            }
        }

        public void Add(Species item, string key)
        {
            Add(item);
            if (_labels.Contains(key)) _defaults[key] = item;
        }

        public void Add(IEnumerable<Species> items)
        {
            if (items != null)
            {
                foreach (Species s in items)
                {
                    if (!_items.Contains(s))
                    {
                        _items.Add(s);
                        NotifyCollectionChanged(NotifyCollectionChangedAction.Add, s);
                        if (s.HasChildren)
                        {
                            Add(s.Children);
                        }
                    }
                }
                NotifyPropertyChanged("Count");
            }
        }

        public bool Remove(Species item)
        {
            if (_items.Contains(item))
            {
                RemoveAndNotify(item);
                List<Species> toRemove = new List<Species>();
                foreach (Species s in _items)
                {
                    if (s.IsDescendantOf(item)) toRemove.Add(s);
                }
                foreach (Species s in toRemove)
                {
                    RemoveAndNotify(s);
                }
                NotifyPropertyChanged("Count");
                return true;
            }
            else return false;
        }

        private void RemoveAndNotify(Species item)
        {
            if (item.Ancestor != null)
            {
                item.Ancestor.RemoveChild(item);
            }
            int index = _items.IndexOf(item);
            _items.RemoveAt(index);
            foreach (string s in _labels)
            {
                if (_defaults[s] == item)
                {
                    _defaults[s] = null;
                    break;
                }
            }
            NotifyCollectionChanged(NotifyCollectionChangedAction.Remove, item, index);
        }

        private void InitializeDefaults()
        {
            _defaults.Clear();
            foreach (string s in _labels)
            {
                _defaults.Add(s, null);
            }
        }

        private void CreateDefaults()
        {
            foreach (string s in _labels)
            {
                Add(new Species(s), s);
            }
        }

        public void SetDefaultSpecies(Species species, string key)
        {
            if (_labels.Contains(key))
            {
                if (species == null || _items.Contains(species))
                {
                    _defaults[key] = species;
                }
                else
                {
                    Add(species, key);
                }
                NotifyPropertyChanged("DefaultFor" + key);
            }
        }

        public IEnumerator<Species> GetEnumerator()
        {
            return _items.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return (System.Collections.IEnumerator)GetEnumerator();
        }

        private void NotifyCollectionChanged(NotifyCollectionChangedAction action, Species changedItem)
        {
            if (CollectionChanged != null)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, changedItem));
            }
        }

        private void NotifyCollectionChanged(NotifyCollectionChangedAction action, Species changedItem, int index)
        {
            if (CollectionChanged != null)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, changedItem, index));
            }
        }

        private void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion
    }
}


text:
<?php

namespace Ekyna\Component\Commerce\Pricing\EventListener;

use Ekyna\Component\Commerce\Exception\IllegalOperationException;
use Ekyna\Component\Commerce\Exception\InvalidArgumentException;
use Ekyna\Component\Commerce\Exception\RuntimeException;
use Ekyna\Component\Commerce\Pricing\Model\TaxGroupInterface;
use Ekyna\Component\Commerce\Pricing\Repository\TaxGroupRepositoryInterface;
use Ekyna\Component\Resource\Event\ResourceEventInterface;
use Ekyna\Component\Resource\Persistence\PersistenceHelperInterface;

/**
 * Class TaxGroupListener
 * @package Ekyna\Component\Commerce\Pricing\EventListener
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
class TaxGroupListener
{
    /**
     * @var PersistenceHelperInterface
     */
    protected $persistenceHelper;

    /**
     * @var TaxGroupRepositoryInterface
     */
    protected $taxGroupRepository;

    /**
     * Constructor.
     *
     * @param PersistenceHelperInterface  $persistenceHelper
     * @param TaxGroupRepositoryInterface $taxGroupRepository
     */
    public function __construct(
        PersistenceHelperInterface $persistenceHelper,
        TaxGroupRepositoryInterface $taxGroupRepository
    ) {
        $this->persistenceHelper = $persistenceHelper;
        $this->taxGroupRepository = $taxGroupRepository;
    }

    /**
     * Pre delete event handler.
     *
     * @param ResourceEventInterface $event
     *
     * @throws IllegalOperationException
     */
    public function onPreDelete(ResourceEventInterface $event)
    {
        $taxGroup = $this->getTaxGroupFromEvent($event);

        if ($taxGroup->isDefault()) {
            throw new IllegalOperationException(); // TODO reason message
        }
    }

    /**
     * Insert event handler.
     *
     * @param ResourceEventInterface $event
     */
    public function onInsert(ResourceEventInterface $event)
    {
        $taxGroup = $this->getTaxGroupFromEvent($event);

        $this->fixDefault($taxGroup);
    }

    /**
     * Update event handler.
     *
     * @param ResourceEventInterface $event
     */
    public function onUpdate(ResourceEventInterface $event)
    {
        $taxGroup = $this->getTaxGroupFromEvent($event);

        $this->fixDefault($taxGroup);
    }

    /**
     * Fixes the default tax group.
     *
     * @param TaxGroupInterface $taxGroup
     */
    protected function fixDefault(TaxGroupInterface $taxGroup)
    {
        if (!$this->persistenceHelper->isChanged($taxGroup, ['default'])) {
            return;
        }

        if ($taxGroup->isDefault()) {
            try {
                $previousTaxGroup = $this->taxGroupRepository->findDefault();
            } catch (RuntimeException $e) {
                return;
            }

            if (null === $previousTaxGroup || $previousTaxGroup === $taxGroup) {
                return;
            }

            $previousTaxGroup->setDefault(false);

            $this->persistenceHelper->persistAndRecompute($previousTaxGroup, false);
        }
    }

    /**
     * Returns the tax group from the event.
     *
     * @param ResourceEventInterface $event
     *
     * @return TaxGroupInterface
     * @throws InvalidArgumentException
     */
    protected function getTaxGroupFromEvent(ResourceEventInterface $event)
    {
        $resource = $event->getResource();

        if (!$resource instanceof TaxGroupInterface) {
            throw new InvalidArgumentException('Expected instance of ' . TaxGroupInterface::class);
        }

        return $resource;
    }
}


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

	<title>FCKeditor - Sample</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="robots" content="noindex, nofollow" />
	<link href="../sample.css" rel="stylesheet" type="text/css" />

		FCKeditor - JavaScript - Sample 10

		This sample shows a form with two FCKeditor instance. Both instances share the same
		toolbar, available in the top.

	<form action="sampleposteddata.asp" method="post" target="_blank">
		Normal text field:

		<input name="NormaText" value="Plain Text" />

		FCKeditor 1:

		FCKeditor 2:

		<input type="submit" value="Submit" />
	</form>


text:
<link rel="import" href="../polymer/polymer.html">

<dom-module id="nifti-image">

  <template>

<nifti-image>

    <content></content>

      Cheers,

      {{author.name}}

  </template>

</dom-module>


text:
//
//  VideoRenderer.h
//  HCi571X-ARToolkit
//
//  Created by Dr.-Ing. Rafael Radkowski on 2/20/13.
//  Copyright (c) 2013 Dr.-Ing. Rafael Radkowski. All rights reserved.
//
#pragma once

#include <iostream>

#include <iostream>
#include <math.h>

#include <osg/Group>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Texture2D>
#include <osg/TexEnv>
#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osgGA/TrackballManipulator>
#include <osg/Vec3>
#include <osg/MatrixTransform>
#include <osg/ShapeDrawable>

#ifdef WIN32
#include <windows.h>
#endif

//---------------------------------------------
// Includes the video callback device
#include "VideoTexCallback.h"

//---------------------------------------------
// A shader loader object
#include "GLSL_ShaderLoader.h"

class VideoRenderer
{
public:

    static osg::Geode* createBackgroundObject(void);

    static double getRadius(double x, double y);

    static bool radialCalibration(double k0, double k1);

#ifdef COCOA // Only for Mac OS X Cocoa users
    static void getScreenResolution (int& screenX, int& screenY);
#endif

    /*!
     This function adapts the texture coordinates to meet the field of view and the
     apsect ratio of the screen.
     */
    static double adaptTexCoordToFieldOfView(double fov_display_h, double fov_display_v,
                                      double fov_camera_h, double fov_camera_v,
                                      int& video_w, int& video_h,
                                      double& tex_size_x, double& tex_size_y,
                                      double& offset_x, double& offset_y);

    /*!
     This function creates the texture coordinates for the quads.
     The texture coordinates pose the undistorted set, which
     maps a texture either streched nor compressed onto the quad.
     */
    static void setTextureToRect(osg::Texture2D* texture, int videoWidth, int videoHeight, int textureWidth, int textureHeight);

    /*!
     This function sets a new texture coordinate.
     The index cannot be larger than the specified number of coordinates.
     @param i the column (width);
     @param j the row (height)
     @param tx the x coordinate (width)
     @param ty the y coordinate (height)
     */
    static bool setTextureCoordinateAt(int i, int j, double tx, double ty);

    static osg::Vec2 getTextureCoordinateAt(int i, int j);

    static osg::Group *createSphere(int radius);

    static osg::Group* createSzene(unsigned char* video, int videoWidth, int videoHeight );

    static osg::Group* createSzeneExt(unsigned char* video, int videoWidth, int videoHeight, osg::Texture2D* mask, osg::Texture2D* update = NULL);

};


text:
(function($){
    "use strict";

	$(document).ready(function(){
	    $('.tp-banner').revolution({
			delay:12000,
			startwidth:1600,
			startheight:600,
			hideThumbs:10,

			parallax:"scroll",
			parallaxBgFreeze:"on",
			parallaxLevels:[10,20,30,40,50,60,70,80,90,100],

			fullWidth:"off",
			fullScreen:"on",
			fullScreenOffsetContainer: "",
			fullScreenAlignForce:"on",

			navigationType:"off",
			navigationStyle:"preview4",

			hideArrowsOnMobile:"on",

			touchenabled:"on",
			onHoverStop:"off",
			spinner:"spinner4"
		});

	    $('.tp-banner-mp').revolution({
			delay:12000,
			startwidth:1170,
			startheight:700,
			hideThumbs:10,

			navigationType:"bullet",
			navigationStyle:"preview1",

			hideArrowsOnMobile:"on",

			touchenabled:"on",
			onHoverStop:"off",
			spinner:"spinner4"
		});

	});

})(jQuery);


text:
package edu.pitt.apollo.dataservicerestfrontend.controller;

import com.wordnik.swagger.annotations.*;
import edu.pitt.apollo.exception.SerializationException;
import edu.pitt.apollo.exception.UnsupportedSerializationFormatException;
import edu.pitt.apollo.dataservicerestfrontend.methods.AddRoleToUserMethod;
import edu.pitt.apollo.dataservicerestfrontend.methods.AddUserMethod;
import edu.pitt.apollo.dataservicerestfrontend.methods.AuthenticateUserMethod;
import edu.pitt.apollo.dataservicerestfrontend.methods.AuthorizeUserMethod;
import edu.pitt.apollo.dataservicerestfrontend.methods.DeleteUserMethod;
import edu.pitt.apollo.dataservicerestfrontend.methods.GetSoftwareIdentificationForRunMethod;
import edu.pitt.apollo.services_common.v3_0_2.ApolloSoftwareTypeEnum;
import edu.pitt.apollo.services_common.v3_0_2.SerializationFormat;
import java.math.BigInteger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;

/**
 * Created by dcs27 on 5/15/15. Purpose: This class contains the RESTful interfaces associated with the users collection.
 */
@Controller
@RequestMapping("/ws")
public class UsersController {

	/*--Methods for the Users collection--*/
	/*   @GET
	 @ApiOperation(value ="List users.", notes = "Returns the list of all users in the users collection.", response = String.class)
	 @ApiResponses(value = {
	 @ApiResponse(code = 200, message = "")
	 })
	 @RequestMapping(value = "/users", method = RequestMethod.GET, headers = "Accept=application/xml")
	 public
	 @ResponseBody
	 String getListOfUsers() {
	 return null;
	 }*/
	@GET
	@ApiOperation(value = "Authenticate user.", notes = "Authenticates the user.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/user/{userName}/authenticate", method = RequestMethod.GET, headers = "Accept=application/xml")
	public @ResponseBody
	String authenticateUser(@ApiParam(value = "User name.", required = true) @PathVariable("userName") String userName,
			@ApiParam(value = "Password for user to be authenticated", required = true) @RequestParam("password") String password) throws UnsupportedSerializationFormatException, SerializationException {

		return new AuthenticateUserMethod("", "", SerializationFormat.XML).authenticateUser(userName, password);
	}

	@GET
	@ApiOperation(value = "Authorize user.", notes = "Authorizes the user to run a given software.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/user/{userName}/authorize", method = RequestMethod.GET, headers = "Accept=application/xml")
	public @ResponseBody
	String authorizeUser(@ApiParam(value = "User name.", required = true) @PathVariable("userName") String userName,
			@ApiParam(value = "Password for user to be authorized", required = true) @RequestParam("password") String password,
			@ApiParam(value = "Software name", required = true) @RequestParam("softwareName") String softwareName,
			@ApiParam(value = "Software version", required = true) @RequestParam("softwareVersion") String softwareVersion,
			@ApiParam(value = "Software developer", required = true) @RequestParam("softwareDeveloper") String softwareDeveloper,
			@ApiParam(value = "Apollo software type enum", required = true) @RequestParam("softwareTypeEnum") ApolloSoftwareTypeEnum softwareTypeEnum,
			@ApiParam(value = "Can the user run the software", required = true) @RequestParam("requestToRunSoftware") boolean requestToRunSoftware) throws UnsupportedSerializationFormatException, SerializationException {

		return new AuthorizeUserMethod("", "", SerializationFormat.XML).authorizeUser(userName, password,
				softwareName, softwareVersion, softwareDeveloper, softwareTypeEnum, requestToRunSoftware);
	}

	@POST
//    @ApiImplicitParam(dataType = "string", name = "userInformationXml", paramType = "body", required = true)
	@ApiOperation(value = "Add user.", notes = "Adds the user to the users collection.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/users", method = RequestMethod.POST, headers = "Accept=application/xml")
	public @ResponseBody
	String addUserToUsersList(@ApiParam(value = "Username", required = true) @RequestParam("username") String username,
			@ApiParam(value = "Password", required = true) @RequestParam("password") String password,
			@ApiParam(value = "User name to add", required = true) @RequestParam("userNameToAdd") String uernameToAdd,
			@ApiParam(value = "Password to add", required = true) @RequestParam("passwordToAdd") String passwordToAdd,
			@ApiParam(value = "User email", required = true) @RequestParam("userEmail") String userEmail) throws UnsupportedSerializationFormatException, SerializationException {

		return new AddUserMethod(username, password, SerializationFormat.XML).addUser(uernameToAdd, passwordToAdd, userEmail);
	}
	//We cannot delete the users collection (DELETE) and we cannot PUT (add a collection) to the users collection.

	/*--Methods for the user of the users collection--*/
	/* @GET
	 @ApiOperation(value ="Get user.", notes = "Returns data associated to the given user ID.", response = String.class)
	 @ApiResponses(value = {
	 @ApiResponse(code = 200, message = "")
	 })
	 @RequestMapping(value = "/user/{userId}", method = RequestMethod.GET, headers = "Accept=application/xml")
	 public
	 @ResponseBody
	 String getUserFromUsersCollection(@ApiParam(value = "User ID", required = true) @PathVariable("userId") BigInteger userId) {
	 return null;
	 }*/
	@DELETE
	@ApiOperation(value = "Delete user.", notes = "Removes a user with the given user ID.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/user/{userName}", method = RequestMethod.DELETE, headers = "Accept=application/xml")
	public @ResponseBody
	String deleteUserFromUseresCollection(@ApiParam(value = "Run ID.", required = true) @PathVariable("userName") String nameOfUserToDelete,
			@ApiParam(value = "Username", required = true) @RequestParam("username") String username,
			@ApiParam(value = "Password", required = true) @RequestParam("password") String password) throws UnsupportedSerializationFormatException, SerializationException {

		return new DeleteUserMethod(username, password, SerializationFormat.XML).deleteUser(nameOfUserToDelete);
	}

	/*  @POST
	 @ApiOperation(value ="Edit user.", notes = "Edit data for a user with the given user ID.", response = String.class)
	 @ApiResponses(value = {
	 @ApiResponse(code = 200, message = "")
	 })
	 @RequestMapping(value = "/user/{userId}", method = RequestMethod.POST, headers = "Accept=application/xml")
	 public
	 @ResponseBody
	 String editUserInUsersCollection(@ApiParam(value = "User ID", required = true) @PathVariable("userId") BigInteger userId) {
	 return null;
	 }*/
	//Cannot PUT at this level.

	/*--Methods for the roles of a user of the users collection--*/
	/* @GET
	 @ApiOperation(value ="Get roles for user.", notes = "Returns a list of roles for the given user ID.", response = String.class)
	 @ApiResponses(value = {
	 @ApiResponse(code = 200, message = "")
	 })
	 @RequestMapping(value = "/user/{userId}/roles", method = RequestMethod.GET, headers = "Accept=application/xml")
	 public
	 @ResponseBody
	 String getRolesOfUser(@ApiParam(value = "User ID", required = true) @PathVariable("userId") BigInteger userId) {
	 return null;
	 }*/
	@POST
	@ApiOperation(value = "Add role to user.", notes = "Add a role for the given user ID.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/user/{userId}/roles", method = RequestMethod.POST, headers = "Accept=application/xml")
	public @ResponseBody
	String addRoleToUser(@ApiParam(value = "Username", required = true) @RequestParam("username") String username,
			@ApiParam(value = "Password", required = true) @RequestParam("password") String password,
			@ApiParam(value = "Request object", required = true) @RequestBody String requestBody) throws UnsupportedSerializationFormatException, SerializationException {

		return new AddRoleToUserMethod(username, password, SerializationFormat.XML).addRoleToUser(requestBody);
	}
	//Cannot DELETE all roles of a user (DELETE), and CANNOT PUT a new collection or resource at this level (PUT).

	/*--Methods for individual role of a user--*/
	/*   @DELETE
	 @ApiOperation(value ="Remove role from user.", notes = "Removes a role from the given user ID.", response = String.class)
	 @ApiResponses(value = {
	 @ApiResponse(code = 200, message = "")
	 })
	 @RequestMapping(value = "/user/{userId}/role/{roleId}", method = RequestMethod.DELETE, headers = "Accept=application/xml")
	 public
	 @ResponseBody
	 String getRolesOfUser(@ApiParam(value = "User ID", required = true) @PathVariable("userId") BigInteger userId,@ApiParam(value = "Role ID", required = true) @PathVariable("roleId") BigInteger roleId) {
	 return null;
	 }*/
}


text:
rm -rf dist/*
python setup.py sdist bdist_wheel
twine upload dist/*


text:
^title Embedding

Wren is designed to be a scripting language that lives inside a host
application, so the embedding API is as important as any of its language
features. Designing this API well requires satisfying several constraints:

1. **Wren is dynamically typed, but C is not.** A variable can hold a value of
   any type in Wren, but that's definitely not the case in C unless you define
   some sort of variant type, which ultimately just kicks the problem down the
   road. Eventually, we have to move data across the boundary between statically and dynamically typed code.

2. **Wren uses garbage collection, but C manages memory manually.** GC adds a
   few constraints on the API. The VM must be able to find every Wren object
   that is still usable, even if that object is being referenced from native C
   code. Otherwise, Wren could free an object that's still in use.

    Also, we ideally don't want to let native C code see a bare pointer to a
    chunk of memory managed by Wren. Many garbage collection strategies involve
    [moving objects][] in memory. If we allow C code to point directly to an
    object, that pointer will be left dangling when the object moves. Wren's GC
    doesn't move objects today, but we would like to keep that option for the
    future.

3. **The embedding API needs to be fast.** Users may add layers of abstraction
   on top of the API to make it more pleasant to work with, but the base API
   defines the *maximum* performance you can get out of the system. It's the
   bottom of the stack, so there's no way for a user to optimize around it if
   it's too slow. There is no lower level alternative.

4. **We want the API to be pleasant to use.** This is the last constraint
   because it's the softest. Of course, we want a beautiful, usable API. But we
   really *need* to handle the above, so we're willing to make things a bit more
   of a chore to reach the first three goals.

[moving objects]: https://en.wikipedia.org/wiki/Tracing_garbage_collection#Copying_vs._mark-and-sweep_vs._mark-and-don.27t-sweep

Fortunately, we aren't the first people to tackle this. If you're familiar with
[Lua's C API][lua], you'll find Wren's similar.

[lua]: https://www.lua.org/pil/24.html

### Performance and safety

When code is safely snuggled within the confines of the VM, it's pretty safe.
Method calls are dynamically checked and generate runtime errors which can be
caught and handled. The stack grows if it gets close to overflowing. In general,
when you're within Wren code, it tries very hard to avoid crashing and burning.

This is why you use a high level language after all—it's safer and more
productive than C. C, meanwhile, really assumes you know what you're doing. You
can cast pointers in invalid ways, misinterpret bits, use memory after freeing
it, etc. What you get in return is blazing performance. Many of the reasons C is
fast are because it takes all the governors and guardrails off.

Wren's embedding API defines the border between those worlds, and takes on some
of the characteristics of C. When you call any of the embedding API functions,
it assumes you are calling them correctly. If you invoke a Wren method from C
that expects three arguments, it trusts that you gave it three arguments.

In debug builds, Wren has assertions to check as many things as it can, but in
release builds, Wren expects you to do the right thing. This means you need to
take care when using the embedding API, just like you do in all C code you
write. In return, you get an API that is quite fast.

## Including Wren

There are two (well, three) ways to get the Wren VM into your program:

1.  **Link to the static or dynamic library.** When you [build Wren][build], it
    generates both shared and static libraries in `lib` that you can link to.

2.  **Include the source directly in your application.** If you want to include
    the source directly in your program, you don't need to run any build steps.
    Just add the source files in `src/vm` to your project. They should compile
    cleanly as C99 or C++98 or anything later.

[build]: ../getting-started.html

In either case, you also want to add `src/include` to your include path so you
can find the [public header for Wren][wren.h]:

[wren.h]: https://github.com/munificent/wren/blob/master/src/include/wren.h

    :::c
    #include "wren.h"

Wren depends only on the C standard library, so you don't usually need to link
to anything else. On some platforms (at least BSD and Linux) some of the math
functions in `math.h` are implemented in a separate library, [libm][], that you
have to explicitly link to.

[libm]: https://en.wikipedia.org/wiki/C_mathematical_functions#libm

If your program is in C++ but you are linking to the Wren library compiled as C,
then you'll need to handle the calling convention differences like so:

    :::c
    extern "C" {
    #include "wren.h"
    }

(Wren's source can be compiled as either C or C++, so you can skip this by
compiling the whole thing yourself as C++. Whatever floats your boat.)

## Creating a Wren VM

Once you've integrated the code into your executable, you need to create a
virtual machine. To do that, you create a WrenConfiguration:

    :::c
    WrenConfiguration config;
    wrenInitConfiguration(&config);

This gives you a basic configuration that has reasonable defaults for
everything. If you don't need to tweak stuff, you can leave it at that. We'll
[learn more][configuration] about what you can configure later.

[configuration]: configuration.html

With this ready, you can create the VM:

    :::c
    WrenVM* vm = wrenNewVM(&config);

This allocates memory for a new VM and initializes it. The Wren C implementation
has no global state, so every single bit of data Wren uses is bundled up inside
a WrenVM. You can have multiple Wren VMs running independently of each other
without any problems, even concurrently on different threads.

`wrenNewVM()` stores its own copy of the configuration, so after calling it, you
can discard the `WrenConfiguration` struct you filled in. Now you have a live
VM, waiting to run some code!

## Executing Wren code

You execute a string of Wren source code like so:

    :::c
    WrenInterpretResult result = wrenInterpret(vm,
        "System.print(\"I am running in a VM!\")");

The string is a series of one or more statements separated by newlines. Wren
copies the string, so you can free it after calling this. When you call
`wrenInterpret()`, Wren first compiles your source to bytecode. If an error
occurs, it returns immediately with `WREN_RESULT_COMPILE_ERROR`.

Otherwise, Wren spins up a new [fiber][] and executes the code in that. Your
code can in turn spawn whatever other fibers it wants. It keeps running fibers
until they all complete or one [suspends].

[fiber]: ../concurrency.html
[suspends]: ../modules/core/fiber.html#fiber.suspend()

If a [runtime error][] occurs (and another fiber doesn't handle it), Wren aborts
fibers all the way back to the main one and returns `WREN_RESULT_RUNTIME_ERROR`.
Otherwise, when the last fiber successfully returns, it returns
`WREN_RESULT_SUCCESS`.

[runtime error]: error-handling.html

All code passed to `wrenInterpret()` runs in a special "main" module. That way,
top-level names defined in one call can be accessed in later ones. It's similar
to a REPL session.

## Shutting down a VM

Once the party is over and you're ready to end your relationship with a VM, you
need to free any memory it allocated. You do that like so:

    :::c
    wrenFreeVM(vm);

After calling that, you obviously cannot use the `WrenVM*` you passed to it
again. It's dead.

Note that Wren will yell at you if you still have any live [WrenHandle][handle]
objects when you call this. This makes sure you haven't lost track of any of
them (which leaks memory) and you don't try to use any of them after the VM has
been freed.

[handle]: slots-and-handles.html#handles

Next, we'll learn to make that VM do useful stuff...

Slots and Handles →


text:
#pragma once

#ifndef AV_RTP_SESSION_H
#define AV_RTP_SESSION_H

#include <jrtplib3/rtpsession.h>
#include "Worker.h"

extern jrtplib::RTPMemoryManager* GetRTPMemMgr();

class AVRTPSession : public jrtplib::RTPSession, public CWorker
{
    typedef jrtplib::RTPSession super;
public:
    AVRTPSession(jrtplib::RTPRandom *rnd = 0, jrtplib::RTPMemoryManager *mgr = ::GetRTPMemMgr());
    virtual ~AVRTPSession(void);

    // Override to prevent sending if stopped working
    int SendPacket(const void *data,size_t len,
        uint8_t pt,bool mark,uint32_t timestampinc);

protected:
	/** Allocate a user defined transmitter.
	 *  In case you specified in the Create function that you want to use a
	 *  user defined transmitter, you should override this function. The RTPTransmitter
	 *  instance returned by this function will then be used to send and receive RTP and
	 *  RTCP packets. Note that when the session is destroyed, this RTPTransmitter
	 *  instance will be destroyed as well.
 	 */
	virtual jrtplib::RTPTransmitter *NewUserDefinedTransmitter()						{ return 0; }

	/** Is called when an incoming RTP packet is about to be processed. */
	virtual void OnRTPPacket(jrtplib::RTPPacket *pack,const jrtplib::RTPTime &receivetime,
	                         const jrtplib::RTPAddress *senderaddress);

	/** Is called when an incoming RTCP packet is about to be processed. */
	virtual void OnRTCPCompoundPacket(jrtplib::RTCPCompoundPacket *pack,const jrtplib::RTPTime &receivetime,
	                                  const jrtplib::RTPAddress *senderaddress);

	/** Is called when an SSRC collision was detected.
	 *  Is called when an SSRC collision was detected. The instance \c srcdat is the one present in
	 *  the table, the address \c senderaddress is the one that collided with one of the addresses
	 *  and \c isrtp indicates against which address of \c srcdat the check failed.
	 */
	virtual void OnSSRCCollision(jrtplib::RTPSourceData *srcdat,const jrtplib::RTPAddress *senderaddress,bool isrtp)	{ }

	/** Is called when another CNAME was received than the one already present for source \c srcdat. */
	virtual void OnCNAMECollision(jrtplib::RTPSourceData *srcdat,const jrtplib::RTPAddress *senderaddress,
	                              const uint8_t *cname,size_t cnamelength)				{ }

	/** Is called when a new entry \c srcdat is added to the source table. */
	virtual void OnNewSource(jrtplib::RTPSourceData *srcdat)			 				;

	/** Is called when the entry \c srcdat is about to be deleted from the source table. */
	virtual void OnRemoveSource(jrtplib::RTPSourceData *srcdat)						;

	/** Is called when participant \c srcdat is timed out. */
	virtual void OnTimeout(jrtplib::RTPSourceData *srcdat)							;

	/** Is called when participant \c srcdat is timed after having sent a BYE packet. */
	virtual void OnBYETimeout(jrtplib::RTPSourceData *srcdat)						;

	/** Is called when an RTCP APP packet \c apppacket has been received at time \c receivetime
	 *  from address \c senderaddress.
	 */
	virtual void OnAPPPacket(jrtplib::RTCPAPPPacket *apppacket,const jrtplib::RTPTime &receivetime,
	                         const jrtplib::RTPAddress *senderaddress)					;

	/** Is called when an unknown RTCP packet type was detected. */
	virtual void OnUnknownPacketType(jrtplib::RTCPPacket *rtcppack,const jrtplib::RTPTime &receivetime,
	                                 const jrtplib::RTPAddress *senderaddress)				;

	/** Is called when an unknown packet format for a known packet type was detected. */
	virtual void OnUnknownPacketFormat(jrtplib::RTCPPacket *rtcppack,const jrtplib::RTPTime &receivetime,
	                                   const jrtplib::RTPAddress *senderaddress)				;

	/** Is called when the SDES NOTE item for source \c srcdat has been timed out. */
	virtual void OnNoteTimeout(jrtplib::RTPSourceData *srcdat)						;

	/** Is called when a BYE packet has been processed for source \c srcdat. */
	virtual void OnBYEPacket(jrtplib::RTPSourceData *srcdat)							;

	/** Is called when an RTCP compound packet has just been sent (useful to inspect outgoing RTCP data). */
	virtual void OnSendRTCPCompoundPacket(jrtplib::RTCPCompoundPacket *pack)					;

#ifdef RTP_SUPPORT_THREAD

    /** Is called when error \c errcode was detected in the poll thread. */
	virtual void OnPollThreadError(int errcode);

	/** Is called each time the poll thread loops.
	 *  Is called each time the poll thread loops. This happens when incoming data was
	 *  detected or when it's time to send an RTCP compound packet.
	 */
	virtual void OnPollThreadStep();

	/** Is called when the poll thread is started.
	 *  Is called when the poll thread is started. This happens just before entering the
	 *  thread main loop.
	 *  \param stop This can be used to stop the thread immediately without entering the loop.
	*/
	virtual void OnPollThreadStart(bool &stop);

	/** Is called when the poll thread is going to stop.
	 *  Is called when the poll thread is going to stop. This happens just before termitating the thread.
	 */
	virtual void OnPollThreadStop();

#endif // RTP_SUPPORT_THREAD

    virtual void ProcessRTPPacket(const jrtplib::RTPSourceData &srcdat,const jrtplib::RTPPacket &rtppack);

public:
    virtual void Start() {
        CWorker::Start();
        //m_bWorking = true;
    }

    virtual void Stop() {
        CWorker::Stop();
        //m_bWorking = false;
        this->BYEDestroy(jrtplib::RTPTime(0.5), NULL, 0);
    }
//
//    virtual bool IsWorking() const { return m_bWorking; }
//
//private:
//    bool m_bWorking;
};

#endif//AV_RTP_SESSION_H


text:
declare module "M" {
    export = A;
}


text:
<!DOCTYPE html>

    <title>HTML Table Widget</title>

    <link rel="stylesheet" href="css/bootstrap-slate.min.css">
    <link rel="stylesheet" href="css/example2.css">

    <link rel="stylesheet" href="css/samples.css">

                <button type="button" class="btn btn-block btn-default" onclick="sendTable()">Send</button>


text:
1. CoffeeScript Syntax
2. CoffeeScript Class
3. CoffeeScript Idioms
4. Compiling CoffeScript
5. The Good Parts
6. The Little Conclusion

## Resources

* [1-6 Chapters] http://arcturo.github.io/library/coffeescript/index.html


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

<title>org.apache.cassandra.io.sstable (apache-cassandra API)</title>
<meta name="date" content="2016-04-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.apache.cassandra.io.sstable

Interface Summary

Interface
Description

IndexSummaryManagerMBean

ISSTableScanner

An ISSTableScanner is an abstraction allowing multiple SSTableScanners to be
 chained together under the hood.

Class Summary

Class
Description

AbstractSSTableSimpleWriter

BloomFilterTracker

ColumnNameHelper

ColumnStats

ColumnStats holds information about the columns for one row inside sstable

ColumnStats.MaxIntTracker

ColumnStats.MaxLongTracker

ColumnStats.MinLongTracker

Component

SSTables are made up of multiple components in separate files.

CQLSSTableWriter

Utility to write SSTables.

CQLSSTableWriter.Builder

A Builder for a CQLSSTableWriter object.

Descriptor

A SSTable is described by the keyspace and column family it contains data
 for, a generation (where higher generations contain more recent data) and
 an alphabetic version string.

Downsampling

IndexHelper

Provides helper to serialize, deserialize and use column indexes.

IndexHelper.IndexInfo

IndexHelper.IndexInfo.Serializer

IndexSummary

IndexSummary.IndexSummarySerializer

IndexSummaryBuilder

IndexSummaryBuilder.ReadableBoundary

Represents a boundary that is guaranteed fully readable in the summary, index file and data file.

IndexSummaryManager

Manages the fixed-size memory pool for index summaries, periodically resizing them
 in order to give more memory to hot sstables and less memory to cold sstables.

IndexSummaryRedistribution

KeyIterator

ReducingKeyIterator

Caller must acquire and release references to the sstables used here.

SnapshotDeletingTask

SSTable

This class is built on top of the SequenceFile.

SSTableDeletingTask

SSTableIdentityIterator

SSTableLoader

Cassandra SSTable bulk loader.

SSTableLoader.Client

SSTableRewriter

Wraps one or more writers as output for rewriting one or more readers: every sstable_preemptive_open_interval_in_mb
 we look in the summary we're collecting for the latest writer for the penultimate key that we know to have been fully
 flushed to the index file, and then double check that the key is fully present in the flushed data file.

SSTableSimpleUnsortedWriter
Deprecated

this class is depracted in favor of CQLSSTableWriter.

SSTableSimpleWriter
Deprecated

this class is depracted in favor of CQLSSTableWriter.

Enum Summary

Enum
Description

Component.Type

Descriptor.Type

Exception Summary

Exception
Description

CorruptSSTableException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2016 The Apache Software Foundation


text:
package command.math;

import command.Command;
import parser.ParseFormatException;
/**
 *
 * @author Mike Ma (ym67)
 *
 */
class Remainder implements Command {

	@Override
	public double evaluate(Command... args) throws ParseFormatException {
		return args[0].evaluate() % args[1].evaluate();
	}

}


text:
using System.Collections.Generic;
using System.Linq;
using Dapper;

namespace SteamDatabaseBackend
{
    static class StoreQueue
    {
        public static void AddAppToQueue(uint appID)
        {
            InsertQuery(new List<uint> { appID }, "app");
        }

        public static void AddAppToQueue(IEnumerable<uint> appIDs)
        {
            InsertQuery(appIDs, "app");
        }

        public static void AddPackageToQueue(uint packageID)
        {
            InsertQuery(new List<uint> { packageID }, "sub");
        }

        public static void AddPackageToQueue(IEnumerable<uint> packageIDs)
        {
            InsertQuery(packageIDs, "sub");
        }

        private static void InsertQuery(IEnumerable<uint> ids, string type)
        {
            var items = ids.Select(x => new StoreUpdateQueue { ID = x, Type = type });

            using (var db = Database.GetConnection())
            {
                db.Execute("INSERT INTO `StoreUpdateQueue` (`ID`, `Type`) VALUES (@ID, @Type) ON DUPLICATE KEY UPDATE `ID` = `ID`", items);
            }
        }
    }
}


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

<TITLE>
GreedyOverselection
</TITLE>

<META NAME="date" CONTENT="2013-05-03">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

ec.select

Class GreedyOverselection

java.lang.Object
  ec.BreedingSource
      ec.SelectionMethod
          ec.select.GreedyOverselection

All Implemented Interfaces:
Prototype, Setup, RandomChoiceChooser, java.io.Serializable, java.lang.Cloneable

public class GreedyOverselection
extends SelectionMethod

GreedyOverselection is a SelectionMethod which implements Koza-style
 fitness-proportionate greedy overselection.  Not appropriate for
 multiobjective fitnesses.

 This selection method first
 divides individuals in a population into two groups: the "good"
 ("top") group, and the "bad" ("bottom") group.  The best top
 percent of individuals in the population go into the good group.
 The rest go into the "bad" group.  With a certain probability (determined
 by the gets setting), an individual will be picked out of the
 "good" group.  Once we have determined which group the individual
 will be selected from, the individual is picked using fitness proportionate
 selection in that group, that is, the likelihood he is picked is
 proportionate to his fitness relative to the fitnesses of others in his
 group.

 All this is expensive to
 set up and bring down, so it's not appropriate for steady-state evolution.
 If you're not familiar with the relative advantages of
 selection methods and just want a good one,
 use TournamentSelection instead.

 Note: Fitnesses must be non-negative.  0 is assumed to be the worst fitness.

Typical Number of Individuals Produced Per <tt>produce(...)</tt> call

 Always 1.

Parameters

base.<tt>top</tt>

 0.0 <= float <= 1.0
 (the percentage of the population going into the "good" (top) group)

base.<tt>gets</tt>

 0.0 <= float <= 1.0
 (the likelihood that an individual will be picked from the "good" group)

Default Base

 select.greedy

See Also:
Serialized Form

Field Summary

 float
gets_n_percent

static java.lang.String
P_GETS

static java.lang.String
P_GREEDY

static java.lang.String
P_TOP

 float[]
sortedFitOver

 float[]
sortedFitUnder

 int[]
sortedPop

          Sorted population -- since I *have* to use an int-sized
        individual (short gives me only 16K),
        I might as well just have pointers to the
        population itself.

 float
top_n_percent

Fields inherited from class ec.SelectionMethod

INDS_PRODUCED

Fields inherited from class ec.BreedingSource

NO_PROBABILITY, P_PROB, probability

Constructor Summary

GreedyOverselection()

Method Summary

 Parameter
defaultBase()

          Returns the default base for this prototype.

 void
finishProducing(EvolutionState s,
                int subpopulation,
                int thread)

          A default version of finishProducing, which does nothing.

 void
prepareToProduce(EvolutionState s,
                 int subpopulation,
                 int thread)

          A default version of prepareToProduce which does nothing.

 int
produce(int subpopulation,
        EvolutionState state,
        int thread)

          An alternative form of "produce" special to Selection Methods;
        selects an individual from the given subpopulation and
        returns its position in that subpopulation.

 void
setup(EvolutionState state,
      Parameter base)

          Sets up the BreedingPipeline.

Methods inherited from class ec.SelectionMethod

produce, produces, typicalIndsProduced

Methods inherited from class ec.BreedingSource

clone, getProbability, pickRandom, preparePipeline, setProbability, setupProbabilities

Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

sortedFitOver

public float[] sortedFitOver

sortedFitUnder

public float[] sortedFitUnder

sortedPop

public int[] sortedPop

Sorted population -- since I *have* to use an int-sized
        individual (short gives me only 16K),
        I might as well just have pointers to the
        population itself.  :-(

P_GREEDY

public static final java.lang.String P_GREEDY

See Also:
Constant Field Values

P_TOP

public static final java.lang.String P_TOP

See Also:
Constant Field Values

P_GETS

public static final java.lang.String P_GETS

See Also:
Constant Field Values

top_n_percent

public float top_n_percent

gets_n_percent

public float gets_n_percent

Constructor Detail

GreedyOverselection

public GreedyOverselection()

Method Detail

defaultBase

public Parameter defaultBase()

Description copied from interface: Prototype

Returns the default base for this prototype.
        This should generally be implemented by building off of the static base()
        method on the DefaultsForm object for the prototype's package. This should
        be callable during setup(...).

setup

public void setup(EvolutionState state,
                  Parameter base)

Description copied from class: BreedingSource

Sets up the BreedingPipeline.  You can use state.output.error here
        because the top-level caller promises to call exitIfErrors() after calling
        setup.  Note that probability might get modified again by
        an external source if it doesn't normalize right.

The most common modification is to normalize it with some other
        set of probabilities, then set all of them up in increasing summation;
        this allows the use of the fast static BreedingSource-picking utility
        method, BreedingSource.pickRandom(...).  In order to use this method,
        for example, if four
        breeding source probabilities are {0.3, 0.2, 0.1, 0.4}, then
        they should get normalized and summed by the outside owners
        as: {0.3, 0.5, 0.6, 1.0}.

Specified by:
setup in interface Prototype
Specified by:
setup in interface Setup
Overrides:
setup in class BreedingSource

See Also:
Prototype.setup(EvolutionState,Parameter)

prepareToProduce

public void prepareToProduce(EvolutionState s,
                             int subpopulation,
                             int thread)

Description copied from class: SelectionMethod

A default version of prepareToProduce which does nothing.

Overrides:
prepareToProduce in class SelectionMethod

produce

public int produce(int subpopulation,
                   EvolutionState state,
                   int thread)

Description copied from class: SelectionMethod

An alternative form of "produce" special to Selection Methods;
        selects an individual from the given subpopulation and
        returns its position in that subpopulation.

Specified by:
produce in class SelectionMethod

finishProducing

public void finishProducing(EvolutionState s,
                            int subpopulation,
                            int thread)

Description copied from class: SelectionMethod

A default version of finishProducing, which does nothing.

Overrides:
finishProducing in class SelectionMethod

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
from datetime import datetime
import glob
import optparse
import os
import re

import cloud_storage_test_base
import page_sets
import pixel_expectations

from telemetry import benchmark
from telemetry.image_processing import image_util
from telemetry.page import page_test
from telemetry.util import cloud_storage

test_data_dir = os.path.abspath(os.path.join(
    os.path.dirname(__file__), '..', '..', 'data', 'gpu'))

default_reference_image_dir = os.path.join(test_data_dir, 'gpu_reference')

test_harness_script = r"""
  var domAutomationController = {};

  domAutomationController._succeeded = false;
  domAutomationController._finished = false;

  domAutomationController.setAutomationId = function(id) {}

  domAutomationController.send = function(msg) {
    domAutomationController._finished = true;

    if(msg.toLowerCase() == "success") {
      domAutomationController._succeeded = true;
    } else {
      domAutomationController._succeeded = false;
    }
  }

  window.domAutomationController = domAutomationController;
"""

class PixelTestFailure(Exception):
  pass

def _DidTestSucceed(tab):
  return tab.EvaluateJavaScript('domAutomationController._succeeded')

class _PixelValidator(cloud_storage_test_base.ValidatorBase):
  def CustomizeBrowserOptions(self, options):
    options.AppendExtraBrowserArgs('--enable-gpu-benchmarking')

  def ValidateAndMeasurePage(self, page, tab, results):
    if not _DidTestSucceed(tab):
      raise page_test.Failure('Page indicated a failure')

    if not tab.screenshot_supported:
      raise page_test.Failure('Browser does not support screenshot capture')

    screenshot = tab.Screenshot(5)

    if screenshot is None:
      raise page_test.Failure('Could not capture screenshot')

    if hasattr(page, 'test_rect'):
      screenshot = image_util.Crop(
          screenshot, page.test_rect[0], page.test_rect[1],
          page.test_rect[2], page.test_rect[3])

    image_name = self._UrlToImageName(page.display_name)

    if self.options.upload_refimg_to_cloud_storage:
      if self._ConditionallyUploadToCloudStorage(image_name, page, tab,
                                                 screenshot):
        # This is the new reference image; there's nothing to compare against.
        ref_png = screenshot
      else:
        # There was a preexisting reference image, so we might as well
        # compare against it.
        ref_png = self._DownloadFromCloudStorage(image_name, page, tab)
    elif self.options.download_refimg_from_cloud_storage:
      # This bot doesn't have the ability to properly generate a
      # reference image, so download it from cloud storage.
      try:
        ref_png = self._DownloadFromCloudStorage(image_name, page, tab)
      except cloud_storage.NotFoundError as e:
        # There is no reference image yet in cloud storage. This
        # happens when the revision of the test is incremented or when
        # a new test is added, because the trybots are not allowed to
        # produce reference images, only the bots on the main
        # waterfalls. Report this as a failure so the developer has to
        # take action by explicitly suppressing the failure and
        # removing the suppression once the reference images have been
        # generated. Otherwise silent failures could happen for long
        # periods of time.
        raise page_test.Failure('Could not find image %s in cloud storage' %
                                image_name)
    else:
      # Legacy path using on-disk results.
      ref_png = self._GetReferenceImage(self.options.reference_dir,
          image_name, page.revision, screenshot)

    # Test new snapshot against existing reference image
    if not image_util.AreEqual(ref_png, screenshot, tolerance=2):
      if self.options.test_machine_name:
        self._UploadErrorImagesToCloudStorage(image_name, screenshot, ref_png)
      else:
        self._WriteErrorImages(self.options.generated_dir, image_name,
                               screenshot, ref_png)
      raise page_test.Failure('Reference image did not match captured screen')

  def _DeleteOldReferenceImages(self, ref_image_path, cur_revision):
    if not cur_revision:
      return

    old_revisions = glob.glob(ref_image_path + "_*.png")
    for rev_path in old_revisions:
      m = re.match(r'^.*_(\d+)\.png$', rev_path)
      if m and int(m.group(1)) < cur_revision:
        print 'Found deprecated reference image. Deleting rev ' + m.group(1)
        os.remove(rev_path)

  def _GetReferenceImage(self, img_dir, img_name, cur_revision, screenshot):
    if not cur_revision:
      cur_revision = 0

    image_path = os.path.join(img_dir, img_name)

    self._DeleteOldReferenceImages(image_path, cur_revision)

    image_path = image_path + '_' + str(cur_revision) + '.png'

    try:
      ref_png = image_util.FromPngFile(image_path)
    except IOError:
      ref_png = None

    if ref_png is not None:
      return ref_png

    print 'Reference image not found. Writing tab contents as reference.'

    self._WriteImage(image_path, screenshot)
    return screenshot

class Pixel(cloud_storage_test_base.TestBase):
  test = _PixelValidator

  @classmethod
  def AddBenchmarkCommandLineArgs(cls, group):
    super(Pixel, cls).AddBenchmarkCommandLineArgs(group)
    group.add_option('--reference-dir',
        help='Overrides the default on-disk location for reference images '
        '(only used for local testing without a cloud storage account)',
        default=default_reference_image_dir)

  def CreatePageSet(self, options):
    page_set = page_sets.PixelTestsPageSet()
    for page in page_set.pages:
      page.script_to_evaluate_on_commit = test_harness_script
    return page_set

  def CreateExpectations(self):
    return pixel_expectations.PixelExpectations()


text:
<?php
/**
 * Formatter for merge log entries.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later
 * @since 1.25
 */

/**
 * This class formats merge log entries.
 *
 * @since 1.25
 */
class MergeLogFormatter extends LogFormatter {
	public function getPreloadTitles() {
		$params = $this->extractParameters();

		return [ Title::newFromText( $params[3] ) ];
	}

	protected function getMessageParameters() {
		$params = parent::getMessageParameters();
		$oldname = $this->makePageLink( $this->entry->getTarget(), [ 'redirect' => 'no' ] );
		$newname = $this->makePageLink( Title::newFromText( $params[3] ) );
		$params[2] = Message::rawParam( $oldname );
		$params[3] = Message::rawParam( $newname );
		$params[4] = $this->context->getLanguage()
			->userTimeAndDate( $params[4], $this->context->getUser() );
		return $params;
	}

	public function getActionLinks() {
		if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) // Action is hidden
			|| !$this->context->getUser()->isAllowed( 'mergehistory' )
		) {
			return '';
		}

		// Show unmerge link
		$params = $this->extractParameters();
		$revert = Linker::linkKnown(
			SpecialPage::getTitleFor( 'MergeHistory' ),
			$this->msg( 'revertmerge' )->escaped(),
			[],
			[
				'target' => $params[3],
				'dest' => $this->entry->getTarget()->getPrefixedDBkey(),
				'mergepoint' => $params[4],
				'submitted' => 1 // show the revisions immediately
			]
		);

		return $this->msg( 'parentheses' )->rawParams( $revert )->escaped();
	}

	protected function getParametersForApi() {
		$entry = $this->entry;
		$params = $entry->getParameters();

		static $map = [
			'4:title:dest',
			'5:timestamp:mergepoint',
			'4::dest' => '4:title:dest',
			'5::mergepoint' => '5:timestamp:mergepoint',
		];
		foreach ( $map as $index => $key ) {
			if ( isset( $params[$index] ) ) {
				$params[$key] = $params[$index];
				unset( $params[$index] );
			}
		}

		return $params;
	}
}


text:
package org.op4j.operators.impl.fn.map;

import java.util.Map;

import org.javaruntype.type.Type;
import org.op4j.functions.Function;
import org.op4j.functions.IFunction;
import org.op4j.operators.impl.AbstractOperator;
import org.op4j.operators.intf.map.ILevel2MapEntriesKeyOperator;
import org.op4j.operators.qualities.UniqFnOperator;
import org.op4j.target.Target;
import org.op4j.target.Target.CastType;
import org.op4j.target.Target.Normalisation;

/**
 *
 * @since 1.0
 *
 * @author Daniel Fernández
 *
 */
public final class Level2MapEntriesKeyOperator<I,K,V> extends AbstractOperator
        implements UniqFnOperator<I,Map<K,V>>, ILevel2MapEntriesKeyOperator<I,K,V> {

    public Level2MapEntriesKeyOperator(final Target target) {
        super(target);
    }

    public Level1MapEntriesOperator<I,K, V> endOn() {
        return new Level1MapEntriesOperator<I,K, V>(getTarget().endOn());
    }

    public <X> Level2MapEntriesKeyOperator<I,X, V> castTo(final Type<X> type) {
        return new Level2MapEntriesKeyOperator<I,X, V>(getTarget().cast(CastType.OBJECT, type));
    }

    public Function<I,Map<K, V>> get() {
        return endOn().endFor().get();
    }

    public Level2MapEntriesKeySelectedOperator<I,K, V> ifTrue(final IFunction<? super K,Boolean> eval) {
        return new Level2MapEntriesKeySelectedOperator<I,K, V>(getTarget().selectMatching(eval));
    }

    public Level2MapEntriesKeySelectedOperator<I,K, V> ifFalse(final IFunction<? super K,Boolean> eval) {
        return new Level2MapEntriesKeySelectedOperator<I,K, V>(getTarget().selectNotMatching(eval));
    }

    public Level2MapEntriesKeySelectedOperator<I,K, V> ifNotNull() {
        return new Level2MapEntriesKeySelectedOperator<I,K, V>(getTarget().selectNotNull());
    }

    public Level2MapEntriesKeySelectedOperator<I,K, V> ifNull() {
        return new Level2MapEntriesKeySelectedOperator<I,K, V>(getTarget().selectNull());
    }

    public <X> Level2MapEntriesKeyOperator<I,X, V> exec(final IFunction<? super K,X> function) {
        return new Level2MapEntriesKeyOperator<I,X, V>(getTarget().execute(function, Normalisation.NONE));
    }

    public Level2MapEntriesKeyOperator<I,K, V> replaceWith(final K replacement) {
        return new Level2MapEntriesKeyOperator<I,K, V>(getTarget().replaceWith(replacement, Normalisation.NONE));
    }

    public Level2MapEntriesKeyOperator<I,K, V> replaceIfNullWith(final K replacement) {
        return ifNull().replaceWith(replacement).endIf();
    }

    public Level2MapEntriesKeyOperator<I, K, V> execIfFalse(final IFunction<? super K, Boolean> eval, final IFunction<? super K, ? extends K> function) {
        return new Level2MapEntriesKeyOperator<I, K, V>(getTarget().executeIfFalse(eval, function, null, Normalisation.NONE));
    }

    public <X> Level2MapEntriesKeyOperator<I, X, V> execIfFalse(final IFunction<? super K, Boolean> eval, final IFunction<? super K, X> function, final IFunction<? super K, X> elseFunction) {
        return new Level2MapEntriesKeyOperator<I, X, V>(getTarget().executeIfFalse(eval, function, elseFunction, Normalisation.NONE));
    }

    public Level2MapEntriesKeyOperator<I, K, V> execIfNotNull(final IFunction<? super K, ? extends K> function) {
        return new Level2MapEntriesKeyOperator<I, K, V>(getTarget().executeIfNotNull(function, null, Normalisation.NONE));
    }

    public <X> Level2MapEntriesKeyOperator<I, X, V> execIfNotNull(final IFunction<? super K, X> function, final IFunction<? super K, X> elseFunction) {
        return new Level2MapEntriesKeyOperator<I, X, V>(getTarget().executeIfNotNull(function, elseFunction, Normalisation.NONE));
    }

    public Level2MapEntriesKeyOperator<I, K, V> execIfNull(final IFunction<? super K, ? extends K> function) {
        return new Level2MapEntriesKeyOperator<I, K, V>(getTarget().executeIfNull(function, null, Normalisation.NONE));
    }

    public <X> Level2MapEntriesKeyOperator<I, X, V> execIfNull(final IFunction<? super K, X> function, final IFunction<? super K, X> elseFunction) {
        return new Level2MapEntriesKeyOperator<I, X, V>(getTarget().executeIfNull(function, elseFunction, Normalisation.NONE));
    }

    public Level2MapEntriesKeyOperator<I, K, V> execIfTrue(final IFunction<? super K, Boolean> eval, final IFunction<? super K, ? extends K> function) {
        return new Level2MapEntriesKeyOperator<I, K, V>(getTarget().executeIfTrue(eval, function, null, Normalisation.NONE));
    }

    public <X> Level2MapEntriesKeyOperator<I, X, V> execIfTrue(final IFunction<? super K, Boolean> eval, final IFunction<? super K, X> function, final IFunction<? super K, X> elseFunction) {
        return new Level2MapEntriesKeyOperator<I, X, V>(getTarget().executeIfTrue(eval, function, elseFunction, Normalisation.NONE));
    }

}


text:
As part of working with the ISB-CGC web app, you will have created cohorts, represented by lists
of barcodes. This short tutorial shows how to retrieve your cohorts, query for sample details,
and compose a BigQuery, all from within the R environment.

The isb-cgc project has a collection of web services called 'endpoints', which accept
and return information. The endpoints allow the user to interact with the isb-cgc system programmatically,
or for a client application to do so on behalf of the user.

The ISBCGCExamples package contains a number of "wrapper" functions, that make calling
the endpoints possible from the R environment. These are just examples, and much
more is possible. See the documentation to get more ideas:

http://isb-cancer-genomics-cloud.readthedocs.io/en/latest/sections/progapi/Programmatic-API.html#isb-cgc-api

To get started, we load up R, and import the ISBCGCExamples library.

```r
library(ISBCGCExamples)
library(bigrquery)
```

### Creating a token

The first step is creating a token. This token contains your authentication
status, and lets the service know about what information is available to you.

```r
my_token <- isb_init()
```

Calling the isb_init function is going to open a browser window that lets you
authenticate with Google.

### Listing cohorts

To get a listing of the previously created cohorts, we can use the list_cohorts
function that takes a token, and returns a list with items including 'count',
'items', 'kind', and 'etag'. The count shows the number of saved cohorts and
the items contains information about the cohorts.

```r
my_cohorts <- list_cohorts(my_token)
names(my_cohorts)
```

```
## [1] "count" "items" "kind"  "etag"
```

If there is a count of four, then the my_cohorts$items list will have length four.
Each item has a name. We can use the lapply function (list-apply) to get the
names out of each list element.

```r
lapply(my_cohorts$items, function(x) x$name)
```

```
##[[1]]
##[1] "All TCGA Data"

##[[2]]
##[1] "HPV_cohort"

##[[[3]]
##[[1] "GBM_Adult_TP"

##[[[4]]
##[[1] "BRCA_Adult_TP"

##[[[5]]
##[[1] "HNSC_Adult_TP_and_NT"
```

Also, importantly, each element in 'items' has an 'id', which is used when we
do further queries on the cohort.

```r
lapply(my_cohorts$items, function(x) x$id)
```

```
##[[[1]]
##[[1] "1"

##[[[2]]
##[[1] "403"

##[[[3]]
##[[1] "847"

##[[[4]]
##[[1] "848"

##[[[5]]
##[[1] "849"
```

### Getting barcode lists from a cohorts

Now that we have the cohort IDs, we can collect the various barcodes contained
in the cohort. These include patient barcodes, sample barcodes, and platform
specific aliquot barcodes. To do this, we can use the barcodes_from_cohort function.

```r
my_cohort_id <- lapply(my_cohorts$items, function(x) x$id)[[4]]
my_barcodes <- cohort_barcodes(my_cohort_id, my_token)
names(my_barcodes)
```

```
## [1] "name"            "sample_count"    "permission"      "source_type"
## [5] "samples"         "comments"        "id"              "parent_id"
## [9] "patients"        "source_notes"    "filters"         "last_date_saved"
## [13] "email"           "patient_count"   "kind"            "etag"
```

The object returned from barcodes_from_cohort is again a list, this time with
elements 'cohort_id', 'sample_count', 'patient_count', 'patients', and 'samples'.
The patients and samples elements are also lists, but lists of patients or
sample barcodes.

```r
my_barcodes$cases[1:5]
```

```
##[[[1]]
##[[1] "TCGA-E2-A10C"

##[[[2]]
##[[1] "TCGA-B6-A0I8"

[[3]]
[1] "TCGA-C8-A278"

[[4]]
[1] "TCGA-C8-A1HI"

[[5]]
[1] "TCGA-AO-A0J8"
```

```r
my_barcodes$samples[1:5]
```

```
## [[1]]
## [1] "TCGA-2W-A8YY-01A"
##
## [[2]]
## [1] "TCGA-4J-AA1J-01A"
##
## [[3]]
## [1] "TCGA-4P-AA8J-01A"
##
## [[4]]
## [1] "TCGA-BA-4074-01A"
##
## [[5]]
## [1] "TCGA-BA-4075-01A"
```

### Getting details on a sample

Suppose you have a particular sample of interest. We can use the endpoints to
get details about the sample.

```r
my_sample_barcode <- my_barcodes$samples[[1]]
my_sample_details  <- sample_get(my_sample_barcode)

names(my_sample_details)
```

```
## [1] "data_details"       "patient"            "data_details_count"
## [4] "aliquots"           "biospecimen_data"   "kind"
## [7] "etag"
```

```r
my_sample_details$data_details_count
```

```
## [1] 9
```

```r
length(my_sample_details$data_details)
```

```
## [1] 9
```

Here the data_details_count list element tells us that there are 18 "data details"
which contain information like data platforms, file names, paths to cloud storage,
the TCGA data level.

For example, let's see what platforms are represented.

```r
lapply(my_sample_details$data_details, function(x) paste(x$platform, ", ", x$experimental_strategy, sep=""))
```

```
##[[1]]
##[[1] "Clinical,"

##[[2]]
##[[1] "Clinical,"

##[[3]]
##[[1] "Illumina GA,miRNA-Seq"

##[[4]]
##[[1] "Illumina GA,WXS"

##[[5]]
##[[1] "Illumina HiSeq,RNA-Seq"

##[[6]]
##[[1] "Illumina GA,miRNA-Seq"

##[[7]]
##[[1] "Illumina,miRNA-Seq"

##[[8]]
##[[1] "Illumina,WXS"

##[[9]]
##[[1] "Illumina,RNA-Seq"
```

### Moving from the endpoints API to BigQuery

If we have a list of barcodes, then we can programmatically construct a BigQuery.

First let's flatten the list of sample barcodes to a character vector.

```r
# get the character vector of samples
samples <- unlist(my_barcodes$samples)

# SQL strings need to be surrounded by single quotes
samples_with_quotes <- sapply(samples[1:10], function(x) paste("'",x,"'", sep=""))

# then the samples need to be surrounded by parenthesis.
query_samples <- paste("( ", paste(samples_with_quotes, collapse=","), " )")

bq <- paste("
SELECT
   project_short_name,
   AVG(LOG2(normalized_count+1)) as mean_log2_expression
FROM
   [isb-cgc:TCGA_hg19_data_v0.RNAseq_Gene_Expression_UNC_RSEM]
WHERE
   HGNC_gene_symbol = 'EGFR' AND
   sample_barcode IN ", query_samples,"
GROUP BY
   project_short_name"
)

results <- query_exec(bq, project)
results
```

```
##project_short_name mean_log2_expression
##1          TCGA-BRCA             6.668811
```

At this point, if this is your first query, a browser window will pop-up, and
you will need to authenticate for BigQuery.

Since we're working in R, we can take advantage of the great visualization libraries.

### Wrap up

To reiterate, using the endpoints API, we got the list of previously created cohorts, retrieved the
list of sample barcodes, examined data associated with the samples, and constructed
a BigQuery.

More information on the endpoints API and R package example functions can be found at:

http://isb-cancer-genomics-cloud.readthedocs.io/en/latest/sections/progapi/Programmatic-API.html

https://github.com/isb-cgc/examples-R/blob/master/inst/doc/Working_With_Barcode_Lists.md

```r
sessionInfo()
```

```
##R version 3.3.2 (2016-10-31)
##Platform: x86_64-apple-darwin13.4.0 (64-bit)
##Running under: OS X El Capitan 10.11.6
##
##locale:
##[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
##
##attached base packages:
##[1] stats     graphics  grDevices utils     datasets  methods   base
##
##other attached packages:
##[1] httr_1.2.1           bigrquery_0.3.0.9000 ISBCGCExamples_0.1.3
##
##loaded via a namespace (and not attached):
## [1] magrittr_1.5   R6_2.2.0       assertthat_0.1 tools_3.3.2    DBI_0.6
## [6] dplyr_0.5.0    curl_2.4       tibble_1.2     Rcpp_0.12.11   jsonlite_1.3
##[11] httpuv_1.3.3   openssl_0.9.6
```


text:
  Chazelles-sur-Lyon est
      une commune localisée dans le département de Loire en Rhône-Alpes. Elle totalisait 5 041 habitants en 2008.

Le nombre de logements, à Chazelles-sur-Lyon, était réparti en 2011 en 1 108 appartements et 1 516 maisons soit
 un marché relativement équilibré.

À proximité de Chazelles-sur-Lyon sont positionnées géographiquement les villes de
Maringes localisée à 3 km, 606 habitants,
Saint-Médard-en-Forez localisée à 5 km, 837 habitants,
Saint-Symphorien-sur-Coise à 4 km, 3 382 habitants,
Meys localisée à 4 km, 670 habitants,
Pomeys située à 4 km, 939 habitants,
Grézieu-le-Marché située à 2 km, 747 habitants,
 entre autres. De plus, Chazelles-sur-Lyon est située à seulement 22 km de Saint-Étienne.

La ville dispose concernant l'enseignement de deux collèges et un lycée.
S'agissant les moins de 6 ans, la ville est pourvue pour le bien être de sa population de une maternelle et deux écoles primaires.
Chazelles-sur-Lyon est équipée des  installations permettant une éducation de proximité.
Si vous avez un projet d'acheter un bien immobilier à Chazelles-sur-Lyon, vous devrez impérativement évaluer la notoriété des écoles de la communes

À Chazelles-sur-Lyon le salaire médian par mois par habitant se situe à approximativement 1 842 €  net. Ceci est inférieur à la moyenne du pays.

À Chazelles-sur-Lyon, le prix moyen à l'achat d'un appartement s'évalue à 1 843 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 609 € du m². À la location la valeur moyenne se situe à 5,74 € du m² mensuel.

La ville offre de nombreux  équipements sportifs, elle propose entre autres trois terrains de sport, une salle de combat et deux boucles de randonnée.


text:
package io.github.s0cks.rapidjson.io;

import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public final class JsonOutputStream
implements Closeable {
    private final OutputStream out;

    public JsonOutputStream(OutputStream out){
        if(out == null) throw new NullPointerException("out == null");
        this.out = out;
    }

    public JsonOutputStream newObject()
    throws IOException{
        this.write('{');
        return this;
    }

    public JsonOutputStream endObject()
    throws IOException {
        this.write('}');
        return this;
    }

    public JsonOutputStream newArray()
    throws IOException {
        this.write('[');
        return this;
    }

    public JsonOutputStream endArray()
    throws IOException {
        this.write(']');
        return this;
    }

    public JsonOutputStream name(String name)
    throws IOException {
        this.write('\"');
        this.write(name);
        this.write('\"');
        this.write(':');
        return this;
    }

    public JsonOutputStream value(String str)
    throws IOException {
        this.write('\"');
        this.write(str);
        this.write('\"');
        return this;
    }

    public JsonOutputStream value(int i)
    throws IOException {
        this.write(String.valueOf(i));
        return this;
    }

    public JsonOutputStream value(double d)
    throws IOException {
        this.write(String.valueOf(d));
        return this;
    }

    public JsonOutputStream value(float f)
    throws IOException {
        this.write(String.valueOf(f));
        return this;
    }

    public JsonOutputStream value(char c)
    throws IOException {
        this.write(c);
        return this;
    }

    public JsonOutputStream value(short s)
    throws IOException {
        this.write(String.valueOf(s));
        return this;
    }

    public JsonOutputStream value(long l)
    throws IOException {
        this.write(String.valueOf(l));
        return this;
    }

    public JsonOutputStream value(byte b)
    throws IOException {
        this.write(String.valueOf(b));
        return this;
    }

    public JsonOutputStream value(boolean b)
    throws IOException{
        this.write(String.valueOf(b));
        return this;
    }

    public JsonOutputStream next()
    throws IOException {
        this.write(',');
        return this;
    }

    private void write(char c)
    throws IOException{
        this.out.write((byte) c);
    }

    private void write(String chars)
    throws IOException{
        this.out.write(chars.getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public void close()
    throws IOException {
        this.out.close();
    }
}


text:
package com.nasa.pic.app.noactivities.wallpaper;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.annotation.MainThread;
import android.support.annotation.UiThread;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.NotificationCompat;

import com.nasa.pic.R;
import com.nasa.pic.app.activities.MainActivity;
import com.nasa.pic.events.WallpaperChangedEvent;
import com.nasa.pic.events.WallpaperChangingEvent;
import com.nasa.pic.events.WallpaperUndoEvent;

import de.greenrobot.event.EventBus;

import static android.support.v4.app.NotificationCompat.PRIORITY_DEFAULT;
import static android.support.v4.app.NotificationCompat.PRIORITY_MAX;

public final class WallpaperSettingNotification {
	private static final int WALLPAPER_CHANGED_NOTIFICATION_ID = 0x34;
	private static final int CHANGING_WALLPAPER_NOTIFICATION_ID = 0x35;
	private static final int REMIND_NOTIFICATION_ID = 0x35;
	private static final int SMALL_ICON = R.drawable.ic_logo_toolbar;
	private static final int LARGE_ICON = R.drawable.ic_logo_splash;

	@UiThread
	@MainThread
	static void createChangedNotification(Context context, CharSequence message) {
		Resources res = context.getResources();
		PendingIntent contentPendingIntent = PendingIntent.getActivities(context, 0, new Intent[] { MainActivity.createActivityIntent(context, false) }, PendingIntent.FLAG_UPDATE_CURRENT);
		PendingIntent undoChangePendingIntent = PendingIntent.getService(context,
		                                                                 SetWallpaperService.UNDO_REQUEST_CODE,
		                                                                 SetWallpaperService.createServiceIntent(context, null, true),
		                                                                 PendingIntent.FLAG_ONE_SHOT);
		String undoChangeButtonTitle = context.getResources()
		                                      .getString(R.string.wallpaper_change_undo);
		Notification notification = new NotificationCompat.Builder(context).setSmallIcon(SMALL_ICON)
		                                                                   .setLargeIcon(BitmapFactory.decodeResource(res, LARGE_ICON))
		                                                                   .setColor(ContextCompat.getColor(context, R.color.colorPrimary))
		                                                                   .setContentTitle(res.getString(R.string.application_name))
		                                                                   .setContentText(message)
		                                                                   .setContentIntent(contentPendingIntent)
		                                                                   .setPriority(PRIORITY_MAX)
		                                                                   .setVibrate(new long[] { 1000 })
		                                                                   .addAction(android.R.drawable.ic_menu_revert, undoChangeButtonTitle, undoChangePendingIntent)
		                                                                   .build();
		NotificationManagerCompat.from(context)
		                         .notify(WALLPAPER_CHANGED_NOTIFICATION_ID, notification);
		if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
			EventBus.getDefault()
			        .post(new WallpaperChangedEvent(message));
		}

	}

	@UiThread
	@MainThread
	static void createUndoFinishedNotification(Context context, CharSequence message) {
		Resources res = context.getResources();
		PendingIntent contentPendingIntent = PendingIntent.getActivities(context, 0, new Intent[] { MainActivity.createActivityIntent(context, false)}, PendingIntent.FLAG_UPDATE_CURRENT);
		Notification notification = new NotificationCompat.Builder(context).setSmallIcon(SMALL_ICON)
		                                                                   .setLargeIcon(BitmapFactory.decodeResource(res, LARGE_ICON))
		                                                                   .setColor(ContextCompat.getColor(context, R.color.colorPrimary))
		                                                                   .setContentTitle(res.getString(R.string.application_name))
		                                                                   .setContentText(message)
		                                                                   .setPriority(PRIORITY_MAX)
		                                                                   .setVibrate(new long[] { 1000 })
		                                                                   .setContentIntent(contentPendingIntent)
		                                                                   .build();
		NotificationManagerCompat.from(context)
		                         .notify(WALLPAPER_CHANGED_NOTIFICATION_ID, notification);
		if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
			EventBus.getDefault()
			        .post(new WallpaperUndoEvent(message));
		}
	}

	@UiThread
	@MainThread
	static void createChangingNotification(Context context) {
		String message = context.getString(R.string.wallpaper_changing);
		Resources res = context.getResources();
		PendingIntent contentPendingIntent = PendingIntent.getActivities(context, 0, new Intent[] { MainActivity.createActivityIntent(context, false) }, PendingIntent.FLAG_UPDATE_CURRENT);
		Notification notification = new NotificationCompat.Builder(context).setSmallIcon(SMALL_ICON)
		                                                                   .setLargeIcon(BitmapFactory.decodeResource(res, LARGE_ICON))
		                                                                   .setColor(ContextCompat.getColor(context, R.color.colorPrimary))
		                                                                   .setContentTitle(res.getString(R.string.application_name))
		                                                                   .setContentText(message)
		                                                                   .setPriority(PRIORITY_DEFAULT)
		                                                                   .setVibrate(new long[] { 1000 })
		                                                                   .setContentIntent(contentPendingIntent)
		                                                                   .build();
		NotificationManagerCompat.from(context)
		                         .notify(CHANGING_WALLPAPER_NOTIFICATION_ID, notification);
		if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
			EventBus.getDefault()
			        .post(new WallpaperChangingEvent(message));
		}
	}

	public static void createWallpaperDailyRemind(Context context) {
		String message = context.getString(R.string.wallpaper_remind);
		Resources res = context.getResources();
		PendingIntent contentPendingIntent = PendingIntent.getActivities(context, 0, new Intent[] { MainActivity.createActivityIntent(context, true)}, PendingIntent.FLAG_UPDATE_CURRENT);
		Notification notification = new NotificationCompat.Builder(context).setSmallIcon(SMALL_ICON)
		                                                                   .setLargeIcon(BitmapFactory.decodeResource(res, LARGE_ICON))
		                                                                   .setColor(ContextCompat.getColor(context, R.color.colorPrimary))
		                                                                   .setContentTitle(res.getString(R.string.application_name))
		                                                                   .setContentText(message)
		                                                                   .setPriority(PRIORITY_MAX)
		                                                                   .setVibrate(new long[] { 1000 })
		                                                                   .setContentIntent(contentPendingIntent)
		                                                                   .build();
		NotificationManagerCompat.from(context)
		                         .notify(REMIND_NOTIFICATION_ID, notification);
	}

	@UiThread
	@MainThread
	static void removeChangingNotification(Context context) {
		NotificationManagerCompat.from(context)
		                         .cancel(WallpaperSettingNotification.REMIND_NOTIFICATION_ID);
		NotificationManagerCompat.from(context)
		                         .cancel(WallpaperSettingNotification.CHANGING_WALLPAPER_NOTIFICATION_ID);
	}
}