text:
package org.apache.hadoop.hbase.master.procedure;

import java.io.IOException;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.master.SplitWALManager;
import org.apache.hadoop.hbase.procedure2.ProcedureStateSerializer;
import org.apache.hadoop.hbase.procedure2.ProcedureSuspendedException;
import org.apache.hadoop.hbase.procedure2.ProcedureUtil;
import org.apache.hadoop.hbase.procedure2.ProcedureYieldException;
import org.apache.hadoop.hbase.procedure2.StateMachineProcedure;
import org.apache.hadoop.hbase.util.RetryCounter;
import org.apache.hadoop.hbase.wal.AbstractFSWALProvider;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProcedureProtos;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ProcedureProtos;

/**
 * The procedure is to split a WAL. It will get an available region server and
 * schedule a {@link SplitWALRemoteProcedure} to actually send the request to region
 * server to split this WAL.
 * It also check if the split wal task really succeed. If the WAL still exists, it will
 * schedule another region server to split this WAL.
 */
@InterfaceAudience.Private
public class SplitWALProcedure
    extends StateMachineProcedure<MasterProcedureEnv, MasterProcedureProtos.SplitWALState>
    implements ServerProcedureInterface {
  private static final Logger LOG = LoggerFactory.getLogger(SplitWALProcedure.class);
  private String walPath;
  private ServerName worker;
  private ServerName crashedServer;
  private RetryCounter retryCounter;

  public SplitWALProcedure() {
  }

  public SplitWALProcedure(String walPath, ServerName crashedServer) {
    this.walPath = walPath;
    this.crashedServer = crashedServer;
  }

  @Override
  protected Flow executeFromState(MasterProcedureEnv env, MasterProcedureProtos.SplitWALState state)
      throws ProcedureSuspendedException, ProcedureYieldException, InterruptedException {
    SplitWALManager splitWALManager = env.getMasterServices().getSplitWALManager();
    switch (state) {
      case ACQUIRE_SPLIT_WAL_WORKER:
        worker = splitWALManager.acquireSplitWALWorker(this);
        setNextState(MasterProcedureProtos.SplitWALState.DISPATCH_WAL_TO_WORKER);
        return Flow.HAS_MORE_STATE;
      case DISPATCH_WAL_TO_WORKER:
        assert worker != null;
        addChildProcedure(new SplitWALRemoteProcedure(worker, crashedServer, walPath));
        setNextState(MasterProcedureProtos.SplitWALState.RELEASE_SPLIT_WORKER);
        return Flow.HAS_MORE_STATE;
      case RELEASE_SPLIT_WORKER:
        boolean finished;
        try {
          finished = splitWALManager.isSplitWALFinished(walPath);
        } catch (IOException ioe) {
          if (retryCounter == null) {
            retryCounter = ProcedureUtil.createRetryCounter(env.getMasterConfiguration());
          }
          long backoff = retryCounter.getBackoffTimeAndIncrementAttempts();
          LOG.warn("Failed to check whether splitting wal {} success, wait {} seconds to retry",
            walPath, backoff / 1000, ioe);
          setTimeout(Math.toIntExact(backoff));
          setState(ProcedureProtos.ProcedureState.WAITING_TIMEOUT);
          skipPersistence();
          throw new ProcedureSuspendedException();
        }
        splitWALManager.releaseSplitWALWorker(worker, env.getProcedureScheduler());
        if (!finished) {
          LOG.warn("Failed to split wal {} by server {}, retry...", walPath, worker);
          setNextState(MasterProcedureProtos.SplitWALState.ACQUIRE_SPLIT_WAL_WORKER);
          return Flow.HAS_MORE_STATE;
        }
        ServerCrashProcedure.updateProgress(env, getParentProcId());
        return Flow.NO_MORE_STATE;
      default:
        throw new UnsupportedOperationException("unhandled state=" + state);
    }
  }

  @Override
  protected void rollbackState(MasterProcedureEnv env,
      MasterProcedureProtos.SplitWALState splitOneWalState)
      throws IOException, InterruptedException {
    if (splitOneWalState == getInitialState()) {
      return;
    }
    throw new UnsupportedOperationException();
  }

  @Override
  protected MasterProcedureProtos.SplitWALState getState(int stateId) {
    return MasterProcedureProtos.SplitWALState.forNumber(stateId);
  }

  @Override
  protected int getStateId(MasterProcedureProtos.SplitWALState state) {
    return state.getNumber();
  }

  @Override
  protected MasterProcedureProtos.SplitWALState getInitialState() {
    return MasterProcedureProtos.SplitWALState.ACQUIRE_SPLIT_WAL_WORKER;
  }

  @Override
  protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException {
    super.serializeStateData(serializer);
    MasterProcedureProtos.SplitWALData.Builder builder =
        MasterProcedureProtos.SplitWALData.newBuilder();
    builder.setWalPath(walPath).setCrashedServer(ProtobufUtil.toServerName(crashedServer));
    if (worker != null) {
      builder.setWorker(ProtobufUtil.toServerName(worker));
    }
    serializer.serialize(builder.build());
  }

  @Override
  protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException {
    super.deserializeStateData(serializer);
    MasterProcedureProtos.SplitWALData data =
        serializer.deserialize(MasterProcedureProtos.SplitWALData.class);
    walPath = data.getWalPath();
    crashedServer = ProtobufUtil.toServerName(data.getCrashedServer());
    if (data.hasWorker()) {
      worker = ProtobufUtil.toServerName(data.getWorker());
    }
  }

  @Override
  protected synchronized boolean setTimeoutFailure(MasterProcedureEnv env) {
    setState(ProcedureProtos.ProcedureState.RUNNABLE);
    env.getProcedureScheduler().addFront(this);
    return false;
  }

  public String getWAL() {
    return walPath;
  }

  @VisibleForTesting
  public ServerName getWorker(){
    return worker;
  }

  @Override
  public ServerName getServerName() {
    return this.crashedServer;
  }

  @Override
  public boolean hasMetaTableRegion() {
    return AbstractFSWALProvider.isMetaFile(new Path(walPath));
  }

  @Override
  public ServerOperationType getServerOperationType() {
    return ServerOperationType.SPLIT_WAL;
  }

  @Override
  protected void afterReplay(MasterProcedureEnv env){
    if(worker != null){
      env.getMasterServices().getSplitWALManager().addUsedSplitWALWorker(worker);
    }

  }
}


text:
package walk

import (
	"github.com/lxn/win"
)

type tabPageListObserver interface {
	onInsertingPage(index int, page *TabPage) error
	onInsertedPage(index int, page *TabPage) error
	onRemovingPage(index int, page *TabPage) error
	onRemovedPage(index int, page *TabPage) error
	onClearingPages(pages []*TabPage) error
	onClearedPages(pages []*TabPage) error
}

type TabPageList struct {
	items    []*TabPage
	observer tabPageListObserver
}

func newTabPageList(observer tabPageListObserver) *TabPageList {
	return &TabPageList{observer: observer}
}

func (l *TabPageList) Add(item *TabPage) error {
	return l.Insert(len(l.items), item)
}

func (l *TabPageList) At(index int) *TabPage {
	return l.items[index]
}

func (l *TabPageList) Clear() error {
	observer := l.observer
	if observer != nil {
		if err := observer.onClearingPages(l.items); err != nil {
			return err
		}
	}

	oldItems := l.items
	l.items = l.items[:0]

	if observer != nil {
		if err := observer.onClearedPages(oldItems); err != nil {
			l.items = oldItems
			return err
		}
	}

	return nil
}

func (l *TabPageList) Index(item *TabPage) int {
	for i, lvi := range l.items {
		if lvi == item {
			return i
		}
	}

	return -1
}

func (l *TabPageList) Contains(item *TabPage) bool {
	return l.Index(item) > -1
}

func (l *TabPageList) indexHandle(handle win.HWND) int {
	for i, page := range l.items {
		if page.Handle() == handle {
			return i
		}
	}

	return -1
}

func (l *TabPageList) containsHandle(handle win.HWND) bool {
	return l.indexHandle(handle) > -1
}

func (l *TabPageList) insertIntoSlice(index int, item *TabPage) {
	l.items = append(l.items, nil)
	copy(l.items[index+1:], l.items[index:])
	l.items[index] = item
}

func (l *TabPageList) Insert(index int, item *TabPage) error {
	observer := l.observer
	if observer != nil {
		if err := observer.onInsertingPage(index, item); err != nil {
			return err
		}
	}

	l.insertIntoSlice(index, item)

	if observer != nil {
		if err := observer.onInsertedPage(index, item); err != nil {
			l.items = append(l.items[:index], l.items[index+1:]...)
			return err
		}
	}

	return nil
}

func (l *TabPageList) Len() int {
	return len(l.items)
}

func (l *TabPageList) Remove(item *TabPage) error {
	index := l.Index(item)
	if index == -1 {
		return nil
	}

	return l.RemoveAt(index)
}

