text:
{-# LANGUAGE RecordWildCards #-}
module Test where

import Test.Tasty
import Test.Tasty.Golden
import System.Directory
import System.FilePath

import Options.Applicative

import Main hiding (main)

import System.IO.Silently
import System.IO

import Debug.Trace
import System.Process

main =
  defaultMain =<< mkTests <$> findTests

findTests :: IO [FilePath]
findTests = do
  files <- getDirectoryContents "tests/examples"
  return $ (map ("tests/examples" </>) . filter ((== ".hs") . takeExtension )) files

mkTests :: [FilePath] -> TestTree
mkTests files = testGroup "Unit tests" (map mkTest files)
  where
    mkTest :: FilePath -> TestTree
    mkTest fp =
      let outfile = fp <.> "out"
          rfile   = fp <.> "refact"
          topts = Options
                  { optionsTarget       = Just fp
                  , optionsInplace       = False
                  , optionsOutput        = Just outfile
                  , optionsRefactFile    = Just rfile
                  , optionsVerbosity     = Silent
                  , optionsStep          = False
                  , optionsRoundtrip     = False
                  , optionsDebug         = False
                  , optionsVersion       = False
                  , optionsPos           = Nothing
                  }
          action = do
            (_, str, _) <- readCreateProcessWithExitCode (shell $ "hlint --serialise " ++ fp) ""
            writeFile rfile str
            hSilence [stderr] $ runPipe topts fp
          diffCmd = \ref new -> ["diff", "-u", ref, new]
      in goldenVsFileDiff fp diffCmd (fp <.> "expected") outfile action

redpajama_set_name: RedPajamaGithub


text:
"""
    flaskbb.forum.views
    ~~~~~~~~~~~~~~~~~~~~

    This module handles the forum logic like creating and viewing
    topics and posts.

    :copyright: (c) 2014 by the FlaskBB Team.
    :license: BSD, see LICENSE for more details.
"""
import datetime

from flask import (Blueprint, redirect, url_for, current_app,
                   request, flash)
from flask.ext.login import login_required, current_user

from flaskbb.extensions import db
from flaskbb.utils.settings import flaskbb_config
from flaskbb.utils.helpers import get_online_users, time_diff, render_template
from flaskbb.utils.permissions import (can_post_reply, can_post_topic,
                                       can_delete_topic, can_delete_post,
                                       can_edit_post, can_moderate)
from flaskbb.forum.models import (Category, Forum, Topic, Post, ForumsRead,
                                  TopicsRead)
from flaskbb.forum.forms import (QuickreplyForm, ReplyForm, NewTopicForm,
                                 ReportForm, UserSearchForm, SearchPageForm)
from flaskbb.user.models import User

forum = Blueprint("forum", __name__)

@forum.route("/")
def index():
    categories = Category.get_all(user=current_user)

    # Fetch a few stats about the forum
    user_count = User.query.count()
    topic_count = Topic.query.count()
    post_count = Post.query.count()
    newest_user = User.query.order_by(User.id.desc()).first()

    # Check if we use redis or not
    if not current_app.config["REDIS_ENABLED"]:
        online_users = User.query.filter(User.lastseen >= time_diff()).count()

        # Because we do not have server side sessions, we cannot check if there
        # are online guests
        online_guests = None
    else:
        online_users = len(get_online_users())
        online_guests = len(get_online_users(guest=True))

    return render_template("forum/index.html",
                           categories=categories,
                           user_count=user_count,
                           topic_count=topic_count,
                           post_count=post_count,
                           newest_user=newest_user,
                           online_users=online_users,
                           online_guests=online_guests)

@forum.route("/category/<int:category_id>")
@forum.route("/category/<int:category_id>-<slug>")
def view_category(category_id, slug=None):
    category, forums = Category.\
        get_forums(category_id=category_id, user=current_user)

    return render_template("forum/category.html", forums=forums,
                           category=category)

@forum.route("/forum/<int:forum_id>")
@forum.route("/forum/<int:forum_id>-<slug>")
def view_forum(forum_id, slug=None):
    page = request.args.get('page', 1, type=int)

    forum, forumsread = Forum.get_forum(forum_id=forum_id, user=current_user)

    if forum.external:
        return redirect(forum.external)

    topics = Forum.get_topics(forum_id=forum.id, user=current_user, page=page,
                              per_page=flaskbb_config["TOPICS_PER_PAGE"])

    return render_template("forum/forum.html", forum=forum, topics=topics,
                           forumsread=forumsread,)

@forum.route("/topic/<int:topic_id>", methods=["POST", "GET"])
@forum.route("/topic/<int:topic_id>-<slug>", methods=["POST", "GET"])
def view_topic(topic_id, slug=None):
    page = request.args.get('page', 1, type=int)

    topic = Topic.query.filter_by(id=topic_id).first()
    posts = Post.query.filter_by(topic_id=topic.id).\
        order_by(Post.id.asc()).\
        paginate(page, flaskbb_config['POSTS_PER_PAGE'], False)

    # Count the topic views
    topic.views += 1

    # Update the topicsread status if the user hasn't read it
    forumsread = None
    if current_user.is_authenticated():
        forumsread = ForumsRead.query.\
            filter_by(user_id=current_user.id,
                      forum_id=topic.forum.id).first()

    topic.update_read(current_user, topic.forum, forumsread)
    topic.save()

    form = None

    if not topic.locked \
        and not topic.forum.locked \
        and can_post_reply(user=current_user,
                           forum=topic.forum):

            form = QuickreplyForm()
            if form.validate_on_submit():
                post = form.save(current_user, topic)
                return view_post(post.id)

    return render_template("forum/topic.html", topic=topic, posts=posts,
                           last_seen=time_diff(), form=form)

@forum.route("/post/<int:post_id>")
def view_post(post_id):
    post = Post.query.filter_by(id=post_id).first_or_404()
    count = post.topic.post_count
    page = count / flaskbb_config["POSTS_PER_PAGE"]

    if count > flaskbb_config["POSTS_PER_PAGE"]:
        page += 1
    else:
        page = 1

    return redirect(post.topic.url + "?page=%d#pid%s" % (page, post.id))

@forum.route("/<int:forum_id>/topic/new", methods=["POST", "GET"])
@forum.route("/<int:forum_id>-<slug>/topic/new", methods=["POST", "GET"])
@login_required
def new_topic(forum_id, slug=None):
    forum = Forum.query.filter_by(id=forum_id).first_or_404()

    if forum.locked:
        flash("This forum is locked; you cannot submit new topics or posts.",
              "danger")
        return redirect(forum.url)

    if not can_post_topic(user=current_user, forum=forum):
        flash("You do not have the permissions to create a new topic.",
              "danger")
        return redirect(forum.url)

    form = NewTopicForm()
    if form.validate_on_submit():
        if request.form['button'] == 'preview':
            return render_template("forum/new_topic.html", forum=forum, form=form, preview=form.content.data)
        else:
            topic = form.save(current_user, forum)

            # redirect to the new topic
            return redirect(url_for('forum.view_topic', topic_id=topic.id))
    return render_template("forum/new_topic.html", forum=forum, form=form)

@forum.route("/topic/<int:topic_id>/delete")
@forum.route("/topic/<int:topic_id>-<slug>/delete")
@login_required
def delete_topic(topic_id, slug=None):
    topic = Topic.query.filter_by(id=topic_id).first_or_404()

    if not can_delete_topic(user=current_user, forum=topic.forum,
                            post_user_id=topic.first_post.user_id):

        flash("You do not have the permissions to delete the topic", "danger")
        return redirect(topic.forum.url)

    involved_users = User.query.filter(Post.topic_id == topic.id,
                                       User.id == Post.user_id).all()
    topic.delete(users=involved_users)
    return redirect(url_for("forum.view_forum", forum_id=topic.forum_id))

@forum.route("/topic/<int:topic_id>/lock")
@forum.route("/topic/<int:topic_id>-<slug>/lock")
@login_required
def lock_topic(topic_id, slug=None):
    topic = Topic.query.filter_by(id=topic_id).first_or_404()

    # TODO: Bulk lock

    if not can_moderate(user=current_user, forum=topic.forum):
        flash("You do not have the permissions to lock this topic", "danger")
        return redirect(topic.url)

    topic.locked = True
    topic.save()
    return redirect(topic.url)

@forum.route("/topic/<int:topic_id>/unlock")
@forum.route("/topic/<int:topic_id>-<slug>/unlock")
@login_required
def unlock_topic(topic_id, slug=None):
    topic = Topic.query.filter_by(id=topic_id).first_or_404()

    # TODO: Bulk unlock

    # Unlock is basically the same as lock
    if not can_moderate(user=current_user, forum=topic.forum):
        flash("Yo do not have the permissions to unlock this topic", "danger")
        return redirect(topic.url)

    topic.locked = False
    topic.save()
    return redirect(topic.url)

@forum.route("/topic/<int:topic_id>/move/<int:forum_id>")
@forum.route("/topic/<int:topic_id>-<topic_slug>/move/<int:forum_id>-<forum_slug>")
@login_required
def move_topic(topic_id, forum_id, topic_slug=None, forum_slug=None):
    forum = Forum.query.filter_by(id=forum_id).first_or_404()
    topic = Topic.query.filter_by(id=topic_id).first_or_404()

    # TODO: Bulk move

    if not can_moderate(user=current_user, forum=topic.forum):
        flash("You do not have the permissions to move this topic", "danger")
        return redirect(forum.url)

    if not topic.move(forum):
        flash("Could not move the topic to forum %s" % forum.title, "danger")
        return redirect(topic.url)

    flash("Topic was moved to forum %s" % forum.title, "success")
    return redirect(topic.url)

@forum.route("/topic/<int:old_id>/merge/<int:new_id>")
@forum.route("/topic/<int:old_id>-<old_slug>/merge/<int:new_id>-<new_slug>")
@login_required
def merge_topic(old_id, new_id, old_slug=None, new_slug=None):
    old_topic = Topic.query.filter_by(id=old_id).first_or_404()
    new_topic = Topic.query.filter_by(id=new_id).first_or_404()

    # TODO: Bulk merge

    if not can_moderate(user=current_user, forum=topic.forum):
        flash("Yo do not have the permissions to merge this topic", "danger")
        return redirect(old_topic.url)

    if not old_topic.merge(new_topic):
        flash("Could not merge the topic.", "danger")
        return redirect(old_topic.url)

    flash("Topic succesfully merged.", "success")
    return redirect(new_topic.url)

@forum.route("/topic/<int:topic_id>/post/new", methods=["POST", "GET"])
@forum.route("/topic/<int:topic_id>-<slug>/post/new", methods=["POST", "GET"])
@login_required
def new_post(topic_id, slug=None):
    topic = Topic.query.filter_by(id=topic_id).first_or_404()

    if topic.forum.locked:
        flash("This forum is locked; you cannot submit new topics or posts.",
              "danger")
        return redirect(topic.forum.url)

    if topic.locked:
        flash("The topic is locked.", "danger")
        return redirect(topic.forum.url)

    if not can_post_reply(user=current_user, forum=topic.forum):
        flash("You do not have the permissions to delete the topic", "danger")
        return redirect(topic.forum.url)

    form = ReplyForm()
    if form.validate_on_submit():
        if request.form['button'] == 'preview':
            return render_template("forum/new_post.html", topic=topic, form=form, preview=form.content.data)
        else:
            post = form.save(current_user, topic)
            return view_post(post.id)

    return render_template("forum/new_post.html", topic=topic, form=form)

@forum.route("/topic/<int:topic_id>/post/<int:post_id>/reply", methods=["POST", "GET"])
@login_required
def reply_post(topic_id, post_id):
    topic = Topic.query.filter_by(id=topic_id).first_or_404()
    post = Post.query.filter_by(id=post_id).first_or_404()

    if post.topic.forum.locked:
        flash("This forum is locked; you cannot submit new topics or posts.",
              "danger")
        return redirect(post.topic.forum.url)

    if post.topic.locked:
        flash("The topic is locked.", "danger")
        return redirect(post.topic.forum.url)

    if not can_post_reply(user=current_user, forum=topic.forum):
        flash("You do not have the permissions to post in this topic", "danger")
        return redirect(topic.forum.url)

    form = ReplyForm()
    if form.validate_on_submit():
        if request.form['button'] == 'preview':
            return render_template("forum/new_post.html", topic=topic, form=form, preview=form.content.data)
        else:
            form.save(current_user, topic)
            return redirect(post.topic.url)
    else:
        form.content.data = '[quote]{}[/quote]'.format(post.content)

    return render_template("forum/new_post.html", topic=post.topic, form=form)

@forum.route("/post/<int:post_id>/edit", methods=["POST", "GET"])
@login_required
def edit_post(post_id):
    post = Post.query.filter_by(id=post_id).first_or_404()

    if post.topic.forum.locked:
        flash("This forum is locked; you cannot submit new topics or posts.",
              "danger")
        return redirect(post.topic.forum.url)

    if post.topic.locked:
        flash("The topic is locked.", "danger")
        return redirect(post.topic.forum.url)

    if not can_edit_post(user=current_user, forum=post.topic.forum,
                         post_user_id=post.user_id):
        flash("You do not have the permissions to edit this post", "danger")
        return redirect(post.topic.url)

    form = ReplyForm()
    if form.validate_on_submit():
        if request.form['button'] == 'preview':
            return render_template("forum/new_post.html", topic=post.topic, form=form, preview=form.content.data)
        else:
            form.populate_obj(post)
            post.date_modified = datetime.datetime.utcnow()
            post.modified_by = current_user.username
            post.save()
            return redirect(post.topic.url)
    else:
        form.content.data = post.content

    return render_template("forum/new_post.html", topic=post.topic, form=form)

@forum.route("/post/<int:post_id>/delete")
@login_required
def delete_post(post_id, slug=None):
    post = Post.query.filter_by(id=post_id).first_or_404()

    # TODO: Bulk delete

    if not can_delete_post(user=current_user, forum=post.topic.forum,
                           post_user_id=post.user_id):
        flash("You do not have the permissions to edit this post", "danger")
        return redirect(post.topic.url)

    post.delete()

    # If the post was the first post in the topic, redirect to the forums
    if post.first_post:
        return redirect(post.topic.forum.url)
    return redirect(post.topic.url)

@forum.route("/post/<int:post_id>/report", methods=["GET", "POST"])
@login_required
def report_post(post_id):
    post = Post.query.filter_by(id=post_id).first_or_404()

    form = ReportForm()
    if form.validate_on_submit():
        form.save(current_user, post)
        flash("Thanks for reporting!", "success")

    return render_template("forum/report_post.html", form=form)

@forum.route("/markread")
@forum.route("/<int:forum_id>/markread")
@forum.route("/<int:forum_id>-<slug>/markread")
@login_required
def markread(forum_id=None, slug=None):
    # Mark a single forum as read
    if forum_id:
        forum = Forum.query.filter_by(id=forum_id).first_or_404()
        forumsread = ForumsRead.query.filter_by(user_id=current_user.id,
                                                forum_id=forum.id).first()
        TopicsRead.query.filter_by(user_id=current_user.id,
                                   forum_id=forum.id).delete()

        if not forumsread:
            forumsread = ForumsRead()
            forumsread.user_id = current_user.id
            forumsread.forum_id = forum.id

        forumsread.last_read = datetime.datetime.utcnow()
        forumsread.cleared = datetime.datetime.utcnow()

        db.session.add(forumsread)
        db.session.commit()

        return redirect(forum.url)

    # Mark all forums as read
    ForumsRead.query.filter_by(user_id=current_user.id).delete()
    TopicsRead.query.filter_by(user_id=current_user.id).delete()

    forums = Forum.query.all()
    forumsread_list = []
    for forum in forums:
        forumsread = ForumsRead()
        forumsread.user_id = current_user.id
        forumsread.forum_id = forum.id
        forumsread.last_read = datetime.datetime.utcnow()
        forumsread.cleared = datetime.datetime.utcnow()
        forumsread_list.append(forumsread)

    db.session.add_all(forumsread_list)
    db.session.commit()

    return redirect(url_for("forum.index"))

@forum.route("/who_is_online")
def who_is_online():
    if current_app.config['REDIS_ENABLED']:
        online_users = get_online_users()
    else:
        online_users = User.query.filter(User.lastseen >= time_diff()).all()
    return render_template("forum/online_users.html",
                           online_users=online_users)

@forum.route("/memberlist", methods=['GET', 'POST'])
def memberlist():
    page = request.args.get('page', 1, type=int)

    search_form = UserSearchForm()

    if search_form.validate():
        users = search_form.get_results().\
            paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
        return render_template("forum/memberlist.html", users=users,
                               search_form=search_form)
    else:
        users = User.query.\
            paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
        return render_template("forum/memberlist.html", users=users,
                               search_form=search_form)

@forum.route("/topictracker")
@login_required
def topictracker():
    page = request.args.get("page", 1, type=int)
    topics = current_user.tracked_topics.\
        outerjoin(TopicsRead,
                  db.and_(TopicsRead.topic_id == Topic.id,
                          TopicsRead.user_id == current_user.id)).\
        add_entity(TopicsRead).\
        order_by(Post.id.desc()).\
        paginate(page, flaskbb_config['TOPICS_PER_PAGE'], True)

    return render_template("forum/topictracker.html", topics=topics)

@forum.route("/topictracker/<int:topic_id>/add")
@forum.route("/topictracker/<int:topic_id>-<slug>/add")
@login_required
def track_topic(topic_id, slug=None):
    topic = Topic.query.filter_by(id=topic_id).first_or_404()
    current_user.track_topic(topic)
    current_user.save()
    return redirect(topic.url)

@forum.route("/topictracker/<int:topic_id>/delete")
@forum.route("/topictracker/<int:topic_id>-<slug>/delete")
@login_required
def untrack_topic(topic_id, slug=None):
    topic = Topic.query.filter_by(id=topic_id).first_or_404()
    current_user.untrack_topic(topic)
    current_user.save()
    return redirect(topic.url)

@forum.route("/search", methods=['GET', 'POST'])
def search():
    form = SearchPageForm()

    if form.validate_on_submit():
        result = form.get_results()
        return render_template('forum/search_result.html', form=form,
                               result=result)

    return render_template('forum/search_form.html', form=form)


text:
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
import gc
import matplotlib.pyplot as plt
import seaborn as sns
##x%matplotlib inline
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import roc_auc_score, log_loss
from numpy import linalg as LA
import re
#import Stemmer
import nltk
from nltk.corpus import wordnet as wn
import gensim
from numpy import linalg as LA

# average embedding
def makeFeatureVec(words, model, num_features):
    # Function to average all of the word vectors in a given
    # paragraph
    #
    # Pre-initialize an empty numpy array (for speed)
    featureVec = np.zeros((num_features,),dtype="float32")
    #
    nwords = 0.
    #
    # Index2word is a list that contains the names of the words in
    # the model's vocabulary. Convert it to a set, for speed
    index2word_set = set(model.index2word)
    #
    # Loop over each word in the review and, if it is in the model's
    # vocaublary, add its feature vector to the total
    for word in words:
        if word in index2word_set:
            nwords = nwords + 1.
            featureVec = np.add(featureVec,model[word])
    #
    # Divide the result by the number of words to get the average
    featureVec = np.divide(featureVec,nwords)
    return featureVec

# sym
def synsym(s1,s2):
    ts0 = nltk.pos_tag(nltk.word_tokenize(s1))
    ts1 = nltk.pos_tag(nltk.word_tokenize(s2))
    # adj
    jj0 = [x for x,y in ts0 if y=='JJ' or y=='JJR' or y=='JJS']
    jj1 = [x for x,y in ts1 if y=='JJ' or y=='JJR' or y=='JJS']
    if len(jj0) == 0 or len(jj1) ==0:
      jjps = 0
    else:
      v1 = makeFeatureVec(jj0,model,300)
      v2 = makeFeatureVec(jj1,model,300)
      jjps = np.inner(v1,v2)/(LA.norm(v1)*LA.norm(v2))
    # noum
    jj0 = [x for x,y in ts0 if y=='NN' or y=='NNS' or y=='NNP' or y=='NNPS' or y=='DT']
    jj1 = [x for x,y in ts1 if y=='NN' or y=='NNS' or y=='NNP' or y=='NNPS' or y=='DT']
    if len(jj0) == 0 or len(jj1) ==0:
      nps = 0
    else:
      v1 = makeFeatureVec(jj0,model,300)
      v2 = makeFeatureVec(jj1,model,300)
      nps =  np.inner(v1,v2)/(LA.norm(v1)*LA.norm(v2))
    # verb
    jj0 = [x for x,y in ts0 if y=='VB' or y=='VBD' or y=='VBG' or y=='VBN' or y=='VBP' or y=='VBZ']
    jj1 = [x for x,y in ts1 if y=='VB' or y=='VBD' or y=='VBG' or y=='VBN' or y=='VBP' or y=='VBZ']
    if len(jj0) == 0 or len(jj1) ==0:
      vps = 0
    else:
      v1 = makeFeatureVec(jj0,model,300)
      v2 = makeFeatureVec(jj1,model,300)
      vps =  np.inner(v1,v2)/(LA.norm(v1)*LA.norm(v2))
    return [jjps,nps,vps]

# data
df_train = pd.read_csv('./data/train.csv')
df_test = pd.read_csv('./data/test.csv')
# Load Google's pre-trained Word2Vec model.
model = gensim.models.KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin', binary=True)

print(">> df_train:",df_train.shape)
print(">> df_test:",df_test.shape)

print("-- src:",df_train.ix[1,'question1'])

qs1 = pd.Series(df_train['question1'].tolist() + df_test['question1'].tolist()).astype(str)
qs2 = pd.Series(df_train['question2'].tolist() + df_test['question2'].tolist()).astype(str)

feat = np.zeros((df_train.shape[0]+df_test.shape[0],3))

for i in range(0,feat.shape[0]):
  if i % 100000 ==0:
    print(str(i),end=' ',flush=True)
  feat[i,:] =  synsym(qs1[i],qs2[i])
  if i == 0:
    print(str(feat[i,:]))

tr_feat = feat[0:df_train.shape[0]]
te_feat = feat[df_train.shape[0]:]

# write on disk
tr_csv = pd.DataFrame({'adj_sym_we':tr_feat[:,0],'noun_sym_we':tr_feat[:,1],'verb_sym_we':tr_feat[:,2]})
te_csv = pd.DataFrame({'adj_sym_we':te_feat[:,0],'noun_sym_we':te_feat[:,1],'verb_sym_we':te_feat[:,2]})

tr_csv.to_csv("xtrain_4.csv", index=False)
te_csv.to_csv("xtest_4.csv", index=False)


text:
include_recipe 'nodejs'
include_recipe 'nginx'

service 'nginx' do
  action :disable
end

service 'nginx' do
  action :stop
end

template '/etc/nginx/nginx_datasift.conf' do
  user 'root'
  group 'root'
  mode 0644
  source 'nginx.conf.erb'
end

supervisor_service 'nginx' do
  user 'root'
  command '/usr/sbin/nginx -c /etc/nginx/nginx_datasift.conf'
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ExternalNmeaGPS.Controls
{
	/// <summary>
	/// Interaction logic for SatelliteView.xaml
	/// </summary>
	public partial class SatelliteView : UserControl
	{
		public SatelliteView()
		{
			InitializeComponent();
		}

		public IEnumerable<NmeaParser.Nmea.Gps.Gpgsv> GpgsvMessages
		{
			get { return (IEnumerable<NmeaParser.Nmea.Gps.Gpgsv>)GetValue(GpgsvMessagesProperty); }
			set { SetValue(GpgsvMessagesProperty, value); }
		}

		// Using a DependencyProperty as the backing store for GpgsvMessages.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty GpgsvMessagesProperty =
			DependencyProperty.Register("GpgsvMessages", typeof(IEnumerable<NmeaParser.Nmea.Gps.Gpgsv>), typeof(SatelliteView), new PropertyMetadata(null, OnGpgsvMessagesChanged));

		private static void OnGpgsvMessagesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var sats = e.NewValue as IEnumerable<NmeaParser.Nmea.Gps.Gpgsv>;
			if (sats == null)
				(d as SatelliteView).satellites.ItemsSource = null;
			else
				(d as SatelliteView).satellites.ItemsSource = sats.SelectMany(s => s.SVs);
		}
	}
	public class PolarPlacementItem : ContentControl
	{
		public PolarPlacementItem()
		{
			HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
			VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
		}
		protected override Size ArrangeOverride(Size arrangeBounds)
		{
			double az = (Azimuth - 90) / 180 * Math.PI;
			double e = (90 - Elevation) / 90;
			double X = Math.Cos(az) * e;
			double Y = Math.Sin(az) * e;
			X = arrangeBounds.Width * .5 * X;
			Y = arrangeBounds.Height * .5 * Y;
			RenderTransform = new TranslateTransform(X, Y);
			return base.ArrangeOverride(arrangeBounds);
		}

		public double Azimuth
		{
			get { return (double)GetValue(AzimuthProperty); }
			set { SetValue(AzimuthProperty, value); }
		}

		public static readonly DependencyProperty AzimuthProperty =
			DependencyProperty.Register("Azimuth", typeof(double), typeof(PolarPlacementItem), new PropertyMetadata(0d, OnAzimuthPropertyChanged));

		private static void OnAzimuthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			(d as PolarPlacementItem).InvalidateArrange();
		}

		public double Elevation
		{
			get { return (double)GetValue(ElevationProperty); }
			set { SetValue(ElevationProperty, value); }
		}

		public static readonly DependencyProperty ElevationProperty =
			DependencyProperty.Register("Elevation", typeof(double), typeof(PolarPlacementItem), new PropertyMetadata(0d, OnElevationPropertyChanged));

		private static void OnElevationPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			(d as PolarPlacementItem).InvalidateArrange();
		}

	}
}