func (l *TabPageList) RemoveAt(index int) error {
	observer := l.observer
	item := l.items[index]
	if observer != nil {
		if err := observer.onRemovingPage(index, item); err != nil {
			return err
		}
	}

	l.items = append(l.items[:index], l.items[index+1:]...)

	if observer != nil {
		if err := observer.onRemovedPage(index, item); err != nil {
			l.insertIntoSlice(index, item)
			return err
		}
	}

	return nil
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

#pragma once
#ifdef ENABLE_LOGS_PREVIEW

#  include "opentelemetry/common/spin_lock_mutex.h"
#  include "opentelemetry/nostd/type_traits.h"
#  include "opentelemetry/sdk/logs/exporter.h"
#  include "opentelemetry/sdk/logs/log_record.h"
#  include "opentelemetry/version.h"

#  include <iostream>
#  include <sstream>

OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace logs
{
/**
 * The OStreamLogRecordExporter exports logs through an ostream (default set to std::cout)
 */
class OStreamLogRecordExporter final : public opentelemetry::sdk::logs::LogRecordExporter
{
public:
  /**
   * Create an OStreamLogRecordExporter. This constructor takes in a reference to an ostream that
   * the Export() method will send log data into. The default ostream is set to stdout.
   */
  explicit OStreamLogRecordExporter(std::ostream &sout = std::cout) noexcept;

  std::unique_ptr<sdk::logs::Recordable> MakeRecordable() noexcept override;

  /**
   * Exports a span of logs sent from the processor.
   */
  opentelemetry::sdk::common::ExportResult Export(
      const opentelemetry::nostd::span<std::unique_ptr<sdk::logs::Recordable>> &records) noexcept
      override;

  /**
   * Marks the OStream Log Exporter as shut down.
   */
  bool Shutdown(
      std::chrono::microseconds timeout = std::chrono::microseconds::max()) noexcept override;

private:
  // The OStream to send the logs to
  std::ostream &sout_;
  // Whether this exporter has been shut down
  bool is_shutdown_ = false;
  mutable opentelemetry::common::SpinLockMutex lock_;
  bool isShutdown() const noexcept;
  void printAttributes(
      const std::unordered_map<std::string, opentelemetry::sdk::common::OwnedAttributeValue> &map,
      const std::string prefix = "\n\t");
};
}  // namespace logs
}  // namespace exporter
OPENTELEMETRY_END_NAMESPACE
#endif


text:
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "GameFramework/PawnMovementComponent.h"
#include "CollidingPawnMovementComponent.generated.h"

/**
 *
 */
UCLASS()
class BORDERLANDS_API UCollidingPawnMovementComponent : public UPawnMovementComponent
{
	GENERATED_BODY()

public:
	virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) override;

};


text:
import type { Selector, PseudoSelector } from "css-what";
export declare type Filter = "first" | "last" | "eq" | "nth" | "gt" | "lt" | "even" | "odd" | "not";
export declare const filterNames: Set<string>;
export interface CheerioSelector extends PseudoSelector {
    name: Filter;
    data: string | null;
}
export declare function isFilter(s: Selector): s is CheerioSelector;
export declare function getLimit(filter: Filter, data: string | null): number;
//# sourceMappingURL=positionals.d.ts.map


text:
module FakeMechanize
  # Responder is a class responsible for creation of responses and errors requests.
  class Responder
    def initialize(responses, errors)
      @responses, @errors = responses, errors
    end

    # Create a new error request. See ErrorRequest for options.
    # If <tt>:method</tt> is omited, all http verbs can answer.
    def error(args)
      if args[:method]
        @errors << ErrorRequest.new(args)
      else
        HttpVerbs.each do |method|
          @errors << ErrorRequest.new({:method => method}.merge(args))
        end
      end
    end

    HttpVerbs.each do |method|
      module_eval <<-EOE, __FILE__, __LINE__
        def #{method}(args = {})
          @responses << Request.new({:method => :#{method}}.merge(args))
        end
      EOE
    end
  end # Responder
end # FakeMechanize


text:
#pragma once

#include <QtWidgets/QGraphicsItem>

class QDomElement;
class QGraphicsTextItem;

namespace twoDModel {
namespace items {

/// Represents some zone on the 2D model world, probably with some text like "Start zone".
class RegionItem : public QGraphicsObject
{
	Q_OBJECT

public:
	explicit RegionItem(QGraphicsItem *parent = 0);

	/// Returns a unique identifier of the region.
	QString id() const;

	/// Sets a unique identifier of the region.
	void setId(const QString &id);

	/// Returns true if the region is filled with hatching.
	bool filled() const;

	/// Enables or disables filling region with hatching.
	void setFilled(bool filled);

	/// Returns text that written over the region.
	QString text() const;

	/// Sets text that written over the region.
	void setText(const QString &text);

	/// Returns the upper-left corner of the text relatively to upper-left corner of the item.
	QPointF textPosition() const;

	/// Sets the upper-left corner of the text relatively to upper-left corner of the item.
	void setTextPosition(const QPointF &pos);

	/// Returns the color of the item`s borders, text and hatching.
	QColor color() const;

	/// Sets the color of the item`s borders, text and hatching.
	void setColor(const QColor &color);

	/// Sets the size of an item on the scene.
	void setSize(const QSizeF &size);

	/// Returns true if the given point in scene coordinates is contained by this region.
	bool containsPoint(const QPointF &point) const;

	/// Returns true if the center of the bounding rect of the given item is contained by this region.
	bool containsItem(QGraphicsItem *item) const;

	QRectF boundingRect() const override;

	virtual void serialize(QDomElement &element);
	virtual void deserialize(const QDomElement &element);

protected:
	void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) override;

private:
	virtual QString regionType() const = 0;

	QPointF deserializePoint(const QDomElement &element, const QString &xAttribute, const QString &yAttribute);

	QGraphicsTextItem *mTextItem;  // Takes ownership
	QString mId;
	bool mFilled;
	QColor mColor;
	QSizeF mSize;
};

}
}


text:
var express = require('express');
var router = express.Router();
var request = require('request');
var config = require('config.json');

router.get('/', function (req, res) {
    // log user out
    delete req.session.token;

    // move success message into local variable so it only appears once (single read)
    var viewData = { success: req.session.success };
    delete req.session.success;

    res.render('login', viewData);
});

router.post('/', function (req, res) {
    // authenticate using api to maintain clean separation between layers
    request.post({
        url: config.apiUrl + '/users/authenticate',
        form: req.body,
        json: true
    }, function (error, response, body) {
        if (error) {
            return res.render('login', { error: 'An error occurred' });
        }

        if (!body.token) {
            return res.render('login', { error: body, username: req.body.username });
        }

		// save the JWT token to a cookie
		res.cookie('auth_token', body.token, {
			expires: new Date(Date.now() + config.authTokenTimeout),
			httpOnly: true
			//secure: true
		});

        // redirect to returnUrl
        var returnUrl = req.query.returnUrl && decodeURIComponent(req.query.returnUrl) || '/';
        res.redirect(returnUrl);
    });
});

module.exports = router;


text:
These are snippets of code created by me during my programming learning process. You are free to reuse the code,
however, these functions are very poorly documented, they have been tested only against several sample inputs,
and bugs are very likely to show up if you decide to reuse this code. If you are looking for solid implementations
of these algorithms to use in your project, I strongly advise against using this particular repository. However,
if you still decide to go with it, all you can find in here is licensed under the MIT licence.

I am aware of the poor code quality, lackluster documentation, lack of any project structures and bad programming practices
that this code exhibits. However, the aim of this repo isn't providing high quality, reusable code. Those were mere
exercises and they fulfilled their goal. I am not going to work on improving this code's quality.

If you are looking for some background on why this code was created, most of files here were answers to programming
and algorythmic exercises I did as part of the Computer Science course that I started in 2014 on Jagiellonian University,
Cracow. They were automatically tested in a code testing system called BaCa.

-Pawel Adamczuk, 2016


text:
layout: post
title: "Learning where you are"
date: 2014-11-25 19:20
comments: true
tags: [work, learning]
---

I've been reflecting on work lately. I enjoy the team I work with, the crews we collaborate with and our clients who are all pretty damn good people. But I feel like I could be learning a lot more, and wondering about something more challenging and which I'll learn more from.

Then: how can I make my current work more challenging and more learning oriented, so that I'm learning and being challenged in new ways without having to lose the great team I'm with.

Tonight was graduation ceremony for TWoA Te Ara Reo Maori Level 2 which I studied this year. Great to complete the course (I had a lot of re-learning to do with regard to study habits!) but tonight signalled a new space in my life too (for now - Level 4 next year?).

So for now I can see a few opportunities to build things up where I'm at -

* Continuing improvements to our technical systems, which I'm enjoying
* Improving team collab within the company, which I think is something we could improve on
* Growing things to a point where we can scale up beyond the current size, which I hope is a goal we share
* Learning new tech to apply within our company, which I realise was easier to justify when I was self-employed

Not quite the same as being on team with people I can learn from, but I'm finding opportunities for improvement where I'm at all the same. And there are lots of good reasons to be happy here too.

Also: Tonight I started jotting down small things I've learned during the day, partly to combat the nag that "I'm not learning anything". I am - it's just easy to not notice sometimes. (Maybe I want to be learning things I value more; maybe I want to be learning more deeply.)


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

package org.chromium.content.browser;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.FrameLayout;

import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.base.WindowAndroid;

/***
 * This view is used by a ContentView to render its content.
 * Call {@link #setCurrentContentViewCore(ContentViewCore)} with the contentViewCore that should be
 * managing the view.
 * Note that only one ContentViewCore can be shown at a time.
 */
@JNINamespace("content")
public class ContentViewRenderView extends FrameLayout {
    // The native side of this object.
    private long mNativeContentViewRenderView;
    private SurfaceHolder.Callback mSurfaceCallback;

    private final SurfaceView mSurfaceView;
    protected ContentViewCore mContentViewCore;

    /**
     * Constructs a new ContentViewRenderView.
     * This should be called and the {@link ContentViewRenderView} should be added to the view
     * hierarchy before the first draw to avoid a black flash that is seen every time a
     * {@link SurfaceView} is added.
     * @param context The context used to create this.
     */
    public ContentViewRenderView(Context context) {
        super(context);

        mSurfaceView = createSurfaceView(getContext());
        mSurfaceView.setZOrderMediaOverlay(true);

        setSurfaceViewBackgroundColor(Color.WHITE);
        addView(mSurfaceView,
                new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT));
        mSurfaceView.setVisibility(GONE);
    }

    /**
     * Initialization that requires native libraries should be done here.
     * Native code should add/remove the layers to be rendered through the ContentViewLayerRenderer.
     * @param rootWindow The {@link WindowAndroid} this render view should be linked to.
     */
    public void onNativeLibraryLoaded(WindowAndroid rootWindow) {
        assert !mSurfaceView.getHolder().getSurface().isValid() :
                "Surface created before native library loaded.";
        assert rootWindow != null;
        mNativeContentViewRenderView = nativeInit(rootWindow.getNativePointer());
        assert mNativeContentViewRenderView != 0;
        mSurfaceCallback = new SurfaceHolder.Callback() {
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                assert mNativeContentViewRenderView != 0;
                nativeSurfaceChanged(mNativeContentViewRenderView,
                        format, width, height, holder.getSurface());
                if (mContentViewCore != null) {
                    mContentViewCore.onPhysicalBackingSizeChanged(
                            width, height);
                }
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                assert mNativeContentViewRenderView != 0;
                nativeSurfaceCreated(mNativeContentViewRenderView);

                onReadyToRender();
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                assert mNativeContentViewRenderView != 0;
                nativeSurfaceDestroyed(mNativeContentViewRenderView);
            }
        };
        mSurfaceView.getHolder().addCallback(mSurfaceCallback);
        mSurfaceView.setVisibility(VISIBLE);
    }

    /**
     * Sets the background color of the surface view.  This method is necessary because the
     * background color of ContentViewRenderView itself is covered by the background of
     * SurfaceView.
     * @param color The color of the background.
     */
    public void setSurfaceViewBackgroundColor(int color) {
        if (mSurfaceView != null) {
            mSurfaceView.setBackgroundColor(color);
        }
    }

    /**
     * Gets the SurfaceView for this ContentViewRenderView
     */
    public SurfaceView getSurfaceView() {
        return mSurfaceView;
    }

    /**
     * Should be called when the ContentViewRenderView is not needed anymore so its associated
     * native resource can be freed.
     */
    public void destroy() {
        mSurfaceView.getHolder().removeCallback(mSurfaceCallback);
        nativeDestroy(mNativeContentViewRenderView);
        mNativeContentViewRenderView = 0;
    }

    public void setCurrentContentViewCore(ContentViewCore contentViewCore) {
        assert mNativeContentViewRenderView != 0;
        mContentViewCore = contentViewCore;

        if (mContentViewCore != null) {
            mContentViewCore.onPhysicalBackingSizeChanged(getWidth(), getHeight());
            nativeSetCurrentWebContents(
                    mNativeContentViewRenderView, mContentViewCore.getWebContents());
        } else {
            nativeSetCurrentWebContents(mNativeContentViewRenderView, null);
        }
    }

    /**
     * This method should be subclassed to provide actions to be performed once the view is ready to
     * render.
     */
    protected void onReadyToRender() {
    }

    /**
     * This method could be subclassed optionally to provide a custom SurfaceView object to
     * this ContentViewRenderView.
     * @param context The context used to create the SurfaceView object.
     * @return The created SurfaceView object.
     */
    protected SurfaceView createSurfaceView(Context context) {
        return new SurfaceView(context);
    }

    /**
     * @return whether the surface view is initialized and ready to render.
     */
    public boolean isInitialized() {
        return mSurfaceView.getHolder().getSurface() != null;
    }

    /**
     * Enter or leave overlay video mode.
     * @param enabled Whether overlay mode is enabled.
     */
    public void setOverlayVideoMode(boolean enabled) {
        int format = enabled ? PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE;
        mSurfaceView.getHolder().setFormat(format);
        nativeSetOverlayVideoMode(mNativeContentViewRenderView, enabled);
    }

    @CalledByNative
    private void onSwapBuffersCompleted() {
        if (mSurfaceView.getBackground() != null) {
            post(new Runnable() {
                @Override public void run() {
                    mSurfaceView.setBackgroundResource(0);
                }
            });
        }
    }

    private native long nativeInit(long rootWindowNativePointer);
    private native void nativeDestroy(long nativeContentViewRenderView);
    private native void nativeSetCurrentWebContents(
            long nativeContentViewRenderView, WebContents webContents);
    private native void nativeSurfaceCreated(long nativeContentViewRenderView);
    private native void nativeSurfaceDestroyed(long nativeContentViewRenderView);
    private native void nativeSurfaceChanged(long nativeContentViewRenderView,
            int format, int width, int height, Surface surface);
    private native void nativeSetOverlayVideoMode(long nativeContentViewRenderView,
            boolean enabled);
}


text:
package org.bigsolr.hadoop;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Writable;

import org.apache.solr.common.SolrInputDocument;

import org.apache.log4j.Logger;

public class SolrInputRecord extends SolrInputDocument implements Writable {

  private static Logger log = Logger.getLogger(SolrInputRecord.class);

  @Override
  public void write(DataOutput out) throws IOException {
    log.info("SolrInputRecord -> write");
    // To-do. No need to Spark
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    log.info("SolrInputRecord -> readFields");
    // To-do. No need to Spark
  }
}


text:
package com.odiago.flumebase.plan;

import java.util.List;

import org.apache.hadoop.conf.Configuration;

import com.odiago.flumebase.parser.TypedField;
import com.odiago.flumebase.parser.WindowSpec;

/**
 * Join two input streams into an output stream based on an
 * expression criterion within a range interval.
 *
 * Requires that the test expression relies on a single "key" column
 * from each of the two input streams.
 */
public class HashJoinNode extends PlanNode {

  private String mLeftName; // name of the left stream.
  private String mRightName; // name of the right stream.
  private TypedField mLeftKey; // the key field from the left stream.
  private TypedField mRightKey; // the key field from the right stream.
  private WindowSpec mWindowWidth; // window spec over which the join is valid.
  private String mOutName; // name to assign to the output stream from this join.
  private List<TypedField> mLeftFields; // field names from the left stream.
  private List<TypedField> mRightFields; // field names from the right stream.
  private Configuration mConf; // user configuration.

  public HashJoinNode(String leftName, String rightName, TypedField leftKey, TypedField rightKey,
      WindowSpec windowWidth, String outName, List<TypedField> leftFieldNames,
      List<TypedField> rightFieldNames, Configuration conf) {
    mLeftName = leftName;
    mRightName = rightName;
    mLeftKey = leftKey;
    mRightKey = rightKey;
    mWindowWidth = windowWidth;
    mOutName = outName;
    mLeftFields = leftFieldNames;
    mRightFields = rightFieldNames;
    mConf = conf;
  }

  protected void formatParams(StringBuilder sb) {
    sb.append("Join mLeftName=");
    sb.append(mLeftName);
    sb.append(", mRightName=");
    sb.append(mRightName);
    sb.append(", mLeftKey=");
    sb.append(mLeftKey);
    sb.append(", mRightKey=");
    sb.append(mRightKey);
    sb.append(", width=");
    sb.append(mWindowWidth);
    sb.append(", outName=");
    sb.append(mOutName);
    formatAttributes(sb);
  }

  public String getLeftName() {
    return mLeftName;
  }

  public String getRightName() {
    return mRightName;
  }

  public TypedField getLeftKey() {
    return mLeftKey;
  }

  public TypedField getRightKey() {
    return mRightKey;
  }

  public WindowSpec getWindowWidth() {
    return mWindowWidth;
  }

  public String getOutputName() {
    return mOutName;
  }

  public Configuration getConf() {
    return mConf;
  }

  public List<TypedField> getLeftFields() {
    return mLeftFields;
  }

  public List<TypedField> getRightFields() {
    return mRightFields;
  }
}


text:
package com.facebook.buck.android;

import com.facebook.buck.core.build.execution.context.ExecutionContext;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.StepExecutionResult;
import com.facebook.buck.step.StepExecutionResults;
import java.io.IOException;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * This step writes the size of a .dex.jar file and the uncompressed size of its contained
 * classes.dex to the given metadata file. We use this information during dex file loading to
 * estimate the amount of disk space we'll need.
 */
class DexJarAnalysisStep implements Step {

  private final ProjectFilesystem filesystem;
  private final Path dexPath;
  private final Path dexMetaPath;

  DexJarAnalysisStep(ProjectFilesystem filesystem, Path dexPath, Path dexMetaPath) {
    this.filesystem = filesystem;
    this.dexPath = dexPath;
    this.dexMetaPath = dexMetaPath;
  }

  @Override
  public StepExecutionResult execute(ExecutionContext context) throws IOException {

    try (ZipFile zf = new ZipFile(filesystem.resolve(dexPath).toFile())) {
      ZipEntry classesDexEntry = zf.getEntry("classes.dex");
      if (classesDexEntry == null) {
        throw new RuntimeException("could not find classes.dex in jar");
      }

      long uncompressedSize = classesDexEntry.getSize();
      if (uncompressedSize == -1) {
        throw new RuntimeException("classes.dex size should be known");
      }

      filesystem.writeContentsToPath(
          String.format("jar:%s dex:%s", filesystem.getFileSize(dexPath), uncompressedSize),
          dexMetaPath);

      return StepExecutionResults.SUCCESS;
    }
  }

  @Override
  public String getShortName() {
    return "dex_meta";
  }

  @Override
  public String getDescription(ExecutionContext context) {
    return String.format("dex_meta dexPath:%s dexMetaPath:%s", dexPath, dexMetaPath);
  }
}


text:
#include "LETypes.h"
#include "OpenTypeUtilities.h"
#include "OpenTypeTables.h"
#include "ICUFeatures.h"
#include "LESwaps.h"

U_NAMESPACE_BEGIN

LEReferenceTo<FeatureTable> FeatureListTable::getFeatureTable(const LETableReference &base, le_uint16 featureIndex, LETag *featureTag, LEErrorCode &success) const
{
  if (featureIndex >= SWAPW(featureCount) || LE_FAILURE(success)) {
    return LEReferenceTo<FeatureTable>();
  }

    Offset featureTableOffset = featureRecordArray[featureIndex].featureTableOffset;

    *featureTag = SWAPT(featureRecordArray[featureIndex].featureTag);

    return LEReferenceTo<FeatureTable>(base, success, SWAPW(featureTableOffset));
}

#if 0
/*
 * Note: according to the OpenType Spec. v 1.4, the entries in the Feature
 * List Table are sorted alphabetically by feature tag; however, there seem
 * to be some fonts which have an unsorted list; that's why the binary search
 * is #if 0'd out and replaced by a linear search.
 *
 * Also note: as of ICU 2.6, this method isn't called anyhow...
 */