text:
package de.hochschuleTrier.fmv.controls.constraints;

import java.awt.event.MouseWheelEvent;

import prefuse.Display;
import prefuse.Visualization;
import de.hochschuleTrier.fmv.controls.DefaultWheelZoomControl;
import de.hochschuleTrier.fmv.model.impl.UISettings;

public class ConstraintZoomControl extends DefaultWheelZoomControl {

	// prüfen, ob Knoten selektiert und entsprechende Aktion ausführen
	@Override
	public void mouseWheelMoved(final MouseWheelEvent e) {
		final Display display = (Display) e.getComponent();
		if (display.getVisualization().getFocusGroup(Visualization.FOCUS_ITEMS).getTupleCount() > 0 && e.isControlDown()) {
			if (e.getWheelRotation() < 0) {
				UISettings.getInstance().decrementConstraintFocusDistance();
			}
			else {
				UISettings.getInstance().incrementConstraintFocusDistance();
			}
		}
		else {
			super.mouseWheelMoved(e);
		}
	}

}


text:
"""
requests.auth
~~~~~~~~~~~~~

This module contains the authentication handlers for Requests.
"""

import os
import time
import hashlib

from base64 import b64encode

from .compat import urlparse, str
from .utils import parse_dict_header

try:
    from ._oauth import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER, extract_params)