const FeatureTable *FeatureListTable::getFeatureTable(LETag featureTag) const
{
#if 0
    Offset featureTableOffset =
        OpenTypeUtilities::getTagOffset(featureTag, (TagAndOffsetRecord *) featureRecordArray, SWAPW(featureCount));

    if (featureTableOffset == 0) {
        return 0;
    }

    return (const FeatureTable *) ((char *) this + SWAPW(featureTableOffset));
#else
    int count = SWAPW(featureCount);

    for (int i = 0; i < count; i += 1) {
        if (SWAPT(featureRecordArray[i].featureTag) == featureTag) {
            return (const FeatureTable *) ((char *) this + SWAPW(featureRecordArray[i].featureTableOffset));
        }
    }

    return 0;
#endif
}
#endif

U_NAMESPACE_END


text:
require "spec_helper"

describe Lita::Handlers::Wordnik, lita_handler: true do
  let(:response) { double("Faraday::Response", status: 200, body: body) }

  it { is_expected.to route_command("define computer").to(:define) }
  it { is_expected.to route_command("synonyms cold").to(:synonyms) }
  it { is_expected.to route_command("syn cold").to(:synonyms) }
  it { is_expected.to route_command("words like cold").to(:synonyms) }
  it { is_expected.to route_command("antonyms cold").to(:antonyms) }
  it { is_expected.to route_command("ant cold").to(:antonyms) }
  it { is_expected.to route_command("words unlike cold").to(:antonyms) }

  context "with Faraday stubbing" do
    before do
      allow_any_instance_of( Faraday::Connection).to receive(:get).and_return(response)
    end

    describe "#define" do
      let(:body) do
        <<-BODY.chomp
[
  {
    "word": "computer",
    "text": "A device that computes, especially a programmable electronic \
machine that performs high-speed mathematical or logical operations or that \
assembles, stores, correlates, or otherwise processes information.",
    "partOfSpeech": "noun"
  }
]
BODY
      end

      context "when the API key is set" do
        before { registry.config.handlers.wordnik.api_key = "abc123" }

        it "replies with the definition" do
          send_command("define computer")
          expect(replies.last).to include("computer (noun): A device that")
        end

        it "URL encodes words" do
          word = "a phrase with a % sign in it"
          expect(URI).to receive(:encode).with(word)
          send_command("define #{word}")
        end

        it "replies that Wordnik didn't understand the word on 400 status" do
          allow(response).to receive(:status).and_return(400)
          send_command("define computer")
          expect(replies.last).to include("didn't understand")
        end

        it "replies that Wordnik has no definitions on 404 status" do
          allow(response).to receive(:status).and_return(404)
          send_command("define computer")
          expect(replies.last).to include("doesn't have any results")
        end

        it "logs an error and replies that the request completely failed" do
          allow(response).to receive(:status).and_return(500)
          send_command("define computer")
          expect(replies.last).to include("request failed")
        end

        context "when the response has no definitions" do
          let(:body) { "[]" }

          it "replies that Wordnik has no definitions" do
            send_command("define whiskey stone")
            expect(replies.last).to include("doesn't have any results")
          end
        end
      end
    end

    describe "#synonyms" do
      let(:body) do
        <<-BODY.chomp
[
  {
    "words": [
      "stoical",
      "frigid",
      "unconcerned",
      "bleak",
      "indifferent"
    ],
    "relationshipType": "synonym"
  }
]
BODY
      end

      before { registry.config.handlers.wordnik.api_key = "abc123" }

      it "replies with synonyms" do
        send_command("synonyms cold")
        expect(replies.last).to include("(synonyms): stoical, frigid, unconcerned, bleak, indifferent")
      end
    end

    describe "#antonyms" do
      let(:body) do
    <<-BODY.chomp
[
  {
    "words": [
      "hot"
    ],
    "relationshipType": "antonym"
  }
]
BODY
      end

      before { registry.config.handlers.wordnik.api_key = "abc123" }

      it "replies with antonyms" do
        send_command("antonyms cold")
        expect(replies.last).to include("(antonyms): hot")
      end
    end
  end
end


text:
[Index](./index.md)

# Notes

- ![Word Cloud](./assets/wordcloud.png)

notes on topic that i've learnt

## Browser
- how does a browser work
  - parsing
  - AST
  - rendering

## HTML
- html5 elements
- encoding
- canvas
- ARIA
- web components

## CSS
- CSS 2.1
- CSS 3
- tools:
  - SASS
  - LESS
- Libraries/frameworks/platform:
  - bootstrap

## JavaScript
- EMCAScript:
  - ES5 language features
  - ES6 language features
  - standalone features:
    - AJAX
    - local storage
    - session storage
    - cookies
    - offline storage
    - geolocation
    - feature detection
- Browser based JS ( window/screen/location/navigator/history )
- DOM based functions ( document )
- Design knowledge:
  - Patterns
  - promises
  - push notification
  - async/await
- Libraries/frameworks/platform:
  - lodash
  - jQuery
  - momentjs
  - react
  - redux
  - require
  - typescript

## Fonts
- font-face

## Images/Video

## SVG

## Dev tools
- Chrome dev tools

## Linting
- JS linter
  - eslint
- CSS linter
- SCSS linter

## Testing
- framework:
  - mocha
  - karma
  - jasmine
  - enzyme
- assertion lib:
  - chai
  - expect

## Testing Code coverage
- lib:
  - istanbul

## Front End build system
- task runners:
  - grunt
  - gulp
- module bundlers:
  - browserify
  - webpack

## Performance

## Security

## Package Manager
- npm
- yarn

## Version Control
- git
- github

## git
- branching model

## Restful API
- API Convention
- data format

## Network
- Protocols
  - http response codes
  - http vs http2
  - ftp vs smtp

## Server
- NodeJS
- express

## Database
- mongodb
- couchdb
- firebase
- sql

## Documentation
- jsdoc
- documentation.js

## Others
- How to design/architecture an app
  - SPA, multi-page, front-end build system
- Internationalization (i18n)
- Localization (l10n)
- Generating ssl certificate
- OAuth authenitication

## Editor
- atom
- visual studio
- sublime


text:
#ifndef __CC_EGLVIEW_DESKTOP_H__
#define __CC_EGLVIEW_DESKTOP_H__

#include "platform/CCCommon.h"
#include "platform/CCEGLViewProtocol.h"
#include "glfw3.h"

NS_CC_BEGIN

class CC_DLL EGLView : public EGLViewProtocol
{
public:
    // static function
    /**
     @brief    get the shared main open gl window
     */
    static EGLView* getInstance();

    /** @deprecated Use getInstance() instead */
    CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView();

    /**
     * @js ctor
     */
    EGLView();
    /**
     * @js NA
     * @lua NA
     */
    virtual ~EGLView();

    /* override functions */
    virtual bool isOpenGLReady();
    virtual void end();
    virtual void swapBuffers();
    virtual void setFrameSize(float width, float height);
    virtual void setIMEKeyboardState(bool bOpen);
    /*
     *frameZoomFactor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop.
     */
    bool init(const std::string& viewName, float width, float height, float frameZoomFactor = 1.0f);
    bool initWithFullScreen(const std::string& viewName);

    //void resize(int width, int height);

	float getFrameZoomFactor();
    //void centerWindow();

    virtual void setViewPortInPoints(float x , float y , float w , float h);
    virtual void setScissorInPoints(float x , float y , float w , float h);

    bool windowShouldClose();
    void pollEvents();
    GLFWwindow* getWindow() const { return _mainWindow; }

protected:
    /*
     * Set zoom factor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop.
     */
    void setFrameZoomFactor(float zoomFactor);
    bool initGlew();
    inline bool isRetina() { return _isRetina; };

    bool _captured;
    bool _supportTouch;
    bool _isRetina;

    float _frameZoomFactor;
    static EGLView* s_pEglView;

    GLFWwindow* _mainWindow;
    GLFWmonitor* _primaryMonitor;
    friend class EGLViewEventHandler;
};

NS_CC_END   // end of namespace   cocos2d

#endif	// end of __CC_EGLVIEW_DESKTOP_H__


text:
import io
import logging
import xml.etree.ElementTree as ET
import os
import sys

import itertools
import progressbar as pb
import time

from text.corpus import Corpus
from text.document import Document
from text.mirna_entity import mirna_graph
from text.protein_entity import get_uniprot_name
from text.sentence import Sentence

type_match = {"MiRNA": "mirna",
              "Gene": "protein",
              "unknown miRNA-gene regulation": "miRNA-gene",
              "direct miRNA-gene regulation": "miRNA-gene",
              "N/A gene-miRNA regulation": "gene-miRNA",
              "RADLEX": "radlex"}
              # "gene-miRNA regulation": ""}
class BratCorpus(Corpus):
    """
    BRAT corpus format used for NER and RE tasks.
    self.path is the base directory of the files of this corpus.
    """
    def __init__(self, corpusdir, **kwargs):
        super(BratCorpus, self).__init__(corpusdir, **kwargs)
        self.subtypes = []

    def load_corpus(self, corenlpserver, process=True):
        # self.path is the base directory of the files of this corpus
        trainfiles = [self.path + '/' + f for f in os.listdir(self.path) if f.endswith('.txt')]
        total = len(trainfiles)
        widgets = [pb.Percentage(), ' ', pb.Bar(), ' ', pb.AdaptiveETA(), ' ', pb.Timer()]
        pbar = pb.ProgressBar(widgets=widgets, maxval=total, redirect_stdout=True).start()
        time_per_abs = []
        for current, f in enumerate(trainfiles):
            #logging.debug('%s:%s/%s', f, current + 1, total)
            print '{}:{}/{}'.format(f, current + 1, total)
            did = f.split(".")[0].split("/")[-1]
            t = time.time()
            with io.open(f, 'r', encoding='utf8') as txt:
                doctext = txt.read()
            newdoc = Document(doctext, process=False, did=did)
            newdoc.sentence_tokenize("biomedical")
            if process:
                newdoc.process_document(corenlpserver, "biomedical")
            self.documents[newdoc.did] = newdoc
            abs_time = time.time() - t
            time_per_abs.append(abs_time)
            #logging.info("%s sentences, %ss processing time" % (len(newdoc.sentences), abs_time))
            pbar.update(current+1)
        pbar.finish()
        abs_avg = sum(time_per_abs)*1.0/len(time_per_abs)
        logging.info("average time per abstract: %ss" % abs_avg)

    def load_annotations(self, ann_dir, etype, pairtype="all"):
        self.clear_annotations()
        self.clear_annotations("protein")
        self.clear_annotations("mirna")
        tagged = 0
        not_tagged = 0
        pmids = []
        annfiles = [ann_dir + '/' + f for f in os.listdir(ann_dir) if f.endswith('.ann')]
        total = len(annfiles)
        time_per_abs = []
        doc_to_relations = {}
        # print doc_to_relations
        # print self.documents.keys()
        # print doc_to_relations.keys()
        for did in self.documents:
            self.documents[did].relations = set()
            if did in doc_to_relations:
                for r in doc_to_relations[did]:
                    self.documents[did].relations.add(r)
                # print did, self.documents[did].relations
        for current, f in enumerate(annfiles):
            logging.debug('%s:%s/%s', f, current + 1, total)
            did = f.split(".")[0].split("/")[-1]
            pmids.append(did.split("/")[-1])
            with io.open(f, 'r', encoding="utf8") as txt:
                for line in txt:
                    # print line
                    if line.startswith("T"):
                        tid, ann, etext = line.strip().split("\t")
                        entity_type, dstart, dend = ann.split(" ")
                        if etype == "all" or (etype != "all" and etype == type_match[entity_type]):
                            dstart, dend = int(dstart), int(dend)
                            # print self.documents.keys()
                            sentence = self.documents[did].find_sentence_containing(dstart, dend, chemdner=False)
                            if sentence is not None:
                                # e[0] and e[1] are relative to the document, so subtract sentence offset
                                start = dstart - sentence.offset
                                end = dend - sentence.offset
                                eid = sentence.tag_entity(start, end, type_match[entity_type], text=etext)
                                if eid is not None:
                                    tagged += 1
                                else:
                                    not_tagged += 1
                            else:
                                print "could not find sentence for this span: {}-{}".format(dstart, dend)
        logging.info("normalizing entities...")
        for sentence in self.get_sentences("goldstandard"):
                for e in sentence.entities.elist["goldstandard"]:
                    e.normalize()
        self.find_relations(pairtype)
        # self.evaluate_normalization()
        print "tagged: {} not tagged: {}".format(tagged, not_tagged)
        with open(ann_dir[:-1] + "-pmids.txt", 'w') as pmidsfile:
            pmidsfile.write("\n".join(pmids) + "\n")
        # self.run_ss_analysis(pairtype)

    def find_relations(self, pairtype):
        # automatically find the relations from the gold standard at sentence level
        with open("corpora/miRTex/mirtex_relations.txt", 'w') as rfile:
            for sentence in self.get_sentences(hassource="goldstandard"):
                did = sentence.did
                for pair in itertools.combinations(sentence.entities.elist["goldstandard"], 2):
                    # consider that the first entity may appear before or after the second
                    if (pair[0].text, pair[1].text) in self.documents[did].relations or \
                       (pair[1].text, pair[0].text) in self.documents[did].relations:
                        if (pair[1].text, pair[0].text) in self.documents[did].relations:
                            pair = (pair[1], pair[0])
                        start, end = pair[0].dstart, pair[1].dend
                        if start > end:
                            start, end = pair[1].dstart, pair[0].dend
                        between_text = self.documents[did].text[start:end]
                        if between_text.count(pair[0].text) > 1 or between_text.count(pair[1].text) > 1:
                            # print "excluded:", between_text
                            continue
                        # print between_text
                        pair[0].targets.append((pair[1].eid, pairtype))
                        rfile.write("{}\t{}\n".format(pair[0].normalized, pair[1].normalized))

def get_brat_gold_ann_set(goldpath, entitytype, pairtype):
    logging.info("loading gold standard... {}".format(goldpath))
    annfiles = [goldpath + '/' + f for f in os.listdir(goldpath) if f.endswith('.ann')]
    gold_offsets = set()
    for current, f in enumerate(annfiles):
            did = f.split(".")[0].split("/")[-1]
            with open(f, 'r') as txt:
                for line in txt:
                    if line.startswith("T"):
                        tid, ann, etext = line.strip().split("\t")
                        etype, dstart, dend = ann.split(" ")
                        if entitytype == type_match[etype]:
                            dstart, dend = int(dstart), int(dend)
                            gold_offsets.add((did, dstart, dend, etext))
    gold_relations = {}
    return gold_offsets, gold_relations


text:
package org.apache.stratos.autoscaler.deployment.policy;

import static org.junit.Assert.*;

import java.io.File;

import org.apache.stratos.autoscaler.exception.InvalidPolicyException;
import org.apache.stratos.autoscaler.partition.deployers.PartitionReader;
import org.apache.stratos.autoscaler.policy.deployers.DeploymentPolicyReader;
import org.apache.stratos.cloud.controller.deployment.partition.Partition;
import org.junit.Before;
import org.junit.Test;

/**
 * @author nirmal
 *
 */
public class PartitionDeployerTest {

    PartitionReader reader, reader1;

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        reader = new PartitionReader(new File("src/test/resources/partitions.xml"));
        reader1 = new PartitionReader(new File("src/test/resources/partition.xml"));
    }

    @Test
    public void testPartitionCount() throws InvalidPolicyException {

        assertEquals(2, reader.getPartitionList().size());
    }

    @Test
    public void testPartition() throws InvalidPolicyException {

        assertEquals(1, reader1.getPartitionList().size());

        Partition p = reader1.getPartitionList().get(0);
        assertEquals("P1", p.getId());
        assertEquals(3, p.getPartitionMax());
        assertEquals(2, p.getProperties().getProperties().length);
    }

}


text:
class ExceptionsApp < Rambulance::ExceptionsApp
  include CurrentResourceHelper

  helper ApplicationHelper
  helper CurrentResourceHelper

  def not_found
    respond_to do |format|
      format.any { render(formats: :html, content_type: "text/html", layout: "error") }
    end
  end

  def internal_server_error
  end

  def unprocessable_entity
  end
end


text:
package sigar_test

import (
	. "github.com/cloudfoundry/bosh-agent/internal/github.com/onsi/ginkgo"
	. "github.com/cloudfoundry/bosh-agent/internal/github.com/onsi/gomega"

	"testing"
)

func TestGosigar(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Gosigar Suite")
}


text:
#include <cassert>
#include <cmath>

#include "Tudat/Mathematics/BasicMathematics/linearAlgebra.h"

namespace tudat
{
namespace basic_mathematics
{
namespace linear_algebra
{

//! Compute cosine of the angle between two vectors.
double computeCosineOfAngleBetweenVectors( const Eigen::VectorXd& vector0,
                                           const Eigen::VectorXd& vector1 )
{
    assert( vector0.size( ) == vector1.size( ) );

    // Get the cosine of the angle by dotting the normalized vectors.
    double dotProductOfNormalizedVectors = vector0.normalized( ).dot( vector1.normalized( ) );

    // Explicitly define the extreme cases, which can give problems with the acos function.
    if ( dotProductOfNormalizedVectors >= 1.0 )
    {
        return 1.0;
    }

    else if ( dotProductOfNormalizedVectors <= -1.0 )
    {
        return -1.0;
    }
    // Determine the actual angle.
    else
    {
        return dotProductOfNormalizedVectors;
    }
}

//! Compute angle between two vectors.
double computeAngleBetweenVectors( const Eigen::VectorXd& vector0, const Eigen::VectorXd& vector1 )
{
    // Determine the cosine of the angle by using another routine.
    double dotProductOfNormalizedVectors = computeCosineOfAngleBetweenVectors( vector0, vector1 );

    // Return arccosine of the above, which is effectively the angle.
    return std::acos( dotProductOfNormalizedVectors );
}

} // namespace linear_algebra
} // namespace basic_mathematics
} // namespace tudat


text:
var normalizePath = require('./normalizePath');

function getLookUpPaths(currentModuleDir, path) {
    var currentDir,
        currentModuleDirArr,
        nodeModuleDirArr,
        lookUpPaths = [],
        i;

    function pushToLookUpPaths(path) {
        var currentDir = normalizePath(path);

        if(currentDir) {
            lookUpPaths.push(currentDir);
        }
    }

    if(path.charAt(0) === '.') {
        pushToLookUpPaths(currentModuleDir + '/' + path);
    } else if(path.charAt(0) === '/') {
        pushToLookUpPaths(path);
    } else {
        nodeModuleDirArr = currentModuleDir.match(/.*?node_modules/gi);
        if(nodeModuleDirArr) {
            for(i=nodeModuleDirArr.length-1; i>=0; i--) {
                currentDir = nodeModuleDirArr.join('') + '/' + path;
                pushToLookUpPaths(currentDir);
                nodeModuleDirArr.pop();
            }
        } //else {      // documentation on http://nodejs.org/docs/v0.4.8/api/modules.html
                        // doesnt seem to be right. node is actually appending
                        // node_modules to every parent folder even if the script
                        // is inside a node_modules folder.
                        // Uncomment this when its fixed.
            currentModuleDirArr = currentModuleDir.split('/');
            for(i=currentModuleDirArr.length-1; i>=0; i--) {
                currentDir = currentModuleDirArr.join('/') + '/node_modules/' + path;
                pushToLookUpPaths(currentDir);
                currentModuleDirArr.pop();
            }
            if(currentModuleDir.charAt(0) !== '/') {
                currentDir = 'node_modules/' + path;
                pushToLookUpPaths(currentDir);
            }
        //}
    }

    return lookUpPaths;
}

module.exports = getLookUpPaths;


text:
salt.modules.mac_brew_pkg
=========================

.. automodule:: salt.modules.mac_brew_pkg
    :members:


text:
import { MerchantSafe } from '@cardstack/cardpay-sdk';

import { Resolver } from 'did-resolver';
import { getResolver } from '@cardstack/did-resolver';

// created at date affects sorting of safes, making it a constant makes it so safes are by default ordered by the order they're provided
export const DEFAULT_CREATED_AT_DATE = 0;