except (ImportError, SyntaxError):
    SIGNATURE_HMAC = None
    SIGNATURE_TYPE_AUTH_HEADER = None

CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'

def _basic_auth_str(username, password):
    """Returns a Basic Auth string."""

    return 'Basic ' + b64encode(('%s:%s' % (username, password)).encode('latin1')).strip().decode('latin1')

class AuthBase(object):
    """Base class that all auth implementations derive from"""

    def __call__(self, r):
        raise NotImplementedError('Auth hooks must be callable.')

class OAuth1(AuthBase):
    """Signs the request using OAuth 1 (RFC5849)"""
    def __init__(self, client_key,
            client_secret=None,
            resource_owner_key=None,
            resource_owner_secret=None,
            callback_uri=None,
            signature_method=SIGNATURE_HMAC,
            signature_type=SIGNATURE_TYPE_AUTH_HEADER,
            rsa_key=None, verifier=None):

        try:
            signature_type = signature_type.upper()
        except AttributeError:
            pass

        self.client = Client(client_key, client_secret, resource_owner_key,
            resource_owner_secret, callback_uri, signature_method,
            signature_type, rsa_key, verifier)

    def __call__(self, r):
        """Add OAuth parameters to the request.

        Parameters may be included from the body if the content-type is
        urlencoded, if no content type is set an educated guess is made.
        """
        contenttype = r.headers.get('Content-Type', None)
        # extract_params will not give params unless the body is a properly
        # formatted string, a dictionary or a list of 2-tuples.
        decoded_body = extract_params(r.data)
        if contenttype == None and decoded_body != None:
            # extract_params can only check the present r.data and does not know
            # of r.files, thus an extra check is performed. We know that
            # if files are present the request will not have
            # Content-type: x-www-form-urlencoded. We guess it will have
            # a mimetype of multipart/form-encoded and if this is not the case
            # we assume the correct header will be set later.
            if r.files:
                # Omit body data in the signing and since it will always
                # be empty (cant add paras to body if multipart) and we wish
                # to preserve body.
                r.headers['Content-Type'] = 'multipart/form-encoded'
                r.url, r.headers, _ = self.client.sign(
                    unicode(r.full_url), unicode(r.method), None, r.headers)
            else:
                # Normal signing
                r.headers['Content-Type'] = 'application/x-www-form-urlencoded'
                r.url, r.headers, r.data = self.client.sign(
                    unicode(r.full_url), unicode(r.method), r.data, r.headers)

            # Having the authorization header, key or value, in unicode will
            # result in UnicodeDecodeErrors when the request is concatenated
            # by httplib. This can easily be seen when attaching files.
            # Note that simply encoding the value is not enough since Python
            # saves the type of first key set. Thus we remove and re-add.
            # >>> d = {u'a':u'foo'}
            # >>> d['a'] = 'foo'
            # >>> d
            # { u'a' : 'foo' }
            u_header = unicode('Authorization')
            if u_header in r.headers:
                auth_header = r.headers[u_header].encode('utf-8')
                del r.headers[u_header]
                r.headers['Authorization'] = auth_header

        return r

class HTTPBasicAuth(AuthBase):
    """Attaches HTTP Basic Authentication to the given Request object."""
    def __init__(self, username, password):
        self.username = username
        self.password = password

    def __call__(self, r):
        r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
        return r

class HTTPProxyAuth(HTTPBasicAuth):
    """Attaches HTTP Proxy Authenetication to a given Request object."""
    def __call__(self, r):
        r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)
        return r