export const getFilenameFromDid = async (did: string) => {
  let resolver = new Resolver({ ...getResolver() });
  let resolvedDID = await resolver.resolve(did);
  if (!resolvedDID?.didDocument?.alsoKnownAs) {
    throw new Error('Could not resolve DID to filename');
  }
  let didAlsoKnownAs = resolvedDID.didDocument.alsoKnownAs[0];
  return didAlsoKnownAs.split('/')[4].split('.')[0];
};

const defaultMerchantSafe: MerchantSafe = {
  address: 'DEFAULT_MERCHANT_ADDRESS', // should be overwritten in factory
  createdAt: DEFAULT_CREATED_AT_DATE,
  tokens: [],
  owners: ['DEFAULT_MERCHANT_OWNER_ADDRESS'], // should be overwritten in factory
  type: 'merchant',
  accumulatedSpendValue: 0,
  merchant: 'EOA_ADDRESS', // should be overwritten in factory
  infoDID: 'did:cardstack:example-did', // should be overwritten in factory
};
/**
 * Defaults create a freshly created merchant without customization:
 * {
 *   address: 'DEFAULT_MERCHANT_ADDRESS', // should be overwritten in factory
 *   createdAt: DEFAULT_CREATED_AT_DATE,
 *   tokens: [],
 *   owners: ['DEFAULT_MERCHANT_OWNER_ADDRESS'], // should be overwritten in factory
 *   type: 'merchant',
 *   accumulatedSpendValue: 0,
 *   merchant: 'EOA_ADDRESS', // should be overwritten in factory
 * }
 */
export const createMerchantSafe = (
  opts: Partial<MerchantSafe>
): MerchantSafe => ({
  ...defaultMerchantSafe,
  createdAt: DEFAULT_CREATED_AT_DATE,
  ...opts,
  address: opts.address!,
  owners: opts.owners!,
  merchant: opts.merchant!,
});


text:
tonal-starfield-simulation
==========================

Visual simulation for EOH 2015. Based off of [Kinect 4 Unreal](http://opaquemultimedia.com/index.html?pages/k4u.html&k4u).

## Development

#### Setup (windows)
  - [Unreal Engine](https://www.unrealengine.com/) version 4.6.1 (free for students with the [GitHub Student Developer Pack](https://education.github.com/pack/))
  - [Kinect for Windows v2](http://www.microsoft.com/en-us/kinectforwindows/) (hardware)
  - [Kinect for Windows SDK 2.0](http://www.microsoft.com/en-us/download/details.aspx?id=44561)
  - [Visual Studio Express 2013](http://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx)


text:
/*!
 * Cursor jQuery Plugin v1.0
 * By Kohei MATSUSHITA - https://github.com/ma2shita/cursor-jquery-plugin
 * Released under the MIT license (MIT-LICENSE.txt)
 */
;(function($){
	var defaults = {
		cursorElement: 'li',
		currentClassName: 'pointed',
		debug: false
	};

	function logger(n, e) {
		if (defaults['debug']) {
			if (e) {
				console.debug(n, e);
			} else {
				console.debug(n);
			}
		}
	}

	$.fn.cursor = function(options){
		var elem = this;
		$.extend(defaults, options);

		elem.find(defaults['cursorElement']).live('click', function(e){
			elem.find(defaults['cursorElement'] + '.' + defaults['currentClassName']).removeClass(defaults['currentClassName']);
			$(this).addClass(defaults['currentClassName']);
		});

		return this.each(function(){
			var next = $.fn.cursor.next = function(){ //public
				var c = current();
				var t = target(c, 'next');
				move(c, t);
				return c;
			}
			var prev = $.fn.cursor.prev = function(){ //public
				var c = current();
				var t = target(c, 'prev');
				move(c, t);
				return c;
			}
			var current = $.fn.cursor.current = function(){ //public
				var c = elem.find(defaults['cursorElement'] + '.' + defaults['currentClassName']).first();
				logger('c=', c);
				return c;
			}
			var target = function(current, action){ //private
				var sets = {
					next: {method: 'next', selector: 'first'},
					prev: {method: 'prev', selector: 'last'}
				};
				var method = sets[action]['method'];
				var selector = sets[action]['selector'];
				var t = (current.length == 1) ? eval('current.' + method + '()') : elem.find(defaults['cursorElement'] + ':' + selector);
				logger('t=', t);
				return t;
			}
			var move = function(from, to){ //private
				if (to.length == 1) {
					from.removeClass(defaults['currentClassName']);
					to.addClass(defaults['currentClassName']);
					var p1 = to.position()['top'];
					var p2 = Math.floor($(window).height()/2);
					var p3 = Math.floor(to.height()/2);
					$(document).scrollTop(p1 - p2 + p3);
				}
			}
		});
	};
})(jQuery);


text:
"""Utils for preprocessing sequences."""

import numpy as np
import tensorflow.compat.v1 as tf

AA_TOKENS = ('A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P',
             'Q', 'R', 'S', 'T', 'V', 'W', 'Y')
# Includes list of anomalous amino acids based on IUPAC:
# http://publications.iupac.org/pac/1984/pdf/5605x0595.pdf
AA_ANOMALOUS_TOKENS = ('B', 'O', 'U', 'X', 'Z')
AA_ALIGN_TOKENS = ('.', '-')

def pad_sequences(sequences, length=None, value=None):
  """Pads integer sequences to a certain length.

  Args:
    sequences: A list of variable-length and integer-encoded sequences.
    length: The padding length. If `None`, the maximum sequences length is used.
    value: The padding value. If `None`, the maximum of `sequences` plus one
      will be used.

  Returns:
    A `np.ndarray` with shape `(len(sequences), length)` that represents the
    encoded sequences.
  """
  if value is None:
    value = max(np.max(seq) for seq in sequences) + 1
  if length is None:
    length = max(len(seq) for seq in sequences)
  return tf.keras.preprocessing.sequence.pad_sequences(
      sequences, maxlen=length, padding='post', value=value)

def unpad_sequences(sequences, value):
  """Unpads sequences.

  Note that all occurrences of `value` in `sequences` are removed, also if
  they are not at the end of the sequence.

  Args:
    sequences: A matrix of padded integer-encoded sequences.
    value: The padding value.

  Returns:
    A list of sequences without `value`.
  """
  sequences = [np.asarray(seq) for seq in sequences]
  return [seq[seq != value] for seq in sequences]

def sequences_end_with_value(sequences, value, axis=-1):
  """Tests if `sequences` and with `value` along `axis`.

  Args:
    sequences: A matrix of integer-encoded sequences.
    value: An integer value.
    axis: Axis of `sequences` to test.

  Returns:
    A boolean `np.nadarray` that indicates for each sequences if it ends with
    `value` along `axis`.
  """
  sequences = np.asarray(sequences)
  return np.all(np.diff((sequences == value).astype(np.int8), axis=axis) >= 0,
                axis)

def strip_sequences_at_value(sequences, value):
  """Sets all values after the first occurrence of `value` to value`.

  For example:
    sequences = [[0, 1, 2], [0, 1, 0, 1]]
    value = 1
    Returns: [[0, 1, 1], [0, 1, 1, 1]]

  Args:
    sequences: An iterable of integer-encoded sequences, possibly of different
      length.
    value: An integer value.

  Returns:
    A list of sequences with all values set to `value` after the first
    occurrence of `value`.
  """
  stripped = []
  for seq in sequences:
    seq = np.array(seq)
    idx = np.where(seq == value)[0]
    if idx.size:
      seq[idx[0]:] = value
    stripped.append(seq)
  return stripped


text:
/**
 * CreativeAssignment.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.dfa.axis.v1_20;

public class CreativeAssignment  implements java.io.Serializable {
    private boolean active;

    private java.lang.String alternalteText;

    private com.google.api.ads.dfa.axis.v1_20.ClickThroughUrl clickThroughUrl;

    private com.google.api.ads.dfa.axis.v1_20.CreativeGroupAssignment creativeGroupAssignment;

    private long creativeId;

    private java.util.Calendar endDate;

    private com.google.api.ads.dfa.axis.v1_20.RichMediaExitOverride[] richMediaExitOverrides;

    private int sequence;

    private java.util.Calendar startDate;

    private int weight;

    public CreativeAssignment() {
    }

    public CreativeAssignment(
           boolean active,
           java.lang.String alternalteText,
           com.google.api.ads.dfa.axis.v1_20.ClickThroughUrl clickThroughUrl,
           com.google.api.ads.dfa.axis.v1_20.CreativeGroupAssignment creativeGroupAssignment,
           long creativeId,
           java.util.Calendar endDate,
           com.google.api.ads.dfa.axis.v1_20.RichMediaExitOverride[] richMediaExitOverrides,
           int sequence,
           java.util.Calendar startDate,
           int weight) {
           this.active = active;
           this.alternalteText = alternalteText;
           this.clickThroughUrl = clickThroughUrl;
           this.creativeGroupAssignment = creativeGroupAssignment;
           this.creativeId = creativeId;
           this.endDate = endDate;
           this.richMediaExitOverrides = richMediaExitOverrides;
           this.sequence = sequence;
           this.startDate = startDate;
           this.weight = weight;
    }

    /**
     * Gets the active value for this CreativeAssignment.
     *
     * @return active
     */
    public boolean isActive() {
        return active;
    }

    /**
     * Sets the active value for this CreativeAssignment.
     *
     * @param active
     */
    public void setActive(boolean active) {
        this.active = active;
    }

    /**
     * Gets the alternalteText value for this CreativeAssignment.
     *
     * @return alternalteText
     */
    public java.lang.String getAlternalteText() {
        return alternalteText;
    }

    /**
     * Sets the alternalteText value for this CreativeAssignment.
     *
     * @param alternalteText
     */
    public void setAlternalteText(java.lang.String alternalteText) {
        this.alternalteText = alternalteText;
    }

    /**
     * Gets the clickThroughUrl value for this CreativeAssignment.
     *
     * @return clickThroughUrl
     */
    public com.google.api.ads.dfa.axis.v1_20.ClickThroughUrl getClickThroughUrl() {
        return clickThroughUrl;
    }

    /**
     * Sets the clickThroughUrl value for this CreativeAssignment.
     *
     * @param clickThroughUrl
     */
    public void setClickThroughUrl(com.google.api.ads.dfa.axis.v1_20.ClickThroughUrl clickThroughUrl) {
        this.clickThroughUrl = clickThroughUrl;
    }

    /**
     * Gets the creativeGroupAssignment value for this CreativeAssignment.
     *
     * @return creativeGroupAssignment
     */
    public com.google.api.ads.dfa.axis.v1_20.CreativeGroupAssignment getCreativeGroupAssignment() {
        return creativeGroupAssignment;
    }

    /**
     * Sets the creativeGroupAssignment value for this CreativeAssignment.
     *
     * @param creativeGroupAssignment
     */
    public void setCreativeGroupAssignment(com.google.api.ads.dfa.axis.v1_20.CreativeGroupAssignment creativeGroupAssignment) {
        this.creativeGroupAssignment = creativeGroupAssignment;
    }

    /**
     * Gets the creativeId value for this CreativeAssignment.
     *
     * @return creativeId
     */
    public long getCreativeId() {
        return creativeId;
    }

    /**
     * Sets the creativeId value for this CreativeAssignment.
     *
     * @param creativeId
     */
    public void setCreativeId(long creativeId) {
        this.creativeId = creativeId;
    }

    /**
     * Gets the endDate value for this CreativeAssignment.
     *
     * @return endDate
     */
    public java.util.Calendar getEndDate() {
        return endDate;
    }

    /**
     * Sets the endDate value for this CreativeAssignment.
     *
     * @param endDate
     */
    public void setEndDate(java.util.Calendar endDate) {
        this.endDate = endDate;
    }

    /**
     * Gets the richMediaExitOverrides value for this CreativeAssignment.
     *
     * @return richMediaExitOverrides
     */
    public com.google.api.ads.dfa.axis.v1_20.RichMediaExitOverride[] getRichMediaExitOverrides() {
        return richMediaExitOverrides;
    }

    /**
     * Sets the richMediaExitOverrides value for this CreativeAssignment.
     *
     * @param richMediaExitOverrides
     */
    public void setRichMediaExitOverrides(com.google.api.ads.dfa.axis.v1_20.RichMediaExitOverride[] richMediaExitOverrides) {
        this.richMediaExitOverrides = richMediaExitOverrides;
    }

    /**
     * Gets the sequence value for this CreativeAssignment.
     *
     * @return sequence
     */
    public int getSequence() {
        return sequence;
    }

    /**
     * Sets the sequence value for this CreativeAssignment.
     *
     * @param sequence
     */
    public void setSequence(int sequence) {
        this.sequence = sequence;
    }

    /**
     * Gets the startDate value for this CreativeAssignment.
     *
     * @return startDate
     */
    public java.util.Calendar getStartDate() {
        return startDate;
    }

    /**
     * Sets the startDate value for this CreativeAssignment.
     *
     * @param startDate
     */
    public void setStartDate(java.util.Calendar startDate) {
        this.startDate = startDate;
    }

    /**
     * Gets the weight value for this CreativeAssignment.
     *
     * @return weight
     */
    public int getWeight() {
        return weight;
    }

    /**
     * Sets the weight value for this CreativeAssignment.
     *
     * @param weight
     */
    public void setWeight(int weight) {
        this.weight = weight;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof CreativeAssignment)) return false;
        CreativeAssignment other = (CreativeAssignment) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            this.active == other.isActive() &&
            ((this.alternalteText==null && other.getAlternalteText()==null) ||
             (this.alternalteText!=null &&
              this.alternalteText.equals(other.getAlternalteText()))) &&
            ((this.clickThroughUrl==null && other.getClickThroughUrl()==null) ||
             (this.clickThroughUrl!=null &&
              this.clickThroughUrl.equals(other.getClickThroughUrl()))) &&
            ((this.creativeGroupAssignment==null && other.getCreativeGroupAssignment()==null) ||
             (this.creativeGroupAssignment!=null &&
              this.creativeGroupAssignment.equals(other.getCreativeGroupAssignment()))) &&
            this.creativeId == other.getCreativeId() &&
            ((this.endDate==null && other.getEndDate()==null) ||
             (this.endDate!=null &&
              this.endDate.equals(other.getEndDate()))) &&
            ((this.richMediaExitOverrides==null && other.getRichMediaExitOverrides()==null) ||
             (this.richMediaExitOverrides!=null &&
              java.util.Arrays.equals(this.richMediaExitOverrides, other.getRichMediaExitOverrides()))) &&
            this.sequence == other.getSequence() &&
            ((this.startDate==null && other.getStartDate()==null) ||
             (this.startDate!=null &&
              this.startDate.equals(other.getStartDate()))) &&
            this.weight == other.getWeight();
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        _hashCode += (isActive() ? Boolean.TRUE : Boolean.FALSE).hashCode();
        if (getAlternalteText() != null) {
            _hashCode += getAlternalteText().hashCode();
        }
        if (getClickThroughUrl() != null) {
            _hashCode += getClickThroughUrl().hashCode();
        }
        if (getCreativeGroupAssignment() != null) {
            _hashCode += getCreativeGroupAssignment().hashCode();
        }
        _hashCode += new Long(getCreativeId()).hashCode();
        if (getEndDate() != null) {
            _hashCode += getEndDate().hashCode();
        }
        if (getRichMediaExitOverrides() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getRichMediaExitOverrides());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getRichMediaExitOverrides(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        _hashCode += getSequence();
        if (getStartDate() != null) {
            _hashCode += getStartDate().hashCode();
        }
        _hashCode += getWeight();
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(CreativeAssignment.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://www.doubleclick.net/dfa-api/v1.20", "CreativeAssignment"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("active");
        elemField.setXmlName(new javax.xml.namespace.QName("", "active"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("alternalteText");
        elemField.setXmlName(new javax.xml.namespace.QName("", "alternalteText"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/encoding/", "string"));
        elemField.setNillable(true);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("clickThroughUrl");
        elemField.setXmlName(new javax.xml.namespace.QName("", "clickThroughUrl"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.doubleclick.net/dfa-api/v1.20", "ClickThroughUrl"));
        elemField.setNillable(true);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("creativeGroupAssignment");
        elemField.setXmlName(new javax.xml.namespace.QName("", "creativeGroupAssignment"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.doubleclick.net/dfa-api/v1.20", "CreativeGroupAssignment"));
        elemField.setNillable(true);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("creativeId");
        elemField.setXmlName(new javax.xml.namespace.QName("", "creativeId"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("endDate");
        elemField.setXmlName(new javax.xml.namespace.QName("", "endDate"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime"));
        elemField.setNillable(true);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("richMediaExitOverrides");
        elemField.setXmlName(new javax.xml.namespace.QName("", "richMediaExitOverrides"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.doubleclick.net/dfa-api/v1.20", "RichMediaExitOverride"));
        elemField.setNillable(true);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("sequence");
        elemField.setXmlName(new javax.xml.namespace.QName("", "sequence"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("startDate");
        elemField.setXmlName(new javax.xml.namespace.QName("", "startDate"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime"));
        elemField.setNillable(true);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("weight");
        elemField.setXmlName(new javax.xml.namespace.QName("", "weight"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
package org.radargun;

/**
 * Return value from {@link org.radargun.MasterStage} or {@link org.radargun.DistStage}, that should signal
 * which stage should follow.
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
public enum StageResult {
   /**
    * Continue with next stage (this stage was successful).
    */
   SUCCESS,
   /**
    * Fail current scenario (this stage was not successful).
    */
   FAIL,
   /**
    * Fail current scenario and do not execute scenarios with any further configurations.
    */
   EXIT,

   /**
    * Break the innermost repeat
    */
   BREAK,

   /**
    * Continue with the next cycle of the innermost repeat
    */
   CONTINUE;

   public boolean isError() {
      return this == FAIL || this == EXIT;
   }
}


text:
package edu.ucsf.lava.crms.people.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

import edu.ucsf.lava.core.action.ActionUtils;
import edu.ucsf.lava.core.controller.BaseListComponentHandler;
import edu.ucsf.lava.core.controller.ComponentCommand;
import edu.ucsf.lava.core.controller.ScrollablePagedListHolder;
import edu.ucsf.lava.core.dao.LavaDaoFilter;
import edu.ucsf.lava.crms.people.model.AddPatientCommand;
import edu.ucsf.lava.crms.people.model.Patient;

public class AddPatientLookupHandler extends BaseListComponentHandler {

	public AddPatientLookupHandler() {
		this.setHandledList("foundPatients","patient");
		this.setEntityForStandardSourceProvider(Patient.class);
	}

	public LavaDaoFilter extractFilterFromRequest(RequestContext context, Map components) {
		HttpServletRequest request =  ((ServletExternalContext)context.getExternalContext()).getRequest();
		LavaDaoFilter filter = Patient.newFilterInstance(getCurrentUser(request));
		return filter;
	}

	public void updateFilterFromContext(LavaDaoFilter filter, RequestContext context, Map components){
	}

	public Event preEventHandled(RequestContext context, Object command, BindingResult errors) throws Exception {
		if(ActionUtils.getEventId(context).equalsIgnoreCase("addPatient__saveAdd")){
			return handlePreAddPatientSaveAdd(context,command,errors);
		}
		return new Event(this,SUCCESS_FLOW_EVENT_ID);
	}

	protected Event handlePreAddPatientSaveAdd(RequestContext context, Object command, BindingResult errors) throws Exception {
		Map components = ((ComponentCommand)command).getComponents();
		AddPatientCommand apc = (AddPatientCommand) components.get("addPatient");
		ScrollablePagedListHolder entityList = (ScrollablePagedListHolder) ((ComponentCommand)command).getComponents().get("foundPatients");
		LavaDaoFilter filter = (LavaDaoFilter)entityList.getFilter();
		if (apc.getPatient().getId()==null){
			filter.clearParams();
			filter.setParam("deidentified", apc.getDeidentified());
			filter.setParam("subjectId",apc.getSubjectId());
			filter.setParam("firstName",apc.getPatient().getFirstName());
			filter.setParam("lastName",apc.getPatient().getLastName());
			filter.setParam("birthDate",apc.getPatient().getBirthDate());
		}else{
			filter.clearParams();
		}
		((BaseListSourceProvider)entityList.getSourceProvider()).setListHandler(this);
		entityList.doRefresh();
		if (entityList.getNrOfElements()>0){

			errors.addError(new ObjectError(errors.getObjectName(),new String[]{"addPatient.foundExistingPatients"},null,""));
			return new Event(this,ERROR_FLOW_EVENT_ID);
		}
		return new Event(this,SUCCESS_FLOW_EVENT_ID);
	}

	public LavaDaoFilter onPostFilterParamConversion(LavaDaoFilter daoFilter) {

		if (daoFilter.getParam("deidentified")!=null && (Boolean)daoFilter.getParam("deidentified")){
			if(daoFilter.getParam("subjectId")==null || daoFilter.getParam("birthDate")==null){
				return emptyPatientLookupDaoFilter(daoFilter);
			}
			//setup dao params for query
			daoFilter.addDaoParam(daoFilter.daoNamedParam("firstName",daoFilter.getParam("subjectId")));
			daoFilter.addDaoParam(daoFilter.daoNamedParam("lastName",Patient.DEIDENTIFIED));
			daoFilter.addDaoParam(daoFilter.daoNamedParam("birthDate",daoFilter.getParam("birthDate")));
		}else{

			if(daoFilter.getParam("firstName")==null || daoFilter.getParam("lastName")==null || daoFilter.getParam("birthDate")==null){
				return emptyPatientLookupDaoFilter(daoFilter);
			}
			daoFilter.addDaoParam(daoFilter.daoNamedParam("firstName",daoFilter.getParam("firstName")));
			daoFilter.addDaoParam(daoFilter.daoNamedParam("lastName",daoFilter.getParam("lastName")));
			daoFilter.addDaoParam(daoFilter.daoNamedParam("birthDate",daoFilter.getParam("birthDate")));
		}
		return daoFilter;
	}

	protected LavaDaoFilter emptyPatientLookupDaoFilter(LavaDaoFilter daoFilter){
		daoFilter.addDaoParam(daoFilter.daoNamedParam("firstName",(String)null));
		daoFilter.addDaoParam(daoFilter.daoNamedParam("lastName",(String)null));
		daoFilter.addDaoParam(daoFilter.daoNamedParam("birthDate",(Date)null));
		return daoFilter;
	}

	public List getList(Class entityClass, LavaDaoFilter daoFilter) {
		return Patient.addPatientLookup(daoFilter);
	}

}


text:
//
//  GDataFeedYouTubeVideoMessage.h
//

#if !GDATA_REQUIRE_SERVICE_INCLUDES || GDATA_INCLUDE_YOUTUBE_SERVICE

#import "GDataFeedBase.h"

// Note: the video message *entry* is a subclass of the YouTube video entry,
// but this feed class derives just from GDataFeedBase, not from the
// video feed class

@interface GDataFeedYouTubeVideoMessage : GDataFeedBase
+ (GDataFeedYouTubeVideoMessage *)videoMessageFeed;
@end

#endif // !GDATA_REQUIRE_SERVICE_INCLUDES || GDATA_INCLUDE_YOUTUBE_SERVICE


text:
import selectors
import socket
import loopfunction
import logging
import queue
import maxthreads

class Log:
    INDENTATION = 4

    def __init__(self, *args_):
        self.do = {'errors': False,
                   'enter': False,
                   'exit': False,
                   'args': False}

        for i in args_:
            if i not in self.do and i != 'all':
                print('ERROR:' + i)
                raise ValueError('{} is not a valid variable'.format(i))

        for i in self.do.keys():
            if i in args_ or 'all' in args_:
                self.do[i] = True

    def __call__(self, f):
        def wrapped_f(*args, **kwargs):
            if self.do['enter']:
                logging.debug(self._indent_string(
                             'function {} called with\n'.format(f.__name__) +
                             'args={}\n'.format(args) +
                             'kwargs={}'.format(kwargs), self.INDENTATION))
            try:
                f(*args, **kwargs)
            except:
                if self.do['errors']:
                    logging.error(self._indent_string(
                                  'function {} was called with\n'.format(f.__name__) +
                                  'args={}\n'.format(args) +
                                  'kwargs={}\n'.format(kwargs) +
                                  'and exited with error:\n' +
                                  '-'*50 + '\n' +
                                  logging.traceback.format_exc() +
                                  '-'*50 + '\n', self.INDENTATION))
                raise
            else:
                if self.do['exit']:
                    logging.debug('function {} exited normally'.format(f.__name__))
        return wrapped_f

    @staticmethod
    def _indent_string(string, indentation):
        return (' '*indentation).join(string.splitlines(True))

class SocketServer:

    @Log('errors')
    def __init__(self,
                 port=1234,
                 host=socket.gethostbyname(socket.gethostname()),
                 queue_size=1000,
                 block_time=2,
                 selector=selectors.EpollSelector,
                 handle_readable=lambda client: True,
                 handle_incoming=lambda client, address: True,
                 max_subthreads=-1):

        self.port = port
        self.host = host
        self.queue_size = queue_size
        self.block_time = block_time
        self.selector = selector
        self.handle_readable = handle_readable
        self.handle_incoming = handle_incoming

        self._server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._server_socket.setblocking(False)

        self._accept_selector = selector()
        self._recv_selector = selector()

        self._accept_selector.register(self._server_socket, selectors.EVENT_READ)

        self._loop_objects = (
            loopfunction.Loop(target=self._mainthread_accept_clients,
                              on_start=lambda: logging.debug('Thread started: Accept clients'),
                              on_stop=lambda: logging.debug('Thread stopped: Accept clients')),

            loopfunction.Loop(target=self._mainthread_poll_readable,
                              on_start=lambda: logging.debug('Thread started: Poll for readable clients'),
                              on_stop=lambda: logging.debug('Thread stopped: Poll for readable clients')),

        )

        self._threads_limiter = maxthreads.MaxThreads(max_subthreads)
        self.clients = {}

    @Log('errors')
    def _mainthread_accept_clients(self):
        """Accepts new clients and sends them to the to _handle_accepted within a subthread
        """
        try:
            if self._accept_selector.select(timeout=self.block_time):
                client = self._server_socket.accept()
                logging.info('Client connected: {}'.format(client[1]))

                self._threads_limiter.start_thread(target=self._subthread_handle_accepted,
                                                   args=(client,))
        except socket.error:
            pass

    @Log('errors')
    def _mainthread_poll_readable(self):
        """Searches for readable client sockets. These sockets are then put in a subthread
        to be handled by _handle_readable
        """
        events = self._recv_selector.select(self.block_time)
        for key, mask in events:
            if mask == selectors.EVENT_READ:
                self._recv_selector.unregister(key.fileobj)

                self._threads_limiter.start_thread(target=self._subthread_handle_readable,
                                                   args=(key.fileobj,))

    @Log('errors')
    def _subthread_handle_accepted(self, client):
        """Gets accepted clients from the queue object and sets up the client socket.
        The client can then be found in the clients dictionary with the socket object
        as the key.
        """

        conn, addr = client
        if self.handle_incoming(conn, addr):
            logging.info('Accepted connection from client: {}'.format(addr))
            conn.setblocking(False)
            self.clients[conn] = addr
            self.register(conn)
        else:
            logging.info('Refused connection from client: {}'.format(addr))
            self.disconnect(conn)

    @Log('errors')
    def _subthread_handle_readable(self, conn):
        """Handles readable client sockets. Calls the user modified handle_readable with
        the client socket as the only variable. If the handle_readable function returns
        true the client is again registered to the selector object otherwise the client
        is disconnected.
        """

        if self.handle_readable(conn):
            self.register(conn)
        else:
            self.disconnect(conn)

    @Log('all')
    def start(self):
        logging.info('Binding server socket to {}:{}'.format(self.host, self.port))
        self._server_socket.bind((self.host, self.port))

        self._server_socket.listen(self.queue_size)
        logging.info('Server socket now listening (queue_size={})'.format(self.queue_size))

        logging.info('Starting main threads...')
        for loop_obj in self._loop_objects:
            loop_obj.start()

        logging.info('Main threads started')

    @Log('all')
    def stop(self):
        logging.info('Closing all ({}) connections...'.format(len(self.clients)))

        self.disconnect(self.clients)
        logging.info('Stopping main threads...')
        for loop_obj in self._loop_objects:
            loop_obj.send_stop_signal(silent=True)

        for loop_obj in self._loop_objects:
            loop_obj.stop(silent=True)

        logging.info('Shutting down server socket...')
        self._server_socket.shutdown(socket.SHUT_RDWR)
        logging.info('Closing server socket...')
        self._server_socket.close()

    @Log('errors')
    def register(self, client, silent=False):
        try:
            self._recv_selector.register(client, selectors.EVENT_READ)
        except KeyError:
            if not silent:
                logging.error(
                    'Tried to register an already registered client: {}'.format(self.clients[client]))
                raise KeyError('Client already registered')

    @Log('errors')
    def unregister(self, client, silent=False):
        try:
            self._recv_selector.unregister(client)
        except KeyError:
            if not silent:
                logging.error(
                    'Tried to unregister a client that is not registered: {}'.format(self.clients[client]))
                raise KeyError('Client already registered')

    @Log('errors')
    def disconnect(self, client, how=socket.SHUT_RDWR):
        if hasattr(client, '__iter__'):
            if client == self.clients:
                client = self.clients.copy()
            for i in client:
                self.disconnect(i, how)

        else:
            self.unregister(client, True)
            address = 'Could not find address'
            try:
                address = client.getpeername()
                client.shutdown(socket.SHUT_RDWR)
            except socket.error:
                pass
            client.close()

            try:
                address = self.clients[client]
                del self.clients[client]
            except KeyError:
                pass
            logging.info('Client disconnected: {}'.format(address))