class HTTPDigestAuth(AuthBase):
    """Attaches HTTP Digest Authentication to the given Request object."""
    def __init__(self, username, password):
        self.username = username
        self.password = password

    def handle_401(self, r):
        """Takes the given response and tries digest-auth, if needed."""

        r.request.deregister_hook('response', self.handle_401)

        s_auth = r.headers.get('www-authenticate', '')

        if 'digest' in s_auth.lower():

            last_nonce = ''
            nonce_count = 0

            chal = parse_dict_header(s_auth.replace('Digest ', ''))

            realm = chal['realm']
            nonce = chal['nonce']
            qop = chal.get('qop')
            algorithm = chal.get('algorithm', 'MD5')
            opaque = chal.get('opaque', None)

            algorithm = algorithm.upper()
            # lambdas assume digest modules are imported at the top level
            if algorithm == 'MD5':
                def md5_utf8(x):
                    if isinstance(x, str):
                        x = x.encode('utf-8')
                    return hashlib.md5(x).hexdigest()
                hash_utf8 = md5_utf8
            elif algorithm == 'SHA':
                def sha_utf8(x):
                    if isinstance(x, str):
                        x = x.encode('utf-8')
                    return hashlib.sha1(x).hexdigest()
                hash_utf8 = sha_utf8
            # XXX MD5-sess
            KD = lambda s, d: hash_utf8("%s:%s" % (s, d))

            if hash_utf8 is None:
                return None

            # XXX not implemented yet
            entdig = None
            p_parsed = urlparse(r.request.url)
            path = p_parsed.path
            if p_parsed.query:
                path += '?' + p_parsed.query

            A1 = '%s:%s:%s' % (self.username, realm, self.password)
            A2 = '%s:%s' % (r.request.method, path)

            if qop == 'auth':
                if nonce == last_nonce:
                    nonce_count += 1
                else:
                    nonce_count = 1
                    last_nonce = nonce

                ncvalue = '%08x' % nonce_count
                s = str(nonce_count).encode('utf-8')
                s += nonce.encode('utf-8')
                s += time.ctime().encode('utf-8')
                s += os.urandom(8)

                cnonce = (hashlib.sha1(s).hexdigest()[:16])
                noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, hash_utf8(A2))
                respdig = KD(hash_utf8(A1), noncebit)
            elif qop is None:
                respdig = KD(hash_utf8(A1), "%s:%s" % (nonce, hash_utf8(A2)))
            else:
                # XXX handle auth-int.
                return None

            # XXX should the partial digests be encoded too?
            base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
                   'response="%s"' % (self.username, realm, nonce, path, respdig)
            if opaque:
                base += ', opaque="%s"' % opaque
            if entdig:
                base += ', digest="%s"' % entdig
            base += ', algorithm="%s"' % algorithm
            if qop:
                base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)

            r.request.headers['Authorization'] = 'Digest %s' % (base)
            r.request.send(anyway=True)
            _r = r.request.response
            _r.history.append(r)

            return _r

        return r

    def __call__(self, r):
        r.register_hook('response', self.handle_401)
        return r


text:
function getGraphStep(minValue, maxValue, step) {

    if (step) return step;

    var copy = maxValue;

    if (minValue < 0) {
        copy = maxValue - minValue;
    }

    var pow = 1

    while (copy > 10) {

        copy = copy / 10;
        pow++;
    }

    return Math.pow(10, pow - 1);
}

function getGraphEnd(minValue, maxValue, s) {
    var step = getGraphStep(minValue, maxValue, s);

    var max = 0;

    while (max < maxValue) {

        max += step;
    }

    return max;
}

function getGraphBegin(minValue, maxValue, s) {
    if (minValue > 0) return 0;

    var step = getGraphStep(minValue, maxValue, s);
    var min = 0;

    while (min > minValue) {

        min -= step;
    }

    return min;
}

//function getDxChart(graphControl) {

//    if (graphControl) {

//        if (graphControl.aasDxChart) {

//            return graphControl.aasDxChart;

//        } else if (graphControl.aasChartProperties) {

//            return graphControl.aasChartProperties.dxChart;
//        }
//    }

//    return null;
//}
Global.DhtmlxChartService = {

    aasService: 'DhtmlxChartService',
    aasPublished: true,

    GetGraphEnd: function (minValue, maxValue) {
        return getGraphEnd(minValue, maxValue);
    },

    GetGraphStep: function (minValue, maxValue) {
        return getGraphStep(minValue, maxValue);
    },

    GetGraphBegin: function (minValue, maxValue) {
        return getGraphBegin(minValue, maxValue);
    },

    RefreshGraph: function (graphControlId) {

        var graphControl = document.getElementById(graphControlId);

        if (graphControl.aasChartProperties) {

            graphControl.aasChartProperties.MustRebuildChart = true;
            graphControl.aasChartProperties.RefreshData();

        } else {

            var dxChart = getDxChart(graphControl);

            if (graphControl && dxChart) {

                var rowCount = graphControl.aasRowCount;

                var currentWidth = graphControl.parentNode.clientWidth;

                graphControl.style.width = graphControl.parentNode.clientWidth + 'px';

                var xAxis = graphControl.aasChartProperties.xAxis;

                var pointWidth = graphControl.aasChartProperties.AllAxis[xAxis].PointWidth;

                if (currentWidth <= rowCount * pointWidth) {
                    graphControl.style.width = rowCount * pointWidth + 'px';
                }
                else {
                    graphControl.style.width = graphControl.parentNode.clientWidth + 'px';
                }

                Aspectize.ProtectedCall(dxChart, dxChart.refresh);
                Aspectize.ProtectedCall(dxChart, dxChart.resize);
            }
        }
    },

    SetChartProperties: function (graphControlId, dhtmlxProperties) {

        var graphControl = document.getElementById(graphControlId);

        if (graphControl && graphControl.aasDxChart) {

            for (var k in dhtmlxProperties) {

                Aspectize.ProtectedCall(graphControl.aasDxChart, graphControl.aasDxChart.define, k, dhtmlxProperties[k]);
            }

            Aspectize.ProtectedCall(graphControl.aasDxChart, graphControl.aasDxChart.refresh);
        }
    },

    SetChartData: function (graphControlId, data) {

        var graphControl = document.getElementById(graphControlId);

        if (graphControl && graphControl.aasDxChart) {

            Aspectize.ProtectedCall(graphControl.aasDxChart, graphControl.aasDxChart.parse, data, 'json');
        }
    }

};

//Global.DhtmlxChartBuilder = {

//    aasService: 'DhtmlxChartBuilder',
//    aasPublished: false,

//    Build: function (controlInfo) {

//        var ChartTypes = { Area: { View: 'area' }, Bar: { View: 'bar' }, StackedBar: { View: 'stackedBar' }, Line: { View: 'line' }, Spline: { View: 'spline' }, Pie: { View: 'pie' }, Radar: { View: 'radar' } };

//        controlInfo.CreateInstance = function (ownerWindow, id) {

//            var chart = Aspectize.createElement('div', ownerWindow);

//            chart.aasSubControls = {};

//            return chart;
//        };

//        controlInfo.InitGrid = function (control) {

//            //control.style.height = '350px';
//            control.style.height = '100%';
//            control.style.width = '100%';
//            control.style.minHeight = '100%';
//            control.style.minWidth = '100%';

//            if (control.parentNode.width) {
//                control.style.width = control.parentNode.width;
//            }

//            control.parentNode.style.overflowX = "auto";
//            control.parentNode.style.overflowY = "hidden";

//            var chartType = null;

//            switch (control.aasControlInfo.name) {

//                case 'DhtmlxAreaChart': chartType = ChartTypes.Area; break;
//                case 'DhtmlxBarChart': chartType = ChartTypes.Bar; break;
//                case 'DhtmlxStackedBarChart': chartType = ChartTypes.StackedBar; break;
//                case 'DhtmlxLineChart': chartType = ChartTypes.Line; break;
//                case 'DhtmlxSplineChart': chartType = ChartTypes.Spline; break;
//                case 'DhtmlxPieChart': chartType = ChartTypes.Pie; break;
//                case 'DhtmlxRadarChart': chartType = ChartTypes.Radar; break;
//                default: chartType = ChartTypes.Line; break;
//            }

//            var xAxis = null;
//            var yAxis = null;
//            var otherYAxis = [];

//            var columnInfos = controlInfo.columnInfos;

//            for (var n = 0; n < columnInfos.length; n++) {

//                var columnInfo = columnInfos[n];

//                var typeNameParts = columnInfo.typeName.split('.');

//                var typeName = typeNameParts[typeNameParts.length - 1];

//                switch (typeName) {

//                    case 'DhtmlxChartXAxis': xAxis = columnInfo.name; break;
//                    case 'DhtmlxChartYAxis':
//                        {
//                            if (yAxis === null) {

//                                yAxis = columnInfo.name;
//                            }
//                            else {

//                                if (control.aasControlInfo.name !== 'DhtmlxPieChart') {

//                                    otherYAxis.push(columnInfo.name);
//                                }
//                            }

//                            break;
//                        }
//                    default: break;
//                }
//            }

//            if (!window.dhtmlXChart) throw new Error('Missing DHTMLX integration scripts in the app.ashx file ?');

//            var chart = new dhtmlXChart({
//                view: chartType.View,
//                container: control.id,
//                value: '#' + yAxis + '#',
//                lines: false,
//                label: '#' + yAxis + 'LabelValue#',
//                xAxis: {
//                    title: '',
//                    template: '#' + xAxis + 'Label#',
//                    lines: false
//                }

//                //                pieInnerText: function(obj) {
//                //                    var sum = chart.sum('#' + yAxis + '#');
//                //                    return Math.round(obj[yAxis] / sum * 100) + "%";
//                //                }
//            });

//            for (var i = 0; i < otherYAxis.length; i++) {

//                chart.addSeries({
//                    value: '#' + otherYAxis[i] + '#',
//                    label: '#' + otherYAxis[i] + 'LabelValue#',
//                    color: "#2FA783",
//                    item: { radius: 1, borderColor: '#2FA783', color: '#2FA783', borderWidth: 1 },
//                    line: { color: "#2FA783", width: 3 }
//                });
//            }

//            control.aasDxChart = chart;
//            control.aasDxChartXAxis = xAxis;
//            control.aasDxChartYAxis = yAxis;

//            control.aasChartProperties = { XAxis: { Title: '', Label: '', PointWidth: 50 }, YAxis: {} };

//            control.aasChartProperties.YAxis[yAxis] = { Title: '', LabelValue: '', ShowLine: false, Start: null, End: null, Step: null, LineColor: '#D4D4D4', LineWidth: 3, ItemColor: '#000000', ItemBorderColor: '#000000', ItemRadius: 4, ItemBorderWidth: 2 };

//            for (var i = 0; i < otherYAxis.length; i++) {
//                control.aasChartProperties.YAxis[otherYAxis[i]] = { Title: '', LabelValue: '', ShowLine: false, Start: null, End: null, Step: null, LineColor: '#D4D4D4', LineWidth: 3, ItemColor: '#000000', ItemBorderColor: '#000000', ItemRadius: 4, ItemBorderWidth: 2 };
//            }

//            //control.style.width = '2000px';

//        };

//        controlInfo.InitCellControl = function (control, cellControl, rowId, rowIndex, columnIndex, columnName) {

//            cellControl.aasDxChart = control.aasDxChart;
//            cellControl.aasDxChartXAxis = control.aasDxChartXAxis;
//            cellControl.aasDxChartYAxis = control.aasDxChartYAxis;
//            cellControl.aasChartProperties = control.aasChartProperties;
//            cellControl.aasColumnName = columnName;

//        };

//        controlInfo.RowCreated = function (control, rowId, cellControls) {

//            var chartItem = { id: rowId };

//            for (var n = 0; n < cellControls.length; n++) {

//                var cellControl = cellControls[n];

//                chartItem[cellControl.aasColumnName] = cellControl.aasControlInfo.PropertyBag.Value.toString();

//                if (cellControl.aasControlInfo.name == 'DhtmlxChartXAxis') {
//                    if (cellControl.aasControlInfo.PropertyBag.Label != null) {
//                        chartItem[cellControl.aasColumnName + 'Label'] = cellControl.aasControlInfo.PropertyBag.Label;
//                    }
//                    else {
//                        chartItem[cellControl.aasColumnName + 'Label'] = cellControl.aasControlInfo.PropertyBag.Value.toString();
//                    }
//                }
//                else if (cellControl.aasControlInfo.name == 'DhtmlxChartYAxis') {
//                    if (cellControl.aasControlInfo.PropertyBag.LabelValue != null) {
//                        chartItem[cellControl.aasColumnName + 'LabelValue'] = cellControl.aasControlInfo.PropertyBag.LabelValue;
//                    }
//                    else {
//                        chartItem[cellControl.aasColumnName + 'LabelValue'] = cellControl.aasControlInfo.PropertyBag.Value.toString();
//                    }
//                }

//                cellControl.aasChartItem = chartItem;
//            }

//            //control.aasDxChart.add(chartItem);
//        };

//        controlInfo.GridRendered = function (control, rowControls) {

//            var data = []; var min = null; var max = null; var field = control.aasDxChartYAxis;

//            for (var n = 0; n < rowControls.length; n++) {

//                var rowControl = rowControls[n];

//                if (rowControl.CellControls.length > 0) {

//                    var chartItem = rowControl.CellControls[0].aasChartItem;

//                    data.push(chartItem);

//                    var fv = Number(chartItem[field]);

//                    if (min == null) min = fv;
//                    if (fv < min) min = fv;

//                    if (max == null) max = fv;
//                    if (fv > max) max = fv;
//                }
//            }

//            var start = control.aasChartProperties.YAxis[control.aasDxChartYAxis].Start;
//            if (!start) start = getGraphBegin(min, max);

//            var step = control.aasChartProperties.YAxis[control.aasDxChartYAxis].Step;
//            if (!step) step = getGraphStep(min, max);

//            var end = control.aasChartProperties.YAxis[control.aasDxChartYAxis].End;
//            if (!end) end = getGraphEnd(min, max);

//            control.aasDxChart.define('yAxis', {
//                start: start,
//                end: end,
//                step: step
//            });

//            var rowCount = rowControls.length; // control.aasDxChart.data.dataCount();

//            control.aasRowCount = rowCount;

//            var currentWidth = control.clientWidth;

//            var pointWidth = control.aasChartProperties.XAxis.PointWidth;

//            if (currentWidth < rowCount * pointWidth) {
//                control.style.width = rowCount * pointWidth + 'px';
//            }
//            else {
//                control.style.width = control.parentNode.clientWidth + 'px';
//            }

//            Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.clearAll);
//            Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.refresh);

//            if (rowControls.length > 0) {

//                Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.parse, data, 'json');
//                Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.refresh);
//                Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.resize);
//            }
//        };

//        controlInfo.OnCurrentIndexChanged = function (control, currentIndex) {

//        };
//    }
//};

//Global.DhtmlxChartAxisBuilder = {

//    aasService: 'DhtmlxChartAxisBuilder',
//    aasPublished: false,

//    Build: function (controlInfo) {

//        function translateToObjectProperty(p) {

//            var obj = null;
//            var property = null;

//            if (p.indexOf('Line') === 0) obj = 'line';
//            else if (p.indexOf('Item') === 0) obj = 'item';
//            else obj = 'yAxis';

//            switch (obj) {

//                case 'line':
//                case 'item': {

//                    var stripedObj = p.substring(4);
//                    property = stripedObj[0].toLowerCase() + stripedObj.substring(1);
//                }

//                case 'yAxis': {

//                    property = (p === 'ShowLine') ? 'lines' : p.toLowerCase();
//                }
//            }

//            return { Obj: obj, Property: property };
//        }

//        controlInfo.CreateInstance = function (ownerWindow, id) {

//            var control = Aspectize.createElement('div', ownerWindow);

//            controlInfo.aasLastSetValue = null;

//            var needsFlush = false;
//            function deferredFlush() {

//                function flush() {

//                    needsFlush = false;
//                    Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.refresh);
//                }

//                if (!needsFlush) { needsFlush = true; setTimeout(flush, 0); }
//            };

//            controlInfo.ChangePropertyValue = function (property, newValue) {

//                if (property === 'LabelValue') return;

//                controlInfo.PropertyBag[property] = newValue;

//                if (property === 'Value') {

//                    if (controlInfo.aasLastSetValue !== newValue) {

//                        controlInfo.aasLastSetValue = newValue;

//                        if (control.aasChartItem) {

//                            control.aasChartItem[control.aasColumnName] = newValue;

//                            var index = control.aasDxChart.indexById(control.aasChartItem.id);

//                            if (index !== -1) {

//                                control.aasDxChart.remove(control.aasChartItem.id);
//                                control.aasDxChart.add(control.aasChartItem, index);

//                                deferredFlush();
//                            }
//                            else {

//                                // Old point : should never happen !!!
//                            }
//                        }
//                    }

//                } else {

//                    if (newValue === null) return;

//                    if (controlInfo.name == 'DhtmlxChartXAxis') {

//                        if (control.aasChartProperties.XAxis[property] !== newValue) {

//                            control.aasChartProperties.XAxis[property] = newValue;

//                            //                            if (property === 'Label') {
//                            //                                control.aasDxChart.define('xAxis', {
//                            //                                    template: function (obj) { return '' }
//                            //                                });
//                            //                            }

//                            control.aasDxChart.define('xAxis', {
//                                title: control.aasChartProperties.XAxis.Title,
//                                template: '#' + control.aasDxChartXAxis + 'Label#'
//                            });

//                            deferredFlush();
//                        }

//                    } else if (controlInfo.name == 'DhtmlxChartYAxis') {

//                        if (control.aasChartProperties.YAxis[control.aasColumnName][property] !== newValue) {

//                            control.aasChartProperties.YAxis[control.aasColumnName][property] = newValue;

//                            var t = translateToObjectProperty(property);

//                            var o = {}; o[t.Property] = newValue;

//                            control.aasDxChart.define(t.Obj, o);

//                            //control.aasDxChart.define('yAxis', {
//                            //    title: control.aasChartProperties.YAxis[control.aasColumnName].Title,
//                            //    start: control.aasChartProperties.YAxis[control.aasColumnName].Start,
//                            //    end: control.aasChartProperties.YAxis[control.aasColumnName].End,
//                            //    step: control.aasChartProperties.YAxis[control.aasColumnName].Step,
//                            //    lines: control.aasChartProperties.YAxis[control.aasColumnName].ShowLine
//                            //});

//                            //control.aasDxChart.define('item', {
//                            //    borderColor: control.aasChartProperties.YAxis[control.aasColumnName].ItemBorderColor,
//                            //    color: control.aasChartProperties.YAxis[control.aasColumnName].ItemColor,
//                            //    borderWidth: control.aasChartProperties.YAxis[control.aasColumnName].ItemBorderWidth,
//                            //    radius: control.aasChartProperties.YAxis[control.aasColumnName].ItemRadius
//                            //});

//                            //control.aasDxChart.define('line', {
//                            //    color: control.aasChartProperties.YAxis[control.aasColumnName].LineColor,
//                            //    width: control.aasChartProperties.YAxis[control.aasColumnName].LineWidth
//                            //});

//                            //                            if (!control.aasChartProperties.YAxis.LabelValue) {
//                            //                                control.aasDxChart.define('label', '');
//                            //                            }

//                            deferredFlush();
//                        }
//                    }
//                }
//            };

//            return control;
//        };
//    }
//};


text:
#pragma once

#include <pcl/pcl_exports.h>
#include <pcl/apps/in_hand_scanner/boost.h>
#include <pcl/apps/in_hand_scanner/eigen.h>
#include <pcl/apps/in_hand_scanner/common_types.h>

////////////////////////////////////////////////////////////////////////////////
// Forward declarations
////////////////////////////////////////////////////////////////////////////////

namespace pcl
{
  template <typename PointT>
  class KdTree;
} // End namespace pcl

////////////////////////////////////////////////////////////////////////////////
// ICP
////////////////////////////////////////////////////////////////////////////////

namespace pcl
{
  namespace ihs
  {
    /** \brief Iterative Closest Point registration.
      * \author Martin Saelzle
      * \ingroup apps
      */
    class PCL_EXPORTS ICP
    {
      public:

        using PointXYZRGBNormal = pcl::PointXYZRGBNormal;
        using CloudXYZRGBNormal = pcl::PointCloud<PointXYZRGBNormal>;
        using CloudXYZRGBNormalPtr = CloudXYZRGBNormal::Ptr;
        using CloudXYZRGBNormalConstPtr = CloudXYZRGBNormal::ConstPtr;

        using Mesh = pcl::ihs::Mesh;
        using MeshPtr = pcl::ihs::MeshPtr;
        using MeshConstPtr = pcl::ihs::MeshConstPtr;

        /** \brief Constructor */
        ICP ();

        /** @{ */
        /** \brief Convergence is detected when the change of the fitness between the current and previous iteration becomes smaller than the given epsilon (set in cm^2). The fitness is the mean squared euclidean distance between corresponding points.
          * \note Only accepted if it is greater than 0.
          */
        void
        setEpsilon (const float epsilon);

        float
        getEpsilon () const;
        /** @} */

        /** @{ */
        /** \brief The registration fails if the number of iterations exceeds the maximum number of iterations.
          * \note Must be greater than 0. Smaller values are set to 1.
          */
        void
        setMaxIterations (const unsigned int max_iter);

        unsigned int
        getMaxIterations () const;
        /** @} */

        /** @{ */
        /** \brief The registration fails at the state of convergence if the overlap between the model and data shape is smaller than a minimum overlap. The overlap is the fraction of correspondences (after rejection) to the initial number of data points.
          * \note Must be between zero and one. Values outside this range are clamped to the nearest valid value.
          */
        void
        setMinOverlap (const float overlap);

        float
        getMinOverlap () const;
        /** @} */

        /** @{ */
        /** \brief The registration fails at the state of convergence if the fitness is bigger than this threshold (set in cm^2)
          * \note Must be greater than zero.
          */
        void
        setMaxFitness (const float fitness);

        float
        getMaxFitness () const;
        /** @} */

        /** @{ */
        /** \brief Correspondences are rejected if the squared distance is above a threshold. This threshold is initialized with infinity (all correspondences are accepted in the first iteration). The threshold of the next iterations is set to the fitness of the current iteration multiplied by the factor set by this method.
          * \note Must be greater or equal one. Smaller values are set to one.
          */
        void
        setCorrespondenceRejectionFactor (const float factor);

        float
        getCorrespondenceRejectionFactor () const;
        /** @} */

        /** @{ */
        /** \brief Correspondences are rejected if the angle between the normals is bigger than this threshold. Set in degrees.
          * \note Must be between 180 degrees and 0. Values outside this range are clamped to the nearest valid value.
          */
        void
        setMaxAngle (const float angle);

        float
        getMaxAngle () const;
        /** @} */

        /** \brief Find the transformation that aligns the data cloud (source) to the model mesh (target).
          * \param[in] mesh_model Model mesh (target).
          * \param[in] cloud_data Data cloud (source).
          * \param[in] T_init Initial guess for the transformation.
          * \paran[out] T_final The computed transformation.
          * \return true if success.
          */
        bool
        findTransformation (const MeshConstPtr&              mesh_model,
                            const CloudXYZRGBNormalConstPtr& cloud_data,
                            const Eigen::Matrix4f&           T_init,
                            Eigen::Matrix4f&                 T_final);

      private:

        using PointNormal = pcl::PointNormal;
        using CloudNormal = pcl::PointCloud<PointNormal>;
        using CloudNormalPtr = CloudNormal::Ptr;
        using CloudNormalConstPtr = CloudNormal::ConstPtr;

        using KdTree = pcl::KdTree<PointNormal>;
        using KdTreePtr = boost::shared_ptr<KdTree>;
        using KdTreeConstPtr = boost::shared_ptr<const KdTree>;

        /** \brief Selects the model points that are pointing towards to the camera (data coordinate system = camera coordinate system).
          * \param[in] mesh_model Input mesh.
          * \param[in] T_inv Transformation that brings the model mesh into the camera coordinate system.
          * \return Cloud containing the selected points (the connectivity information of the mesh is currently not used during the registration).
          */
        CloudNormalConstPtr
        selectModelPoints (const MeshConstPtr&    mesh_model,
                           const Eigen::Matrix4f& T_inv) const;

        /** \brief Selects the valid data points. The input cloud is organized -> contains nans which are removed
          * \param[in] cloud_data Input cloud.
          * \return Cloud containing the selected points.
          */
        CloudNormalConstPtr
        selectDataPoints (const CloudXYZRGBNormalConstPtr& cloud_data) const;

        /** \brief Finds the transformation that minimizes the point to plane distance from the source to the target cloud. The input clouds must be arranged to have one to one correspondences (point 0 in source corresponds to point 0 in target, point 1 in source to point 1 in target and so on).
          * \param[in] cloud_source Source cloud (data).
          * \param[in] cloud_target Target cloud (model).
          * \param[out] T The computed transformation.
          * \return true if success
          */
        bool
        minimizePointPlane (const CloudNormal& cloud_source,
                            const CloudNormal& cloud_target,
                            Eigen::Matrix4f&   T) const;

        ////////////////////////////////////////////////////////////////////////
        // Members
        ////////////////////////////////////////////////////////////////////////

        KdTreePtr kd_tree_;

        // Convergence
        float epsilon_; // in cm^2

        // Registration failure
        unsigned int max_iterations_;
        float min_overlap_; // [0 1]
        float max_fitness_; // in cm^2

        // Correspondence rejection
        float factor_;
        float max_angle_; // in degrees
    };
  } // End namespace ihs
} // End namespace pcl


text:
id: 587d781a367417b2b2512ab9
title: Usar a tag em para colocar o texto em itálico
challengeType: 0
videoUrl: 'https://scrimba.com/c/cVJRBtp'
forumTopicId: 301078
dashedName: use-the-em-tag-to-italicize-text
---

# --description--

Para enfatizar o texto, você pode usar a tag `em`. Essa tag exibe o texto em itálico, pois o navegador, através do CSS, aplica a propriedade e valor `font-style: italic;` ao elemento.

# --instructions--

Envolva o conteúdo da tag de parágrafo com uma tag `em` para dar ênfase.

# --hints--

O código deve adicionar uma tag `em` ao html.

```js
assert($('em').length == 1);
```

A tag `em` deve envolver o conteúdo da tag `p`, mas não a tag `p` em si.

```js
assert($('p').children().length == 1 && $('em').children().length == 2);
```

# --seed--

## --seed-contents--

```html
<style>
  h4 {
    text-align: center;
    height: 25px;
  }
  p {
    text-align: justify;
  }
  .links {
    text-align: left;
    color: black;
  }
  .fullCard {
    width: 245px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin: 10px 5px;
    padding: 4px;
  }
  .cardContent {
    padding: 10px;
  }
  .cardText {
    margin-bottom: 30px;
  }
</style>
<div class="fullCard">
  <div class="cardContent">
    <div class="cardText">
      <h4>Google</h4>
      <p>Google was founded by Larry Page and Sergey Brin while they were <u>Ph.D. students</u> at <strong>Stanford University</strong>.</p>
    </div>
    <div class="cardLinks">
      <a href="https://en.wikipedia.org/wiki/Larry_Page" target="_blank" class="links">Larry Page</a><br><br>
      <a href="https://en.wikipedia.org/wiki/Sergey_Brin" target="_blank" class="links">Sergey Brin</a>
    </div>
  </div>
</div>
```

# --solutions--

```html
<style>
  h4 {
    text-align: center;
    height: 25px;
  }
  p {
    text-align: justify;
  }
  .links {
    text-align: left;
    color: black;
  }
  .fullCard {
    width: 245px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin: 10px 5px;
    padding: 4px;
  }
  .cardContent {
    padding: 10px;
  }
  .cardText {
    margin-bottom: 30px;
  }
</style>
<div class="fullCard">
  <div class="cardContent">
    <div class="cardText">
      <h4>Google</h4>
      <p><em>Google was founded by Larry Page and Sergey Brin while they were <u>Ph.D. students</u> at <strong>Stanford University</strong>.</em></p>
    </div>
    <div class="cardLinks">
      <a href="https://en.wikipedia.org/wiki/Larry_Page" target="_blank" class="links">Larry Page</a><br><br>
      <a href="https://en.wikipedia.org/wiki/Sergey_Brin" target="_blank" class="links">Sergey Brin</a>
    </div>
  </div>
</div>
```


text:
package com.amazonaws.services.certificatemanager.model;

import javax.annotation.Generated;

/**
 * <p>
 * The certificate is in use by another AWS service in the caller's account. Remove the association and try again.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ResourceInUseException extends com.amazonaws.services.certificatemanager.model.AWSCertificateManagerException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new ResourceInUseException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public ResourceInUseException(String message) {
        super(message);
    }

}


text:
namespace _02.Bank
{
    public interface IDeposit
    {
        void Deposit(decimal ammount);
    }
}


text:
var Turbolinks = require("turbolinks")
Turbolinks.start();

// window.$ = require("jquery");
// window.jQuery = $;

// Underscore
// import {} from "underscore";

// =========================================================================
// Secondary vendor libraries
// =========================================================================

// import "velocity";
// import "flying-focus";
import "what-input";
import "lazysizes";
window.store = window.store || require("store/dist/store.modern");

// =========================================================================
// jQuery alternatives
// =========================================================================

// axio.get = $.ajax / $.get
// import "axios";

// =========================================================================
// Polyfills
// Used for older browser support
// =========================================================================

// TODO: Update these to NPM packages where possible

// IE8 Polyfills
// import "../vendor/polyfills/console";
// import "../vendor/polyfills/css3-mediaqueries";
// import "../vendor/polyfills/event-listeners";
// import "../vendor/polyfills/picturefill";
// import "../vendor/polyfills/selectivizr";
// import "../vendor/polyfills/jquery.touchSwipe";
// import "../vendor/polyfills/jquery.placeholder";
// import "../vendor/libs/jquery.youtube-wmode";

// IE11 Polyfills
import "../vendor/polyfills/element.remove";
import "../vendor/polyfills/custom-events";

// Future Polyfills
import "../vendor/polyfills/array.from";
import "../vendor/polyfills/es5-shim";
import "../vendor/polyfills/es5-sham";
import "../vendor/polyfills/classList";
import "../vendor/polyfills/closest-matches";
import "../vendor/polyfills/nodelist-foreach";
import "../vendor/polyfills/url-search-params";
import "../vendor/polyfills/array.find";
import "../vendor/polyfills/promise";
import "../vendor/polyfills/fetch";
import "../vendor/polyfills/fetch-abort-controller";


text:
//
//  ZZDouYuHomeCell.h
//  什么值得买
//
//  Created by Wang_ruzhou on 16/7/15.
//  Copyright © 2016年 Wang_ruzhou. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "ZZDouYuHomeModel.h"

@interface ZZDouYuHomeCollectionViewCell : UICollectionViewCell

/** 模型 */
@property (nonatomic, strong) ZZDouYURoom_List *listModel;

@end


text:
import {Marker} from "../../../Component";

export interface ISpatialMarker {
    id: string;
    lat: number;
    lon: number;
    marker: Marker;
}

export default ISpatialMarker;


text:
package com.dianaui.universal.core.client.ui.constants;

import com.dianaui.universal.core.client.ui.base.helper.EnumHelper;
import com.google.gwt.dom.client.Style;

/**
 * @author Sven Jacobs
 * @author Joshua Godi
 */
public enum Pull implements Style.HasCssName {

    NONE(""),
    LEFT(Styles.PULL_LEFT),
    RIGHT(Styles.PULL_RIGHT);

    private final String cssClass;

    private Pull(final String cssClass) {
        this.cssClass = cssClass;
    }

    public static Pull fromStyleName(final String styleName) {
        return EnumHelper.fromStyleName(styleName, Pull.class, NONE);
    }

    @Override
    public String getCssName() {
        return cssClass;
    }

}


text:
/**
 * @license Angular v4.2.6
 * (c) 2010-2017 Google, Inc. https://angular.io/
 * License: MIT
 */
 export * from './animations/index'


text:
package com.amazonaws.services.pinpointemail.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.pinpointemail.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * EventDestinationMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class EventDestinationMarshaller {

    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Name").build();
    private static final MarshallingInfo<Boolean> ENABLED_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Enabled").build();
    private static final MarshallingInfo<List> MATCHINGEVENTTYPES_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MatchingEventTypes").build();
    private static final MarshallingInfo<StructuredPojo> KINESISFIREHOSEDESTINATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("KinesisFirehoseDestination").build();
    private static final MarshallingInfo<StructuredPojo> CLOUDWATCHDESTINATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CloudWatchDestination").build();
    private static final MarshallingInfo<StructuredPojo> SNSDESTINATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SnsDestination").build();
    private static final MarshallingInfo<StructuredPojo> PINPOINTDESTINATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PinpointDestination").build();

    private static final EventDestinationMarshaller instance = new EventDestinationMarshaller();

    public static EventDestinationMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(EventDestination eventDestination, ProtocolMarshaller protocolMarshaller) {

        if (eventDestination == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(eventDestination.getName(), NAME_BINDING);
            protocolMarshaller.marshall(eventDestination.getEnabled(), ENABLED_BINDING);
            protocolMarshaller.marshall(eventDestination.getMatchingEventTypes(), MATCHINGEVENTTYPES_BINDING);
            protocolMarshaller.marshall(eventDestination.getKinesisFirehoseDestination(), KINESISFIREHOSEDESTINATION_BINDING);
            protocolMarshaller.marshall(eventDestination.getCloudWatchDestination(), CLOUDWATCHDESTINATION_BINDING);
            protocolMarshaller.marshall(eventDestination.getSnsDestination(), SNSDESTINATION_BINDING);
            protocolMarshaller.marshall(eventDestination.getPinpointDestination(), PINPOINTDESTINATION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
layout: page
title: What is Blaubot?
noToc: true
---
Blaubot is a middleware to create small adhoc networks via P2P connections such as Bluetooth-RFCOMM, Adhoc-WiFi or simple socket connections. Blaubot takes care of device discovery and connection establishment with the goal to minimize a developer's boilerplate code to set up these small networks.

Tl;dr our main goal is to let a developer call `start();` and spare him as much hassle as possible to create ad hoc networks.
See it in action:

The source code is hosted on [github](https://github.com/Blaubot/Blaubot). Blaubot is written in Java and has a dedicated version for Android.

#Get started
If you intend to use Blaubot on Android, check out the [Android quickstart guide](/quickstart-android).
To get started using Maven, Gradle or just the jar/aar files, refer to the [general documentation](/documentation).
If you have questions or problems, get in touch with Blaubot users and developers on gitter. [![Gitter](https://badges.gitter.im/Blaubot/Blaubot.svg)](https://gitter.im/Blaubot/Blaubot?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)


text:
<?php
/**
 * Created by Fabrizio Fenoglio.
 *
 * @package Rally v1.0.0
 * Released under MIT Licence
 *
 */

namespace Fenos\Rally\Exceptions;

class AlreadyFollowerException extends \Exception {

}


text:
package com.netflix.spinnaker.credentials.definition;

import com.netflix.spinnaker.credentials.Credentials;

/**
 * Contains properties that define {@link Credentials}. {@link CredentialsDefinition} can be POJOs
 * deserialized from configuration or an external system. These are optional but useful to use
 * built-in {@link CredentialsParser}.
 *
 * <p>equals is checked to detect change in definitions
 */
public interface CredentialsDefinition {
  String getName();
}


text:
extern crate log;
extern crate simplelog;
extern crate num_cpus;

use std::env;
use std::process;
use std::{thread, time};
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use simplelog::{Config, SimpleLogger, CombinedLogger, LogLevelFilter};

// Sleep interval between temperature checking.
const SLEEP_TIME_MILLI: u64 = 3000;

// File where minimum supported frequency should be colected.
const MIN_FREQ_FILE: &'static str = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq";

// File where maximum supported frequency should be colected.
const MAX_FREQ_FILE: &'static str = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";

// Step size to change cpu frequency.
const STEP_FREQ: u64 = 100000;

// Possible files where current temperature should be collected.
const POSSIBLE_TEMP_FILES: &'static [&'static str] = &[
	"/sys/class/thermal/thermal_zone0/temp",
	"/sys/class/thermal/thermal_zone1/temp",
	"/sys/class/thermal/thermal_zone2/temp",
	"/sys/class/hwmon/hwmon0/temp1_input",
	"/sys/class/hwmon/hwmon1/temp1_input",
	"/sys/class/hwmon/hwmon2/temp1_input",
	"/sys/class/hwmon/hwmon0/device/temp1_input",
	"/sys/class/hwmon/hwmon1/device/temp1_input",
	"/sys/class/hwmon/hwmon2/device/temp1_input",
];

fn parse_int_file(path: String) -> u64 {
	let mut content = String::new();
	let mut fp = File::open(path).unwrap();
	fp.read_to_string(&mut content).unwrap();
	content.trim().parse::<u64>().unwrap()
}

fn min_frequency() -> u64 {
	parse_int_file(MIN_FREQ_FILE.to_string())
}

fn max_frequency() -> u64 {
	parse_int_file(MAX_FREQ_FILE.to_string())
}

fn get_temp() -> u64 {
	for file in POSSIBLE_TEMP_FILES {
		if Path::new(file).exists() {
			return parse_int_file(file.to_string()) / 1000;
		}
	}
	error!("impossible to collect current cpu temperature!");
	process::exit(1);
}

fn set_freq(freq: u64) {
	info!("setting frequency to {}", freq);
	for c in 0..num_cpus::get() {
		let path = format!("/sys/devices/system/cpu/cpu{}/cpufreq/scaling_max_freq", c);
		let mut fp = File::create(path).unwrap();
		fp.write_all(format!("{}\n", freq).as_bytes()).unwrap();
	}
}

fn main() {
	CombinedLogger::init(
		vec![
			SimpleLogger::new(LogLevelFilter::Info, Config::default()),
		]
	).unwrap();

	let args: Vec<String> = env::args().collect();
	if args.len() != 2 {
		error!("usage: {} <max temp>", args[0]);
		process::exit(1);
	}

	let max_temp: u64;
	match args[1].parse::<u64>() {
		Err(_) => {
			error!("invalid temperature: {}", args[1]);
			process::exit(1);
		},
		Ok(x) => max_temp = x,
	}
	info!("maximum temperature: {}", max_temp);

	info!("cpu count: {}", num_cpus::get());

	let min_freq = min_frequency();
	info!("minimum frequency supported: {}", min_freq);
	let max_freq = max_frequency();
	info!("maximum frequency supported: {}", max_freq);

	let mut cur_freq = max_freq;
	set_freq(cur_freq);
	loop {
		let temp = get_temp();
		if temp > max_temp && cur_freq > min_freq {
			cur_freq -= STEP_FREQ;
			if cur_freq < min_freq {
				cur_freq = min_freq;
			}
			set_freq(cur_freq);
		}
		else if temp < (max_temp-5) && cur_freq < max_freq {
			cur_freq += STEP_FREQ;
			if cur_freq > max_freq {
				cur_freq = max_freq;
			}
			set_freq(cur_freq);
		}
		debug!("current temperature: {}", temp);
		thread::sleep(time::Duration::from_millis(SLEEP_TIME_MILLI));
	}
}


text:
var async = require('async')
var path = require('path')

module.exports = function (api) {
  var utils = require(path.join(__dirname, '/../utils.js'))(api)

  var del = function (callback) {
    var self = this
    var jobs = []

    if (!self.data.guid) { return callback(new Error('guid is required')) }
    if (!self.index) { return callback(new Error('index is required')) }

    if (!self.data._index) {
      jobs.push(function (done) {
        self.hydrate(done)
      })
    }

    jobs.push(function (done) {
      var query = {
        index: self.data._index,
        refresh: api.config.elasticsearch.refreshOnWrite,
        type: self.type,
        id: self.data.guid
      }

      utils.runWithLimit(api.elasticsearch.client, 'delete', [query], done)
    })

    async.series(jobs, callback)
  }

  return del
}


text:
namespace IStrategizer
{
    class GameEntity;

    class CellFeature
    {
    public:
        ResourceDescription m_resourceDescription;
        ForceDescription m_alliedForceDescription;
        ForceDescription m_enemyForceDescription;
        BuildingDescription m_alliedBuildingDescription;
        BuildingDescription m_enemyBuildingDescription;
        int m_distanceFromEnemyBase;
        int m_distanceFromBase;
        TInfluence m_influnce;
        CellFeature() { Clear(); }
        CellFeature(const PlanStepParameters& p_parameters);
        void AddEntity(GameEntity *p_entity,bool p_isAllied);
        void RemoveEntity(GameEntity *p_entity, bool p_isAllied);
        void Clear();
        void To(PlanStepParameters& p_parameters) const;
        void CalculateDistanceToBases(Vector2 cellWorldPosition);
        float GetDistance(CellFeature *p_other) const;
        float GetInflunceSimilarity (TInfluence& p_otherInflunce) const;

        static const CellFeature& Null() { static CellFeature nullCellFeature; return nullCellFeature; }

    private:
        void CalculateDistanceToBasesAux(Vector2 cellWorldPosition, const EntityList& bases, int& distance) const;
        float GetBaseDistanceSimilarity(int firstBase, int secondBase) const;
    };
}

#endif // CELLFEATURE_H


text:
"use strict";

module.exports = ($core, { $prim, $combinators }) => {
  const { ParseError, Result, StrictParser } = $core;
  const { pure, bind, then, fail, mplus, label, tryParse } = $prim;
  const { choice } = $combinators;

  /**
   * type OperatorType = "infix" \/ "prefix" \/ "postfix"
   */

  /**
   * object OperatorType {
   *   INFIX: "infix";
   *   PREFIX: "prefix";
   *   POSTFIX: "postfix";
   * }
   */
  const OperatorType = Object.freeze({
    INFIX  : "infix",
    PREFIX : "prefix",
    POSTFIX: "postfix",
  });

  /**
   * type OperatorAssoc = "none" \/ "left" \/ "right"
   */

  /**
   * object OperatorAssoc {
   *   NONE: "none";
   *   LEFT: "left";
   *   RIGHT: "right";
   * }
   */
  const OperatorAssoc = Object.freeze({
    NONE : "none",
    LEFT : "left",
    RIGHT: "right",
  });

  /**
   * type InfixOperator[S, U, A] = {
   *   type: "infix",
   *   parser: Parser[S, U, (A, A) => A],
   *   assoc: OperatorAssoc,
   * }
   */

  /**
   * type PrefixOperator[S, U, A] = {
   *   type: "prefix",
   *   parser: Parser[S, U, A => A],
   * }
   */

  /**
   * type PostfixOperator[S, U, A] = {
   *   type: "postfix",
   *   parser: Parser[S, U, A => A],
   * }
   */

  /**
   * type Operator[S, U, A] =
   *      InfixOperator[S, U, A]
   *   \/ PrefixOperator[S, U, A]
   *   \/ PostfixOperator[S, U, A]
   */

  /**
   * object Operator {
   *   infix[S, U, A](
   *     parser: Parser[S, U, (A, A) => A],
   *     assoc: OperatorAssoc
   *   ): InfixOperator[S, U, A];
   *   prefix[S, U, A](parser: Parser[S, U, A => A]): PrefixOperator[S, U, A];
   *   postfix[S, U, A](parser: Parser[S, U, A => A]): PostfixOperator[S, U, A];
   * }
   */
  const Operator = Object.freeze({
    infix(parser, assoc) {
      return { type: OperatorType.INFIX, parser, assoc };
    },
    prefix(parser) {
      return { type: OperatorType.PREFIX, parser };
    },
    postfix(parser) {
      return { type: OperatorType.POSTFIX, parser };
    },
  });

  /**
   * makeParser: [S, U, A](term: Parser[S, U, A], ops: Array[Operator[S, U, A]]) => Parser[S, U, A]
   */
  function makeParser(term, ops) {
    // collect operators
    const nonAssoc   = [];
    const leftAssoc  = [];
    const rightAssoc = [];
    const prefix     = [];
    const postfix    = [];
    for (const op of ops) {
      switch (op.type) {
      case OperatorType.INFIX:
        switch (op.assoc) {
        case OperatorAssoc.NONE:
          nonAssoc.push(op.parser);
          break;
        case OperatorAssoc.LEFT:
          leftAssoc.push(op.parser);
          break;
        case OperatorAssoc.RIGHT:
          rightAssoc.push(op.parser);
          break;
        default:
          throw new Error(`unknown operator associativity: ${op.assoc}`);
        }
        break;
      case OperatorType.PREFIX:
        prefix.push(op.parser);
        break;
      case OperatorType.POSTFIX:
        postfix.push(op.parser);
        break;
      default:
        throw new Error(`unknown operator type: ${op.type}`);
      }
    }

    // create operator parsers
    const nassocOp  = choice(nonAssoc);
    const lassocOp  = choice(leftAssoc);
    const rassocOp  = choice(rightAssoc);
    const prefixOp  = label(choice(prefix), "");
    const postfixOp = label(choice(postfix), "");

    // warn ambiguity (always efail)
    function ambiguous(assoc, parser) {
      return tryParse(
        then(parser, fail(`ambiguous use of a ${assoc} associative operator`))
      );
    }

    const ambiguousNon   = ambiguous("non", nassocOp);
    const ambiguousLeft  = ambiguous("left", lassocOp);
    const ambiguousRight = ambiguous("right", rassocOp);

    // identity
    function id(x) {
      return x;
    }

    // unary operators
    const prefixP  = mplus(prefixOp, pure(id));
    const postfixP = mplus(postfixOp, pure(id));

    // term parser
    const termP = bind(prefixP, pre =>
      bind(term, val =>
        bind(postfixP, post =>
          pure(post(pre(val)))
        )
      )
    );

    // right assoc binary operator
    function rassocP(x) {
      return mplus(
        bind(rassocOp, f =>
          bind(bind(termP, rassocP1), y =>
            pure(f(x, y))
          )
        ),
        mplus(ambiguousLeft, ambiguousNon)
      );
    }

    function rassocP1(x) {
      return new StrictParser(state => {
        const vals = [];
        const operations = [];
        let currentState = state;
        let currentErr = ParseError.unknown(state.pos);
        let consumed = false;
        while (true) {
          const initState = currentState;

          const opRes = rassocOp.run(currentState);
          if (opRes.success) {
            if (opRes.consumed) {
              consumed = true;
              operations.push(opRes.val);
              currentState = opRes.state;
              currentErr = opRes.err;
            } else {
              operations.push(opRes.val);
              currentState = opRes.state;
              currentErr = ParseError.merge(currentErr, opRes.err);
            }
          } else {
            if (opRes.consumed) {
              return opRes;
            } else {
              const ambRes = mplus(ambiguousLeft, ambiguousNon).run(initState); // always efail
              // assert(!ambRes.success && !ambRes.consumed);
              const err = ParseError.merge(ParseError.merge(currentErr, opRes.err), ambRes.err);
              let resVal = x;
              if (vals.length > 0) {
                let currentVal = vals[vals.length - 1];
                for (let i = vals.length - 2; i >= 0; i -= 1) {
                  currentVal = operations[i + 1](vals[i], currentVal);
                }
                resVal = operations[0](resVal, currentVal);
              }
              return consumed
                ? Result.csucc(err, resVal, initState)
                : Result.esucc(err, resVal, initState);
            }
          }

          const termRes = termP.run(currentState);
          if (termRes.success) {
            if (termRes.consumed) {
              consumed = true;
              vals.push(termRes.val);
              currentState = termRes.state;
              currentErr = termRes.err;
            } else {
              vals.push(termRes.val);
              currentState = termRes.state;
              currentErr = ParseError.merge(currentErr, termRes.err);
            }
          } else {
            if (termRes.consumed) {
              return termRes;
            } else {
              if (opRes.consumed) {
                return Result.cfail(ParseError.merge(currentErr, termRes.err));
              } else {
                const ambRes = mplus(ambiguousLeft, ambiguousNon).run(initState); // always efail
                // assert(!ambRes.success && !ambRes.consumed);
                const err = ParseError.merge(ParseError.merge(currentErr, termRes.err), ambRes.err);
                let resVal = x;
                if (vals.length > 0) {
                  let currentVal = vals[vals.length - 1];
                  for (let i = vals.length - 2; i >= 0; i -= 1) {
                    currentVal = operations[i + 1](vals[i], currentVal);
                  }
                  resVal = operations[0](resVal, currentVal);
                }
                return consumed
                  ? Result.csucc(err, resVal, initState)
                  : Result.esucc(err, resVal, initState);
              }
            }
          }
        }
      });
    }

    // left assoc binary operator
    function lassocP(x) {
      return mplus(
        bind(lassocOp, f =>
          bind(termP, y =>
            lassocP1(f(x, y))
          )
        ),
        mplus(ambiguousRight, ambiguousNon)
      );
    }

    function lassocP1(x) {
      return new StrictParser(state => {
        let currentVal = x;
        let currentOperation;
        let currentState = state;
        let currentErr = ParseError.unknown(state.pos);
        let consumed = false;
        while (true) {
          const initState = currentState;

          const opRes = lassocOp.run(currentState);
          if (opRes.success) {
            if (opRes.consumed) {
              consumed = true;
              currentOperation = opRes.val;
              currentState = opRes.state;
              currentErr = opRes.err;
            } else {
              currentOperation = opRes.val;
              currentState = opRes.state;
              currentErr = ParseError.merge(currentErr, opRes.err);
            }
          } else {
            if (opRes.consumed) {
              return opRes;
            } else {
              const ambRes = mplus(ambiguousRight, ambiguousNon).run(initState); // always efail
              // assert(!ambRes.success && !ambRes.consumed);
              const err = ParseError.merge(ParseError.merge(currentErr, opRes.err), ambRes.err);
              return consumed
                ? Result.csucc(err, currentVal, initState)
                : Result.esucc(err, currentVal, initState);
            }
          }

          const termRes = termP.run(currentState);
          if (termRes.success) {
            if (termRes.consumed) {
              consumed = true;
              currentVal = currentOperation(currentVal, termRes.val);
              currentState = termRes.state;
              currentErr = termRes.err;
            } else {
              currentVal = currentOperation(currentVal, termRes.val);
              currentState = termRes.state;
              currentErr = ParseError.merge(currentErr, termRes.err);
            }
          } else {
            if (termRes.consumed) {
              return termRes;
            } else {
              if (opRes.consumed) {
                return Result.cfail(ParseError.merge(currentErr, termRes.err));
              } else {
                const ambRes = mplus(ambiguousRight, ambiguousNon).run(initState); // always efail
                // assert(!ambRes.success && !ambRes.consumed);
                const err = ParseError.merge(ParseError.merge(currentErr, termRes.err), ambRes.err);
                return consumed
                  ? Result.csucc(err, currentVal, initState)
                  : Result.esucc(err, currentVal, initState);
              }
            }
          }
        }
      });
    }

    // non assoc binary operator
    function nassocP(x) {
      return bind(nassocOp, f =>
        bind(termP, y =>
          mplus(
            mplus(
              mplus(ambiguousRight, ambiguousLeft),
              ambiguousNon
            ),
            pure(f(x, y))
          )
        )
      );
    }

    return bind(termP, x =>
      label(
        mplus(
          mplus(
            mplus(rassocP(x), lassocP(x)),
            nassocP(x)
          ),
          pure(x)
        ),
        "operator"
      )
    );
  }

  /**
   * buildExpressionParser: [S, U, A](
   *   opTable: Array[Array[Operator[S, U, A]]],
   *   atom: Parser[S, U, A]
   * ) => Parser[S, U, A]
   */
  function buildExpressionParser(opTable, atom) {
    return opTable.reduce(makeParser, atom);
  }

  return Object.freeze({
    OperatorType,
    OperatorAssoc,
    Operator,
    buildExpressionParser,
  });
};


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

#ifndef __CMDLINE_H__
#define __CMDLINE_H__

//*****************************************************************************
//
// If building with a C++ compiler, make all of the definitions in this header
// have a C binding.
//
//*****************************************************************************
#ifdef __cplusplus
extern "C"
{
#endif

//*****************************************************************************
//
//! \addtogroup cmdline_api
//! @{
//
//*****************************************************************************

//*****************************************************************************
//
//! Defines the value that is returned if the command is not found.
//
//*****************************************************************************
#define CMDLINE_BAD_CMD         (-1)

//*****************************************************************************
//
//! Defines the value that is returned if there are too many arguments.
//
//*****************************************************************************
#define CMDLINE_TOO_MANY_ARGS   (-2)

//*****************************************************************************
//
// Command line function callback type.
//
//*****************************************************************************
typedef int (*pfnCmdLine)(int argc, char *argv[]);

//*****************************************************************************
//
//! Structure for an entry in the command list table.
//
//*****************************************************************************
typedef struct
{
    //
    //! A pointer to a string containing the name of the command.
    //
    const char *pcCmd;

    //
    //! A function pointer to the implementation of the command.
    //
    pfnCmdLine pfnCmd;

    //
    //! A pointer to a string of brief help text for the command.
    //
    const char *pcHelp;
}
tCmdLineEntry;

//*****************************************************************************
//
//! This is the command table that must be provided by the application.
//
//*****************************************************************************
extern tCmdLineEntry g_sCmdTable[];

//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************

//*****************************************************************************
//
// Prototypes for the APIs.
//
//*****************************************************************************
extern int CmdLineProcess(char *pcCmdLine);

//*****************************************************************************
//
// Mark the end of the C bindings section for C++ compilers.
//
//*****************************************************************************
#ifdef __cplusplus
}
#endif

#endif // __CMDLINE_H__


text:
    #include <OpenVanilla/OVBase.h>
#else
    #include "OVBase.h"
#endif

namespace OpenVanilla {
    using namespace std;

    class OVException {
    public:
        class OverflowException {};
    };
};

#endif