text:
title:  inQuire
date:  07/02/2020
---

#### inQuire

`How is your personal devotional life?`

`When have you had times that your devotions have been consistent? Inconsistent? In a rut?`

`When have you had times when you've had amazing devotions? What made the difference?`

`Why do you think it is hard to have a consistent devotional life?`

`What are some of the greatest hindrances to personal devotions?`

`Given that we are not saved by works, why is it a temptation to think doing devotions is a part of our salvific work?`

`Can we be saved without a devotional life, though?`

`What role do devotions play in the Christian life?`

`What are some practical things you can share that have helped you in your devotional life?`

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

<meta charset=utf-8 >
<title>SfunCorps Globe R1</title>
<meta name=viewport content='width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no' >
<meta name=description content='' >
<meta name=keywords content='WebGL,Three.js,JavaScript,GitHub,FOSS,3D,STEM' >
<meta name=date content='2016-07-23' >


text:
namespace TestApp.Common.Logging341
{
    using Tethys.Logging.Controls;

    partial class MainForm
  {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
      if (disposing && (this.components != null))
      {
        this.components.Dispose();
      }
      base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.groupAddEvent = new System.Windows.Forms.GroupBox();
      this.btnAddAllEvents = new System.Windows.Forms.Button();
      this.radioCustomText = new System.Windows.Forms.RadioButton();
      this.radioDefaultText = new System.Windows.Forms.RadioButton();
      this.txtEventText = new System.Windows.Forms.TextBox();
      this.lblText = new System.Windows.Forms.Label();
      this.comboEventType = new System.Windows.Forms.ComboBox();
      this.lblType = new System.Windows.Forms.Label();
      this.btnAddEvent = new System.Windows.Forms.Button();
      this.rtfLogView = new Tethys.Logging.Controls.RtfLogView();
      this.groupAddEvent.SuspendLayout();
      this.SuspendLayout();
      //
      // groupAddEvent
      //
      this.groupAddEvent.Controls.Add(this.btnAddAllEvents);
      this.groupAddEvent.Controls.Add(this.radioCustomText);
      this.groupAddEvent.Controls.Add(this.radioDefaultText);
      this.groupAddEvent.Controls.Add(this.txtEventText);
      this.groupAddEvent.Controls.Add(this.lblText);
      this.groupAddEvent.Controls.Add(this.comboEventType);
      this.groupAddEvent.Controls.Add(this.lblType);
      this.groupAddEvent.Controls.Add(this.btnAddEvent);
      this.groupAddEvent.Location = new System.Drawing.Point(12, 12);
      this.groupAddEvent.Name = "groupAddEvent";
      this.groupAddEvent.Size = new System.Drawing.Size(532, 133);
      this.groupAddEvent.TabIndex = 15;
      this.groupAddEvent.TabStop = false;
      this.groupAddEvent.Text = " Add Event ";
      //
      // btnAddAllEvents
      //
      this.btnAddAllEvents.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
      this.btnAddAllEvents.Location = new System.Drawing.Point(426, 74);
      this.btnAddAllEvents.Name = "btnAddAllEvents";
      this.btnAddAllEvents.Size = new System.Drawing.Size(96, 48);
      this.btnAddAllEvents.TabIndex = 21;
      this.btnAddAllEvents.Text = "Add All Events";
      this.btnAddAllEvents.Click += new System.EventHandler(this.BtnAddAllEventsClick);
      //
      // radioCustomText
      //
      this.radioCustomText.AutoSize = true;
      this.radioCustomText.Location = new System.Drawing.Point(19, 66);
      this.radioCustomText.Name = "radioCustomText";
      this.radioCustomText.Size = new System.Drawing.Size(123, 17);
      this.radioCustomText.TabIndex = 20;
      this.radioCustomText.TabStop = true;
      this.radioCustomText.Text = "Use customized text:";
      this.radioCustomText.UseVisualStyleBackColor = true;
      this.radioCustomText.CheckedChanged += new System.EventHandler(this.CheckChanged);
      //
      // radioDefaultText
      //
      this.radioDefaultText.AutoSize = true;
      this.radioDefaultText.Location = new System.Drawing.Point(19, 43);
      this.radioDefaultText.Name = "radioDefaultText";
      this.radioDefaultText.Size = new System.Drawing.Size(99, 17);
      this.radioDefaultText.TabIndex = 19;
      this.radioDefaultText.TabStop = true;
      this.radioDefaultText.Text = "Use default text";
      this.radioDefaultText.UseVisualStyleBackColor = true;
      this.radioDefaultText.CheckedChanged += new System.EventHandler(this.CheckChanged);
      //
      // txtEventText
      //
      this.txtEventText.Location = new System.Drawing.Point(78, 89);
      this.txtEventText.Name = "txtEventText";
      this.txtEventText.Size = new System.Drawing.Size(232, 20);
      this.txtEventText.TabIndex = 18;
      //
      // lblText
      //
      this.lblText.Location = new System.Drawing.Point(38, 89);
      this.lblText.Name = "lblText";
      this.lblText.Size = new System.Drawing.Size(32, 20);
      this.lblText.TabIndex = 17;
      this.lblText.Text = "Text:";
      this.lblText.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
      //
      // comboEventType
      //
      this.comboEventType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
      this.comboEventType.Location = new System.Drawing.Point(56, 16);
      this.comboEventType.Name = "comboEventType";
      this.comboEventType.Size = new System.Drawing.Size(121, 21);
      this.comboEventType.TabIndex = 16;
      //
      // lblType
      //
      this.lblType.Location = new System.Drawing.Point(16, 16);
      this.lblType.Name = "lblType";
      this.lblType.Size = new System.Drawing.Size(32, 24);
      this.lblType.TabIndex = 15;
      this.lblType.Text = "Type:";
      this.lblType.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
      //
      // btnAddEvent
      //
      this.btnAddEvent.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
      this.btnAddEvent.Location = new System.Drawing.Point(426, 16);
      this.btnAddEvent.Name = "btnAddEvent";
      this.btnAddEvent.Size = new System.Drawing.Size(96, 48);
      this.btnAddEvent.TabIndex = 3;
      this.btnAddEvent.Text = "Add New Event";
      this.btnAddEvent.Click += new System.EventHandler(this.BtnAddEventClick);
      //
      // rtfLogView
      //
      this.rtfLogView.AddAtTail = true;
      this.rtfLogView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
      this.rtfLogView.LabelText = "Status:";
      this.rtfLogView.Location = new System.Drawing.Point(12, 153);
      this.rtfLogView.Margin = new System.Windows.Forms.Padding(4);
      this.rtfLogView.MaxLogLength = -1;
      this.rtfLogView.Name = "rtfLogView";
      this.rtfLogView.ShowDebugEvents = false;
      this.rtfLogView.Size = new System.Drawing.Size(531, 148);
      this.rtfLogView.TabIndex = 16;
      this.rtfLogView.TextColor = System.Drawing.Color.Black;
      //
      // MainForm
      //
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
      this.ClientSize = new System.Drawing.Size(556, 312);
      this.Controls.Add(this.rtfLogView);
      this.Controls.Add(this.groupAddEvent);
      this.Name = "MainForm";
      this.Text = "Logging Tests for Common.Logging";
      this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainFormFormClosing);
      this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainFormFormClosed);
      this.Load += new System.EventHandler(this.MainFormLoad);
      this.groupAddEvent.ResumeLayout(false);
      this.groupAddEvent.PerformLayout();
      this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.GroupBox groupAddEvent;
    private System.Windows.Forms.TextBox txtEventText;
    private System.Windows.Forms.Label lblText;
    private System.Windows.Forms.ComboBox comboEventType;
    private System.Windows.Forms.Label lblType;
    private System.Windows.Forms.Button btnAddEvent;
    private System.Windows.Forms.RadioButton radioCustomText;
    private System.Windows.Forms.RadioButton radioDefaultText;
    private System.Windows.Forms.Button btnAddAllEvents;
    private RtfLogView rtfLogView;
  }
}

// LoggingTest


text:
<!DOCTYPE html>

    <link href="assets/accessibility.liveRegionAttachment.css" rel="stylesheet" type="text/css" />


text:
class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :nick
  end
end


text:
'use strict';

/**
 * Controllers
 */

angular.module('myApp.controllers', [])
.controller('HomeCtrl', function($scope) {

});


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <winpr/crt.h>
#include <winpr/synch.h>
#include <winpr/print.h>
#include <winpr/stream.h>
#include <winpr/cmdline.h>
#include <winpr/collections.h>
#include <winpr/interlocked.h>
#include <winpr/sysinfo.h>

#include <freerdp/addin.h>
#include <freerdp/primitives.h>
#include <freerdp/client/geometry.h>
#include <freerdp/client/video.h>
#include <freerdp/channels/log.h>
#include <freerdp/codec/h264.h>
#include <freerdp/codec/yuv.h>

#define TAG CHANNELS_TAG("video")

#include "video_main.h"

struct _VIDEO_CHANNEL_CALLBACK
{
	IWTSVirtualChannelCallback iface;

	IWTSPlugin* plugin;
	IWTSVirtualChannelManager* channel_mgr;
	IWTSVirtualChannel* channel;
};
typedef struct _VIDEO_CHANNEL_CALLBACK VIDEO_CHANNEL_CALLBACK;

struct _VIDEO_LISTENER_CALLBACK
{
	IWTSListenerCallback iface;

	IWTSPlugin* plugin;
	IWTSVirtualChannelManager* channel_mgr;
	VIDEO_CHANNEL_CALLBACK* channel_callback;
};
typedef struct _VIDEO_LISTENER_CALLBACK VIDEO_LISTENER_CALLBACK;

struct _VIDEO_PLUGIN
{
	IWTSPlugin wtsPlugin;

	IWTSListener* controlListener;
	IWTSListener* dataListener;
	VIDEO_LISTENER_CALLBACK* control_callback;
	VIDEO_LISTENER_CALLBACK* data_callback;

	VideoClientContext *context;
};
typedef struct _VIDEO_PLUGIN VIDEO_PLUGIN;

#define XF_VIDEO_UNLIMITED_RATE 31

static const BYTE MFVideoFormat_H264[] = {'H', '2', '6', '4',
		0x00, 0x00,
		0x10, 0x00,
		0x80, 0x00,
		0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71};

typedef struct _PresentationContext PresentationContext;
typedef struct _VideoFrame VideoFrame;

/** @brief private data for the channel */
struct _VideoClientContextPriv
{
	VideoClientContext *video;
	GeometryClientContext *geometry;
	wQueue *frames;
	CRITICAL_SECTION framesLock;
	wBufferPool *surfacePool;
	UINT32 publishedFrames;
	UINT32 droppedFrames;
	UINT32 lastSentRate;
	UINT64 nextFeedbackTime;
	PresentationContext *currentPresentation;
};

/** @brief */
struct _VideoFrame
{
	UINT64 publishTime;
	UINT64 hnsDuration;
	MAPPED_GEOMETRY *geometry;
	UINT32 w, h;
	BYTE *surfaceData;
	PresentationContext *presentation;
};

/** @brief */
struct _PresentationContext
{
	VideoClientContext *video;
	BYTE PresentationId;
	UINT32 SourceWidth, SourceHeight;
	UINT32 ScaledWidth, ScaledHeight;
	MAPPED_GEOMETRY *geometry;

	UINT64 startTimeStamp;
	UINT64 publishOffset;
	H264_CONTEXT *h264;
	YUV_CONTEXT *yuv;
	wStream *currentSample;
	UINT64 lastPublishTime, nextPublishTime;
	volatile LONG refCounter;
	BYTE *surfaceData;
	VideoSurface *surface;
};

static const char *video_command_name(BYTE cmd)
{
	switch(cmd)
	{
	case TSMM_START_PRESENTATION:
		return "start";
	case TSMM_STOP_PRESENTATION:
		return "stop";
	default:
		return "<unknown>";
	}
}

static BOOL yuv_to_rgb(PresentationContext *presentation, BYTE *dest)
{
	const BYTE* pYUVPoint[3];
	H264_CONTEXT *h264 = presentation->h264;

	BYTE** ppYUVData;
	ppYUVData = h264->pYUVData;

	pYUVPoint[0] = ppYUVData[0];
	pYUVPoint[1] = ppYUVData[1];
	pYUVPoint[2] = ppYUVData[2];

	if (!yuv_context_decode(presentation->yuv, pYUVPoint, h264->iStride, PIXEL_FORMAT_BGRX32, dest, h264->width * 4))
	{
		WLog_ERR(TAG, "error in yuv_to_rgb conversion");
		return FALSE;
	}

	return TRUE;
}

static void video_client_context_set_geometry(VideoClientContext *video, GeometryClientContext *geometry)
{
	video->priv->geometry = geometry;
}

VideoClientContextPriv *VideoClientContextPriv_new(VideoClientContext *video)
{
	VideoClientContextPriv *ret = calloc(1, sizeof(*ret));
	if (!ret)
		return NULL;

	ret->frames = Queue_New(TRUE, 10, 2);
	if (!ret->frames)
	{
		WLog_ERR(TAG, "unable to allocate frames queue");
		goto error_frames;
	}

	ret->surfacePool = BufferPool_New(FALSE, 0, 16);
	if (!ret->surfacePool)
	{
		WLog_ERR(TAG, "unable to create surface pool");
		goto error_surfacePool;
	}

	if (!InitializeCriticalSectionAndSpinCount(&ret->framesLock, 4 * 1000))
	{
		WLog_ERR(TAG, "unable to initialize frames lock");
		goto error_spinlock;
	}

	ret->video = video;

	 /* don't set to unlimited so that we have the chance to send a feedback in
	  * the first second (for servers that want feedback directly)
	  */
	ret->lastSentRate = 30;
	return ret;

error_spinlock:
	BufferPool_Free(ret->surfacePool);
error_surfacePool:
	Queue_Free(ret->frames);
error_frames:
	free(ret);
	return NULL;
}

static PresentationContext *PresentationContext_new(VideoClientContext *video, BYTE PresentationId,
		UINT32 x, UINT32 y, UINT32 width, UINT32 height)
{
	VideoClientContextPriv *priv = video->priv;
	PresentationContext *ret = calloc(1, sizeof(*ret));
	if (!ret)
		return NULL;

	ret->video = video;
	ret->PresentationId = PresentationId;

	ret->h264 = h264_context_new(FALSE);
	if (!ret->h264)
	{
		WLog_ERR(TAG, "unable to create a h264 context");
		goto error_h264;
	}
	h264_context_reset(ret->h264, width, height);

	ret->currentSample = Stream_New(NULL, 4096);
	if (!ret->currentSample)
	{
		WLog_ERR(TAG, "unable to create current packet stream");
		goto error_currentSample;
	}

	ret->surfaceData = BufferPool_Take(priv->surfacePool, width * height * 4);
	if (!ret->surfaceData)
	{
		WLog_ERR(TAG, "unable to allocate surfaceData");
		goto error_surfaceData;
	}

	ret->surface = video->createSurface(video, ret->surfaceData, x, y, width, height);
	if (!ret->surface)
	{
		WLog_ERR(TAG, "unable to create surface");
		goto error_surface;
	}

	ret->yuv = yuv_context_new(FALSE);
	if (!ret->yuv)
	{
		WLog_ERR(TAG, "unable to create YUV decoder");
		goto error_yuv;
	}

	yuv_context_reset(ret->yuv, width, height);
	ret->refCounter = 1;
	return ret;

error_yuv:
	video->deleteSurface(video, ret->surface);
error_surface:
	BufferPool_Return(priv->surfacePool, ret->surfaceData);
error_surfaceData:
	Stream_Free(ret->currentSample, TRUE);
error_currentSample:
	h264_context_free(ret->h264);
error_h264:
	free(ret);
	return NULL;
}

static void PresentationContext_unref(PresentationContext *presentation)
{
	VideoClientContextPriv *priv;
	MAPPED_GEOMETRY *geometry;

	if (!presentation)
		return;

	if (InterlockedDecrement(&presentation->refCounter) != 0)
		return;

	geometry = presentation->geometry;
	if (geometry)
	{
		geometry->MappedGeometryUpdate = NULL;
		geometry->MappedGeometryClear = NULL;
		geometry->custom = NULL;
		mappedGeometryUnref(geometry);
	}

	priv = presentation->video->priv;

	h264_context_free(presentation->h264);
	Stream_Free(presentation->currentSample, TRUE);
	presentation->video->deleteSurface(presentation->video, presentation->surface);
	BufferPool_Return(priv->surfacePool, presentation->surfaceData);
	yuv_context_free(presentation->yuv);
	free(presentation);
}

static void VideoFrame_free(VideoFrame **pframe)
{
	VideoFrame *frame = *pframe;

	mappedGeometryUnref(frame->geometry);
	BufferPool_Return(frame->presentation->video->priv->surfacePool, frame->surfaceData);
	PresentationContext_unref(frame->presentation);
	free(frame);
	*pframe = NULL;
}

static void VideoClientContextPriv_free(VideoClientContextPriv *priv)
{
	EnterCriticalSection(&priv->framesLock);
	while (Queue_Count(priv->frames))
	{
		VideoFrame *frame = Queue_Dequeue(priv->frames);
		if (frame)
			VideoFrame_free(&frame);
	}

	Queue_Free(priv->frames);
	LeaveCriticalSection(&priv->framesLock);

	DeleteCriticalSection(&priv->framesLock);

	if (priv->currentPresentation)
		PresentationContext_unref(priv->currentPresentation);

	BufferPool_Free(priv->surfacePool);
	free(priv);
}

static UINT video_control_send_presentation_response(VideoClientContext *context, TSMM_PRESENTATION_RESPONSE *resp)
{
	BYTE buf[12];
	wStream *s;
	VIDEO_PLUGIN* video = (VIDEO_PLUGIN *)context->handle;
	IWTSVirtualChannel* channel;
	UINT ret;

	s = Stream_New(buf, 12);
	if (!s)
		return CHANNEL_RC_NO_MEMORY;

	Stream_Write_UINT32(s, 12); /* cbSize */
	Stream_Write_UINT32(s, TSMM_PACKET_TYPE_PRESENTATION_RESPONSE); /* PacketType */
	Stream_Write_UINT8(s, resp->PresentationId);
	Stream_Zero(s, 3);
	Stream_SealLength(s);

	channel = video->control_callback->channel_callback->channel;
	ret = channel->Write(channel, 12, buf, NULL);
	Stream_Free(s, FALSE);

	return ret;
}

static BOOL video_onMappedGeometryUpdate(MAPPED_GEOMETRY *geometry)
{
	PresentationContext *presentation = (PresentationContext *)geometry->custom;
	RDP_RECT *r = &geometry->geometry.boundingRect;
	WLog_DBG(TAG, "geometry updated topGeom=(%d,%d-%dx%d) geom=(%d,%d-%dx%d) rects=(%d,%d-%dx%d)",
			geometry->topLevelLeft, geometry->topLevelTop,
			geometry->topLevelRight - geometry->topLevelLeft, geometry->topLevelBottom - geometry->topLevelTop,

			geometry->left, geometry->top,
			geometry->right - geometry->left, geometry->bottom - geometry->top,

			r->x, r->y, r->width, r->height
	);

	presentation->surface->x = geometry->topLevelLeft + geometry->left;
	presentation->surface->y = geometry->topLevelTop + geometry->top;

	return TRUE;
}

static BOOL video_onMappedGeometryClear(MAPPED_GEOMETRY *geometry)
{
	PresentationContext *presentation = (PresentationContext *)geometry->custom;

	mappedGeometryUnref(presentation->geometry);
	presentation->geometry = NULL;
	return TRUE;
}

static UINT video_PresentationRequest(VideoClientContext* video, TSMM_PRESENTATION_REQUEST *req)
{
	VideoClientContextPriv *priv = video->priv;
	PresentationContext *presentation;
	UINT ret = CHANNEL_RC_OK;

	presentation = priv->currentPresentation;

	if (req->Command == TSMM_START_PRESENTATION)
	{
		MAPPED_GEOMETRY *geom;
		TSMM_PRESENTATION_RESPONSE resp;

		if (memcmp(req->VideoSubtypeId, MFVideoFormat_H264, 16) != 0)
		{
			WLog_ERR(TAG, "not a H264 video, ignoring request");
			return CHANNEL_RC_OK;
		}

		if (presentation)
		{
			if (presentation->PresentationId == req->PresentationId)
			{
				WLog_ERR(TAG, "ignoring start request for existing presentation %d", req->PresentationId);
				return CHANNEL_RC_OK;
			}

			WLog_ERR(TAG, "releasing current presentation %d", req->PresentationId);
			PresentationContext_unref(presentation);
			presentation = priv->currentPresentation = NULL;
		}

		if (!priv->geometry)
		{
			WLog_ERR(TAG, "geometry channel not ready, ignoring request");
			return CHANNEL_RC_OK;
		}

		geom = HashTable_GetItemValue(priv->geometry->geometries, &(req->GeometryMappingId));
		if (!geom)
		{
			WLog_ERR(TAG, "geometry mapping 0x%"PRIx64" not registered", req->GeometryMappingId);
			return CHANNEL_RC_OK;
		}

		WLog_DBG(TAG, "creating presentation 0x%x", req->PresentationId);
		presentation = PresentationContext_new(video, req->PresentationId,
				geom->topLevelLeft + geom->left,
				geom->topLevelTop + geom->top,
				req->SourceWidth, req->SourceHeight);
		if (!presentation)
		{
			WLog_ERR(TAG, "unable to create presentation video");
			return CHANNEL_RC_NO_MEMORY;
		}

		mappedGeometryRef(geom);
		presentation->geometry = geom;

		priv->currentPresentation = presentation;
		presentation->video = video;
		presentation->SourceWidth = req->SourceWidth;
		presentation->SourceHeight = req->SourceHeight;
		presentation->ScaledWidth = req->ScaledWidth;
		presentation->ScaledHeight = req->ScaledHeight;

		geom->custom = presentation;
		geom->MappedGeometryUpdate = video_onMappedGeometryUpdate;
		geom->MappedGeometryClear = video_onMappedGeometryClear;

		/* send back response */
		resp.PresentationId = req->PresentationId;
		ret = video_control_send_presentation_response(video, &resp);
	}
	else if (req->Command == TSMM_STOP_PRESENTATION)
	{
		WLog_DBG(TAG, "stopping presentation 0x%x", req->PresentationId);
		if (!presentation)
		{
			WLog_ERR(TAG, "unknown presentation to stop %d", req->PresentationId);
			return CHANNEL_RC_OK;
		}

		priv->currentPresentation = NULL;
		priv->droppedFrames = 0;
		priv->publishedFrames = 0;
		PresentationContext_unref(presentation);
	}

	return CHANNEL_RC_OK;
}

static UINT video_read_tsmm_presentation_req(VideoClientContext *context, wStream *s)
{
	TSMM_PRESENTATION_REQUEST req;

	if (Stream_GetRemainingLength(s) < 60)
	{
		WLog_ERR(TAG, "not enough bytes for a TSMM_PRESENTATION_REQUEST");
		return ERROR_INVALID_DATA;
	}

	Stream_Read_UINT8(s, req.PresentationId);
	Stream_Read_UINT8(s, req.Version);
	Stream_Read_UINT8(s, req.Command);
	Stream_Read_UINT8(s, req.FrameRate); /* FrameRate - reserved and ignored */

	Stream_Seek_UINT16(s); /* AverageBitrateKbps reserved and ignored */
	Stream_Seek_UINT16(s); /* reserved */

	Stream_Read_UINT32(s, req.SourceWidth);
	Stream_Read_UINT32(s, req.SourceHeight);
	Stream_Read_UINT32(s, req.ScaledWidth);
	Stream_Read_UINT32(s, req.ScaledHeight);
	Stream_Read_UINT64(s, req.hnsTimestampOffset);
	Stream_Read_UINT64(s, req.GeometryMappingId);
	Stream_Read(s, req.VideoSubtypeId, 16);

	Stream_Read_UINT32(s, req.cbExtra);

	if (Stream_GetRemainingLength(s) < req.cbExtra)
	{
		WLog_ERR(TAG, "not enough bytes for cbExtra of TSMM_PRESENTATION_REQUEST");
		return ERROR_INVALID_DATA;
	}

	req.pExtraData = Stream_Pointer(s);

	WLog_DBG(TAG, "presentationReq: id:%"PRIu8" version:%"PRIu8" command:%s srcWidth/srcHeight=%"PRIu32"x%"PRIu32
			" scaled Width/Height=%"PRIu32"x%"PRIu32" timestamp=%"PRIu64" mappingId=%"PRIx64"",
			req.PresentationId, req.Version, video_command_name(req.Command),
			req.SourceWidth, req.SourceHeight, req.ScaledWidth, req.ScaledHeight,
			req.hnsTimestampOffset, req.GeometryMappingId);

	return video_PresentationRequest(context, &req);
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT video_control_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream *s)
{
	VIDEO_CHANNEL_CALLBACK* callback = (VIDEO_CHANNEL_CALLBACK*) pChannelCallback;
	VIDEO_PLUGIN* video;
	VideoClientContext *context;
	UINT ret = CHANNEL_RC_OK;
	UINT32 cbSize, packetType;

	video = (VIDEO_PLUGIN*) callback->plugin;
	context = (VideoClientContext *)video->wtsPlugin.pInterface;

	if (Stream_GetRemainingLength(s) < 4)
		return ERROR_INVALID_DATA;

	Stream_Read_UINT32(s, cbSize);
	if (cbSize < 8 || Stream_GetRemainingLength(s) < (cbSize-4))
	{
		WLog_ERR(TAG, "invalid cbSize");
		return ERROR_INVALID_DATA;
	}

	Stream_Read_UINT32(s, packetType);
	switch (packetType)
	{
	case TSMM_PACKET_TYPE_PRESENTATION_REQUEST:
		ret = video_read_tsmm_presentation_req(context, s);
		break;
	default:
		WLog_ERR(TAG, "not expecting packet type %"PRIu32"", packetType);
		ret = ERROR_UNSUPPORTED_TYPE;
		break;
	}

	return ret;
}

static UINT video_control_send_client_notification(VideoClientContext *context, TSMM_CLIENT_NOTIFICATION *notif)
{
	BYTE buf[100];
	wStream *s;
	VIDEO_PLUGIN* video = (VIDEO_PLUGIN *)context->handle;
	IWTSVirtualChannel* channel;
	UINT ret;
	UINT32 cbSize;

	s = Stream_New(buf, 30);
	if (!s)
		return CHANNEL_RC_NO_MEMORY;

	cbSize = 16;
	Stream_Seek_UINT32(s); /* cbSize */
	Stream_Write_UINT32(s, TSMM_PACKET_TYPE_CLIENT_NOTIFICATION); /* PacketType */
	Stream_Write_UINT8(s, notif->PresentationId);
	Stream_Write_UINT8(s, notif->NotificationType);
	Stream_Zero(s, 2);
	if (notif->NotificationType == TSMM_CLIENT_NOTIFICATION_TYPE_FRAMERATE_OVERRIDE)
	{
		Stream_Write_UINT32(s, 16); /* cbData */

		/* TSMM_CLIENT_NOTIFICATION_FRAMERATE_OVERRIDE */
		Stream_Write_UINT32(s, notif->FramerateOverride.Flags);
		Stream_Write_UINT32(s, notif->FramerateOverride.DesiredFrameRate);
		Stream_Zero(s, 4 * 2);

		cbSize += 4 * 4;
	}
	else
	{
		Stream_Write_UINT32(s, 0); /* cbData */
	}

	Stream_SealLength(s);
	Stream_SetPosition(s, 0);
	Stream_Write_UINT32(s, cbSize);
	Stream_Free(s, FALSE);

	channel = video->control_callback->channel_callback->channel;
	ret = channel->Write(channel, cbSize, buf, NULL);

	return ret;
}

static void video_timer(VideoClientContext *video, UINT64 now)
{
	PresentationContext *presentation;
	VideoClientContextPriv *priv = video->priv;
	VideoFrame *peekFrame, *frame = NULL;

	EnterCriticalSection(&priv->framesLock);
	do
	{
		peekFrame = (VideoFrame *)Queue_Peek(priv->frames);
		if (!peekFrame)
			break;

		if (peekFrame->publishTime > now)
			break;

		if (frame)
		{
			WLog_DBG(TAG, "dropping frame @%"PRIu64, frame->publishTime);
			priv->droppedFrames++;
			VideoFrame_free(&frame);
		}
		frame = peekFrame;
		Queue_Dequeue(priv->frames);
	}
	while (1);
	LeaveCriticalSection(&priv->framesLock);

	if (!frame)
		goto treat_feedback;

	presentation = frame->presentation;

	priv->publishedFrames++;
	memcpy(presentation->surfaceData, frame->surfaceData, frame->w * frame->h * 4);

	video->showSurface(video, presentation->surface);

	VideoFrame_free(&frame);

treat_feedback:
	if (priv->nextFeedbackTime < now)
	{
		/* we can compute some feedback only if we have some published frames and
		 * a current presentation
		 */
		if (priv->publishedFrames && priv->currentPresentation)
		{
			UINT32 computedRate;

			InterlockedIncrement(&priv->currentPresentation->refCounter);

			if (priv->droppedFrames)
			{
				/**
				 * some dropped frames, looks like we're asking too many frames per seconds,
				 * try lowering rate. We go directly from unlimited rate to 24 frames/seconds
				 * otherwise we lower rate by 2 frames by seconds
				 */
				if (priv->lastSentRate == XF_VIDEO_UNLIMITED_RATE)
					computedRate = 24;
				else
				{
					computedRate = priv->lastSentRate - 2;
					if (!computedRate)
						computedRate = 2;
				}
			}
			else
			{
				/**
				 * we treat all frames ok, so either ask the server to send more,
				 * or stay unlimited
			 */
				if (priv->lastSentRate == XF_VIDEO_UNLIMITED_RATE)
					computedRate = XF_VIDEO_UNLIMITED_RATE; /* stay unlimited */
				else
				{
					computedRate = priv->lastSentRate + 2;
					if (computedRate > XF_VIDEO_UNLIMITED_RATE)
						computedRate = XF_VIDEO_UNLIMITED_RATE;
				}
			}

			if (computedRate != priv->lastSentRate)
			{
				TSMM_CLIENT_NOTIFICATION notif;
				notif.PresentationId = priv->currentPresentation->PresentationId;
				notif.NotificationType = TSMM_CLIENT_NOTIFICATION_TYPE_FRAMERATE_OVERRIDE;
				if (computedRate == XF_VIDEO_UNLIMITED_RATE)
				{
					notif.FramerateOverride.Flags = 0x01;
					notif.FramerateOverride.DesiredFrameRate = 0x00;
				}
				else
				{
					notif.FramerateOverride.Flags = 0x02;
					notif.FramerateOverride.DesiredFrameRate = computedRate;
				}

				video_control_send_client_notification(video, &notif);
				priv->lastSentRate = computedRate;

				WLog_DBG(TAG, "server notified with rate %d published=%d dropped=%d", priv->lastSentRate,
						priv->publishedFrames, priv->droppedFrames);
			}

			PresentationContext_unref(priv->currentPresentation);
		}

		WLog_DBG(TAG, "currentRate=%d published=%d dropped=%d", priv->lastSentRate,
				priv->publishedFrames, priv->droppedFrames);

		priv->droppedFrames = 0;
		priv->publishedFrames = 0;
		priv->nextFeedbackTime = now + 1000;
	}
}

static UINT video_VideoData(VideoClientContext* context, TSMM_VIDEO_DATA *data)
{
	VideoClientContextPriv *priv = context->priv;
	PresentationContext *presentation;
	int status;

	presentation = priv->currentPresentation;
	if (!presentation)
	{
		WLog_ERR(TAG, "no current presentation");
		return CHANNEL_RC_OK;
	}

	if (presentation->PresentationId != data->PresentationId)
	{
		WLog_ERR(TAG, "current presentation id=%d doesn't match data id=%d", presentation->PresentationId,
				data->PresentationId);
		return CHANNEL_RC_OK;
	}

	if (!Stream_EnsureRemainingCapacity(presentation->currentSample, data->cbSample))
	{
		WLog_ERR(TAG, "unable to expand the current packet");
		return CHANNEL_RC_NO_MEMORY;
	}

	Stream_Write(presentation->currentSample, data->pSample, data->cbSample);

	if (data->CurrentPacketIndex == data->PacketsInSample)
	{
		H264_CONTEXT *h264 = presentation->h264;
		UINT64 startTime = GetTickCount64(), timeAfterH264;
		MAPPED_GEOMETRY *geom = presentation->geometry;

		Stream_SealLength(presentation->currentSample);
		Stream_SetPosition(presentation->currentSample, 0);

		status = h264->subsystem->Decompress(h264, Stream_Pointer(presentation->currentSample),
				Stream_Length(presentation->currentSample));
		if (status == 0)
			return CHANNEL_RC_OK;

		if (status < 0)
			return CHANNEL_RC_OK;

		timeAfterH264 = GetTickCount64();
		if (data->SampleNumber == 1)
		{
			presentation->lastPublishTime = startTime;
		}

		presentation->lastPublishTime += (data->hnsDuration / 10000);
		if (presentation->lastPublishTime <= timeAfterH264 + 10)
		{
			int dropped = 0;

			/* if the frame is to be published in less than 10 ms, let's consider it's now */
			yuv_to_rgb(presentation, presentation->surfaceData);

			context->showSurface(context, presentation->surface);

			priv->publishedFrames++;

			/* cleanup previously scheduled frames */
			EnterCriticalSection(&priv->framesLock);
			while (Queue_Count(priv->frames) > 0)
			{
				VideoFrame *frame = Queue_Dequeue(priv->frames);
				if (frame)
				{
					priv->droppedFrames++;
					VideoFrame_free(&frame);
					dropped++;
				}
			}
			LeaveCriticalSection(&priv->framesLock);

			if (dropped)
				WLog_DBG(TAG, "showing frame (%d dropped)", dropped);
		}
		else
		{
			BOOL enqueueResult;
			VideoFrame *frame = calloc(1, sizeof(*frame));
			if (!frame)
			{
				WLog_ERR(TAG, "unable to create frame");
				return CHANNEL_RC_NO_MEMORY;
			}
			mappedGeometryRef(geom);

			frame->presentation = presentation;
			frame->publishTime = presentation->lastPublishTime;
			frame->geometry = geom;
			frame->w = presentation->SourceWidth;
			frame->h = presentation->SourceHeight;

			frame->surfaceData = BufferPool_Take(priv->surfacePool, frame->w * frame->h * 4);
			if (!frame->surfaceData)
			{
				WLog_ERR(TAG, "unable to allocate frame data");
				mappedGeometryUnref(geom);
				free(frame);
				return CHANNEL_RC_NO_MEMORY;
			}

			if (!yuv_to_rgb(presentation, frame->surfaceData))
			{
				WLog_ERR(TAG, "error during YUV->RGB conversion");
				BufferPool_Return(priv->surfacePool, frame->surfaceData);
				mappedGeometryUnref(geom);
				free(frame);
				return CHANNEL_RC_NO_MEMORY;
			}

			InterlockedIncrement(&presentation->refCounter);

			EnterCriticalSection(&priv->framesLock);
			enqueueResult = Queue_Enqueue(priv->frames, frame);
			LeaveCriticalSection(&priv->framesLock);

			if (!enqueueResult)
			{
				WLog_ERR(TAG, "unable to enqueue frame");
				VideoFrame_free(&frame);
				return CHANNEL_RC_NO_MEMORY;
			}

			WLog_DBG(TAG, "scheduling frame in %"PRIu32" ms", (frame->publishTime-startTime));
		}
	}

	return CHANNEL_RC_OK;
}

static UINT video_data_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream *s)
{
	VIDEO_CHANNEL_CALLBACK* callback = (VIDEO_CHANNEL_CALLBACK*) pChannelCallback;
	VIDEO_PLUGIN* video;
	VideoClientContext *context;
	UINT32 cbSize, packetType;
	TSMM_VIDEO_DATA data;

	video = (VIDEO_PLUGIN*) callback->plugin;
	context = (VideoClientContext *)video->wtsPlugin.pInterface;

	if (Stream_GetRemainingLength(s) < 4)
		return ERROR_INVALID_DATA;

	Stream_Read_UINT32(s, cbSize);
	if (cbSize < 8 || Stream_GetRemainingLength(s) < (cbSize-4))
	{
		WLog_ERR(TAG, "invalid cbSize");
		return ERROR_INVALID_DATA;
	}

	Stream_Read_UINT32(s, packetType);
	if (packetType != TSMM_PACKET_TYPE_VIDEO_DATA)
	{
		WLog_ERR(TAG, "only expecting VIDEO_DATA on the data channel");
		return ERROR_INVALID_DATA;
	}

	if (Stream_GetRemainingLength(s) < 32)
	{
		WLog_ERR(TAG, "not enough bytes for a TSMM_VIDEO_DATA");
		return ERROR_INVALID_DATA;
	}

	Stream_Read_UINT8(s, data.PresentationId);
	Stream_Read_UINT8(s, data.Version);
	Stream_Read_UINT8(s, data.Flags);
	Stream_Seek_UINT8(s); /* reserved */
	Stream_Read_UINT64(s, data.hnsTimestamp);
	Stream_Read_UINT64(s, data.hnsDuration);
	Stream_Read_UINT16(s, data.CurrentPacketIndex);
	Stream_Read_UINT16(s, data.PacketsInSample);
	Stream_Read_UINT32(s, data.SampleNumber);
	Stream_Read_UINT32(s, data.cbSample);
	data.pSample = Stream_Pointer(s);

/*
	WLog_DBG(TAG, "videoData: id:%"PRIu8" version:%"PRIu8" flags:0x%"PRIx8" timestamp=%"PRIu64" duration=%"PRIu64
			" curPacketIndex:%"PRIu16" packetInSample:%"PRIu16" sampleNumber:%"PRIu32" cbSample:%"PRIu32"",
			data.PresentationId, data.Version, data.Flags, data.hnsTimestamp, data.hnsDuration,
			data.CurrentPacketIndex, data.PacketsInSample, data.SampleNumber, data.cbSample);
*/

	return video_VideoData(context, &data);
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT video_control_on_close(IWTSVirtualChannelCallback* pChannelCallback)
{
	free(pChannelCallback);
	return CHANNEL_RC_OK;
}

static UINT video_data_on_close(IWTSVirtualChannelCallback* pChannelCallback)
{
	free(pChannelCallback);
	return CHANNEL_RC_OK;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT video_control_on_new_channel_connection(IWTSListenerCallback* listenerCallback,
	IWTSVirtualChannel* channel, BYTE* Data, BOOL* pbAccept,
	IWTSVirtualChannelCallback** ppCallback)
{
	VIDEO_CHANNEL_CALLBACK* callback;
	VIDEO_LISTENER_CALLBACK* listener_callback = (VIDEO_LISTENER_CALLBACK*) listenerCallback;

	callback = (VIDEO_CHANNEL_CALLBACK*) calloc(1, sizeof(VIDEO_CHANNEL_CALLBACK));
	if (!callback)
	{
		WLog_ERR(TAG, "calloc failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	callback->iface.OnDataReceived = video_control_on_data_received;
	callback->iface.OnClose = video_control_on_close;
	callback->plugin = listener_callback->plugin;
	callback->channel_mgr = listener_callback->channel_mgr;
	callback->channel = channel;
	listener_callback->channel_callback = callback;

	*ppCallback = (IWTSVirtualChannelCallback*) callback;

	return CHANNEL_RC_OK;
}

static UINT video_data_on_new_channel_connection(IWTSListenerCallback* pListenerCallback,
	IWTSVirtualChannel* pChannel, BYTE* Data, BOOL* pbAccept,
	IWTSVirtualChannelCallback** ppCallback)
{
	VIDEO_CHANNEL_CALLBACK* callback;
	VIDEO_LISTENER_CALLBACK* listener_callback = (VIDEO_LISTENER_CALLBACK*) pListenerCallback;

	callback = (VIDEO_CHANNEL_CALLBACK*) calloc(1, sizeof(VIDEO_CHANNEL_CALLBACK));
	if (!callback)
	{
		WLog_ERR(TAG, "calloc failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	callback->iface.OnDataReceived = video_data_on_data_received;
	callback->iface.OnClose = video_data_on_close;
	callback->plugin = listener_callback->plugin;
	callback->channel_mgr = listener_callback->channel_mgr;
	callback->channel = pChannel;
	listener_callback->channel_callback = callback;

	*ppCallback = (IWTSVirtualChannelCallback*) callback;

	return CHANNEL_RC_OK;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT video_plugin_initialize(IWTSPlugin* plugin, IWTSVirtualChannelManager* channelMgr)
{
	UINT status;
	VIDEO_PLUGIN* video = (VIDEO_PLUGIN *)plugin;
	VIDEO_LISTENER_CALLBACK *callback;

	video->control_callback = callback = (VIDEO_LISTENER_CALLBACK*) calloc(1, sizeof(VIDEO_LISTENER_CALLBACK));
	if (!callback)
	{
		WLog_ERR(TAG, "calloc for control callback failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	callback->iface.OnNewChannelConnection = video_control_on_new_channel_connection;
	callback->plugin = plugin;
	callback->channel_mgr = channelMgr;

	status = channelMgr->CreateListener(channelMgr, VIDEO_CONTROL_DVC_CHANNEL_NAME, 0,
		(IWTSListenerCallback*)callback, &(video->controlListener));

	if (status != CHANNEL_RC_OK)
		return status;
	video->controlListener->pInterface = video->wtsPlugin.pInterface;

	video->data_callback = callback = (VIDEO_LISTENER_CALLBACK*) calloc(1, sizeof(VIDEO_LISTENER_CALLBACK));
	if (!callback)
	{
		WLog_ERR(TAG, "calloc for data callback failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	callback->iface.OnNewChannelConnection = video_data_on_new_channel_connection;
	callback->plugin = plugin;
	callback->channel_mgr = channelMgr;

	status = channelMgr->CreateListener(channelMgr, VIDEO_DATA_DVC_CHANNEL_NAME, 0,
		(IWTSListenerCallback*)callback, &(video->dataListener));

	if (status == CHANNEL_RC_OK)
		video->dataListener->pInterface = video->wtsPlugin.pInterface;

	return status;
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT video_plugin_terminated(IWTSPlugin* pPlugin)
{
	VIDEO_PLUGIN* video = (VIDEO_PLUGIN*) pPlugin;

	if (video->context)
		VideoClientContextPriv_free(video->context->priv);

	free(video->control_callback);
	free(video->data_callback);
	free(video->wtsPlugin.pInterface);
	free(pPlugin);
	return CHANNEL_RC_OK;
}

/**
 * Channel Client Interface
 */

#ifdef BUILTIN_CHANNELS
#define DVCPluginEntry		video_DVCPluginEntry
#else
#define DVCPluginEntry		FREERDP_API DVCPluginEntry
#endif

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
UINT DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints)
{
	UINT error = CHANNEL_RC_OK;
	VIDEO_PLUGIN* videoPlugin;
	VideoClientContext* videoContext;
	VideoClientContextPriv *priv;

	videoPlugin = (VIDEO_PLUGIN*) pEntryPoints->GetPlugin(pEntryPoints, "video");
	if (!videoPlugin)
	{
		videoPlugin = (VIDEO_PLUGIN*) calloc(1, sizeof(VIDEO_PLUGIN));
		if (!videoPlugin)
		{
			WLog_ERR(TAG, "calloc failed!");
			return CHANNEL_RC_NO_MEMORY;
		}

		videoPlugin->wtsPlugin.Initialize = video_plugin_initialize;
		videoPlugin->wtsPlugin.Connected = NULL;
		videoPlugin->wtsPlugin.Disconnected = NULL;
		videoPlugin->wtsPlugin.Terminated = video_plugin_terminated;

		videoContext = (VideoClientContext*) calloc(1, sizeof(VideoClientContext));
		if (!videoContext)
		{
			WLog_ERR(TAG, "calloc failed!");
			free(videoPlugin);
			return CHANNEL_RC_NO_MEMORY;
		}

		priv = VideoClientContextPriv_new(videoContext);
		if (!priv)
		{
			WLog_ERR(TAG, "VideoClientContextPriv_new failed!");
			free(videoContext);
			free(videoPlugin);
			return CHANNEL_RC_NO_MEMORY;
		}

		videoContext->handle = (void*) videoPlugin;
		videoContext->priv = priv;
		videoContext->timer = video_timer;
		videoContext->setGeometry = video_client_context_set_geometry;

		videoPlugin->wtsPlugin.pInterface = (void*) videoContext;
		videoPlugin->context = videoContext;

		error = pEntryPoints->RegisterPlugin(pEntryPoints, "video", (IWTSPlugin*) videoPlugin);
	}
	else
	{
		WLog_ERR(TAG, "could not get video Plugin.");
		return CHANNEL_RC_BAD_CHANNEL;
	}

	return error;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lichen flavidus Ehrh.

### Remarks
null


text:
namespace kaldi {

class CovarianceStats {
 public:
  CovarianceStats(int32 dim)
      : tot_covar_(dim), between_covar_(dim), num_spk_(0), num_utt_(0) {}

  /// get total covariance, normalized per number of frames.
  void GetTotalCovar(SpMatrix<double> *tot_covar) const {
    KALDI_ASSERT(num_utt_ > 0);
    *tot_covar = tot_covar_;
    tot_covar->Scale(1.0 / num_utt_);
  }
  void GetWithinCovar(SpMatrix<double> *within_covar) {
    KALDI_ASSERT(num_utt_ - num_spk_ > 0);
    *within_covar = tot_covar_;
    within_covar->AddSp(-1.0, between_covar_);
    within_covar->Scale(1.0 / num_utt_);
  }
  void AccStats(const Matrix<double> &utts_of_this_spk) {
    int32 num_utts = utts_of_this_spk.NumRows();
    tot_covar_.AddMat2(1.0, utts_of_this_spk, kTrans, 1.0);
    Vector<double> spk_average(Dim());
    spk_average.AddRowSumMat(1.0 / num_utts, utts_of_this_spk);
    between_covar_.AddVec2(num_utts, spk_average);
    num_utt_ += num_utts;
    num_spk_ += 1;
  }
  /// Will return Empty() if the within-class covariance matrix would be zero.
  bool SingularTotCovar() { return (num_utt_ < Dim()); }
  bool Empty() { return (num_utt_ - num_spk_ == 0); }
  std::string Info() {
    std::ostringstream ostr;
    ostr << num_spk_ << " speakers, " << num_utt_ << " utterances. ";
    return ostr.str();
  }
  int32 Dim() { return tot_covar_.NumRows(); }
  // Use default constructor and assignment operator.
  void AddStats(const CovarianceStats &other) {
    tot_covar_.AddSp(1.0, other.tot_covar_);
    between_covar_.AddSp(1.0, other.between_covar_);
    num_spk_ += other.num_spk_;
    num_utt_ += other.num_utt_;
  }

 private:
  KALDI_DISALLOW_COPY_AND_ASSIGN(CovarianceStats);
  SpMatrix<double> tot_covar_;
  SpMatrix<double> between_covar_;
  int32 num_spk_;
  int32 num_utt_;
};

template <class Real>
void ComputeNormalizingTransform(const SpMatrix<Real> &covar,
                                 MatrixBase<Real> *proj) {
  int32 dim = covar.NumRows();
  TpMatrix<Real> C(dim);  // Cholesky of covar, covar = C C^T
  C.Cholesky(covar);
  C.Invert();  // The matrix that makes covar unit is C^{-1}, because
               // C^{-1} covar C^{-T} = C^{-1} C C^T C^{-T} = I.
  proj->CopyFromTp(C, kNoTrans);  // set "proj" to C^{-1}.
}

void ComputeLdaTransform(
    const std::map<std::string, Vector<BaseFloat> *> &utt2ivector,
    const std::map<std::string, std::vector<std::string> > &spk2utt,
    BaseFloat total_covariance_factor, MatrixBase<BaseFloat> *lda_out) {
  KALDI_ASSERT(!utt2ivector.empty());
  int32 lda_dim = lda_out->NumRows(), dim = lda_out->NumCols();
  KALDI_ASSERT(dim == utt2ivector.begin()->second->Dim());
  KALDI_ASSERT(lda_dim > 0 && lda_dim <= dim);

  CovarianceStats stats(dim);

  std::map<std::string, std::vector<std::string> >::const_iterator iter;
  for (iter = spk2utt.begin(); iter != spk2utt.end(); ++iter) {
    const std::vector<std::string> &uttlist = iter->second;
    KALDI_ASSERT(!uttlist.empty());

    int32 N = uttlist.size();  // number of utterances.
    Matrix<double> utts_of_this_spk(N, dim);
    for (int32 n = 0; n < N; n++) {
      std::string utt = uttlist[n];
      KALDI_ASSERT(utt2ivector.count(utt) != 0);
      utts_of_this_spk.Row(n).CopyFromVec(*(utt2ivector.find(utt)->second));
    }
    stats.AccStats(utts_of_this_spk);
  }

  KALDI_LOG << "Stats have " << stats.Info();
  KALDI_ASSERT(!stats.Empty());
  KALDI_ASSERT(!stats.SingularTotCovar() &&
               "Too little data for iVector dimension.");

  SpMatrix<double> total_covar;
  stats.GetTotalCovar(&total_covar);
  SpMatrix<double> within_covar;
  stats.GetWithinCovar(&within_covar);

  SpMatrix<double> mat_to_normalize(dim);
  mat_to_normalize.AddSp(total_covariance_factor, total_covar);
  mat_to_normalize.AddSp(1.0 - total_covariance_factor, within_covar);

  Matrix<double> T(dim, dim);
  ComputeNormalizingTransform(mat_to_normalize, &T);

  SpMatrix<double> between_covar(total_covar);
  between_covar.AddSp(-1.0, within_covar);

  SpMatrix<double> between_covar_proj(dim);
  between_covar_proj.AddMat2Sp(1.0, T, kNoTrans, between_covar, 0.0);

  Matrix<double> U(dim, dim);
  Vector<double> s(dim);
  between_covar_proj.Eig(&s, &U);
  bool sort_on_absolute_value = false;  // any negative ones will go last (they
                                        // shouldn't exist anyway so doesn't
                                        // really matter)
  SortSvd(&s, &U, static_cast<Matrix<double> *>(NULL), sort_on_absolute_value);

  KALDI_LOG << "Singular values of between-class covariance after projecting "
            << "with interpolated [total/within] covariance with a weight of "
            << total_covariance_factor
            << " on the total covariance, are: " << s;

  // U^T is the transform that will diagonalize the between-class covariance.
  // U_part is just the part of U that corresponds to the kept dimensions.
  SubMatrix<double> U_part(U, 0, dim, 0, lda_dim);

  // We first transform by T and then by U_part^T.  This means T
  // goes on the right.
  Matrix<double> temp(lda_dim, dim);
  temp.AddMatMat(1.0, U_part, kTrans, T, kNoTrans, 0.0);
  lda_out->CopyFromMat(temp);
}

void ComputeAndSubtractMean(
    std::map<std::string, Vector<BaseFloat> *> utt2ivector,
    Vector<BaseFloat> *mean_out) {
  int32 dim = utt2ivector.begin()->second->Dim();
  size_t num_ivectors = utt2ivector.size();
  Vector<double> mean(dim);
  std::map<std::string, Vector<BaseFloat> *>::iterator iter;
  for (iter = utt2ivector.begin(); iter != utt2ivector.end(); ++iter)
    mean.AddVec(1.0 / num_ivectors, *(iter->second));
  mean_out->Resize(dim);
  mean_out->CopyFromVec(mean);
  for (iter = utt2ivector.begin(); iter != utt2ivector.end(); ++iter)
    iter->second->AddVec(-1.0, *mean_out);
}
}

int main(int argc, char *argv[]) {
  using namespace kaldi;
  typedef kaldi::int32 int32;
  try {
    const char *usage =
        "Compute an LDA matrix for iVector system.  Reads in iVectors per "
        "utterance,\n"
        "and an utt2spk file which it uses to help work out the within-speaker "
        "and\n"
        "between-speaker covariance matrices.  Outputs an LDA projection to a\n"
        "specified dimension.  By default it will normalize so that the "
        "projected\n"
        "within-class covariance is unit, but if you set "
        "--normalize-total-covariance\n"
        "to true, it will normalize the total covariance.\n"
        "Note: the transform we produce is actually an affine transform which "
        "will\n"
        "also set the global mean to zero.\n"
        "\n"
        "Usage:  ivector-compute-lda [options] <ivector-rspecifier> "
        "<utt2spk-rspecifier> "
        "<lda-matrix-out>\n"
        "e.g.: \n"
        " ivector-compute-lda ark:ivectors.ark ark:utt2spk lda.mat\n";

    ParseOptions po(usage);

    int32 lda_dim = 100;  // Dimension we reduce to
    BaseFloat total_covariance_factor = 0.0;
    bool binary = true;

    po.Register("dim", &lda_dim, "Dimension we keep with the LDA transform");
    po.Register(
        "total-covariance-factor", &total_covariance_factor,
        "If this is 0.0 we normalize to make the within-class covariance "
        "unit; if 1.0, the total covariance; if between, we normalize "
        "an interpolated matrix.");
    po.Register("binary", &binary, "Write output in binary mode");

    po.Read(argc, argv);

    if (po.NumArgs() != 3) {
      po.PrintUsage();
      exit(1);
    }

    std::string ivector_rspecifier = po.GetArg(1),
                utt2spk_rspecifier = po.GetArg(2),
                lda_wxfilename = po.GetArg(3);

    int32 num_done = 0, num_err = 0, dim = 0;

    SequentialBaseFloatVectorReader ivector_reader(ivector_rspecifier);
    RandomAccessTokenReader utt2spk_reader(utt2spk_rspecifier);

    std::map<std::string, Vector<BaseFloat> *> utt2ivector;
    std::map<std::string, std::vector<std::string> > spk2utt;

    for (; !ivector_reader.Done(); ivector_reader.Next()) {
      std::string utt = ivector_reader.Key();
      const Vector<BaseFloat> &ivector = ivector_reader.Value();
      if (utt2ivector.count(utt) != 0) {
        KALDI_WARN << "Duplicate iVector found for utterance " << utt
                   << ", ignoring it.";
        num_err++;
        continue;
      }
      if (!utt2spk_reader.HasKey(utt)) {
        KALDI_WARN << "utt2spk has no entry for utterance " << utt
                   << ", skipping it.";
        num_err++;
        continue;
      }
      std::string spk = utt2spk_reader.Value(utt);
      utt2ivector[utt] = new Vector<BaseFloat>(ivector);
      if (dim == 0) {
        dim = ivector.Dim();
      } else {
        KALDI_ASSERT(dim == ivector.Dim() && "iVector dimension mismatch");
      }
      spk2utt[spk].push_back(utt);
      num_done++;
    }

    KALDI_LOG << "Read " << num_done << " utterances, " << num_err
              << " with errors.";

    if (num_done == 0) {
      KALDI_ERR << "Did not read any utterances.";
    } else {
      KALDI_LOG << "Computing within-class covariance.";
    }

    Vector<BaseFloat> mean;
    ComputeAndSubtractMean(utt2ivector, &mean);
    KALDI_LOG << "2-norm of iVector mean is " << mean.Norm(2.0);

    Matrix<BaseFloat> lda_mat(lda_dim,
                              dim + 1);  // LDA matrix without the offset term.
    SubMatrix<BaseFloat> linear_part(lda_mat, 0, lda_dim, 0, dim);
    ComputeLdaTransform(utt2ivector, spk2utt, total_covariance_factor,
                        &linear_part);
    Vector<BaseFloat> offset(lda_dim);
    offset.AddMatVec(-1.0, linear_part, kNoTrans, mean, 0.0);
    lda_mat.CopyColFromVec(offset, dim);  // add mean-offset to transform

    KALDI_VLOG(2) << "2-norm of transformed iVector mean is "
                  << offset.Norm(2.0);

    WriteKaldiObject(lda_mat, lda_wxfilename, binary);

    KALDI_LOG << "Wrote LDA transform to "
              << PrintableWxfilename(lda_wxfilename);

    std::map<std::string, Vector<BaseFloat> *>::iterator iter;
    for (iter = utt2ivector.begin(); iter != utt2ivector.end(); ++iter)
      delete iter->second;
    utt2ivector.clear();

    return 0;
  } catch (const std::exception &e) {
    std::cerr << e.what();
    return -1;
  }
}


text:
title: "Faço front-end de graça, saiba como!"
date: 2015-10-12
description: "É isso mesmo que você leu, Faço front-end de graça, mas tem alguns requisitos necessários para que isso aconteça, vem comigo que te explico como"
keywords: "front-end, frontend, html, css, free, freedom, job, projeto, open-source, open, source"
categories: geral
image: /images/posts/2015/10/madruga.gif
tags:
- front-end
- open-source
- geral
---

Você deve estar se perguntando: _**"Front-end de graça? Como assim?"**_

É isso mesmo que você leu, **Faço front-end de graça**, mas tem alguns requisitos necessários para que isso aconteça, vem comigo que te explico como...

## I ❤ open source

Ultimamente estou gostando muito de ajudar a criar projetos _open source_, então um dos requisitos para que eu possa fazer um **HTML bonitão** para o seu projeto é que ele precisa estar no [Github](https://github.com/nandomoreirame) para que todos possam ver, usar e contribuir com ele.

Isso mesmo! Você tem um framework e quer fazer uma documentação bonita pra dele? Tem um projeto bacana e quer uma landing page ou hotsite? Conte comigo!!

## Troca de conhecimento

Outro requisito, caso não seja possível cumprir com o primeiro, é a _**troca de conhecimento**_

Eu tenho amplo conhecimento em tecnologias para _front-end_ como **HTML(Jekyll/liquid, jade, Haml, Erb), CSS(CSS3, SASS, Less, Stylus) e Javascript(jQuery, AngularJS, NodeJS, Gulp.js)**, e eu posso contribuir com o seu projeto **SEM LHE COBRAR NADA POR ISSO**, se e somente se, você tiver algum conhecimento(que possa ser de meu interesse, claro) você pode ensina-lo a mim, seria algo como: _uma nova linguagem de programação, um framework bacana, tocar violão, guitarra, sax, bombardão, teclado, piano, dançar, cozinhar..._ ou seja qualquer coisa mesmo!!!

## E aí, Bora? 👊

![Gif do Seu madruga](/images/posts/2015/10/madruga.gif)

Eu apoio totalmente a troca deconhecimento, seja em uma boa conversa sobre culinária ou em um repositório no _Github_.

Você quer troca figurinhas comigo? Seu projeto está no _Github_ e você precisa de um front-end? Você sabe tocar algum instrumento e tem um projeto bacana para colocar no ar? Podemos nos encontrar e conversar sobre o assunto, podemos fazer isso acontecer...

**Só se for agora 🤘**

/end


text:
package com.elasticinbox.itests;

import static com.jayway.restassured.RestAssured.expect;
import static org.ops4j.pax.exam.CoreOptions.felix;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.ops4j.pax.exam.CoreOptions.scanDir;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import static org.ops4j.pax.exam.CoreOptions.workingDirectory;
import static org.ops4j.pax.exam.CoreOptions.wrappedBundle;

import java.io.IOException;
import java.io.InputStream;

import javax.inject.Inject;

import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractIntegrationTest
{
	static final String TEST_ACCOUNT = "test@elasticinbox.com";
	static final String TEST_PASSWORD = "valid";
	static final String REST_PATH = "/rest/v2/elasticinbox.com/test";
	static final String EMAIL_LARGE_ATT = "/01-attach-utf8.eml";
	static final String EMAIL_REGULAR = "/01-headers-utf8.eml";
	static final String EMAIL_SIMPLE = "/01-simple-ascii.eml";

	static Boolean initialized = false;

	static final Logger logger =
			LoggerFactory.getLogger(AbstractIntegrationTest.class);

	@Inject
	private BundleContext bc;

	@Configuration()
	public Option[] config()
	{
		return options(
				//junitBundles(),
				felix().version("3.2.2"),
				workingDirectory("target/paxrunner/"),
				//repository("https://repository.apache.org/snapshots/").allowSnapshots(),

				// Configs
				systemProperty("elasticinbox.config").value("../test-classes/elasticinbox.yaml"),
				systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),

				// PAX Exam Bundles
				mavenBundle().groupId("org.mortbay.jetty").artifactId("servlet-api").versionAsInProject(),
				mavenBundle().groupId("org.ops4j.pax.web").artifactId("pax-web-api").versionAsInProject(),
				mavenBundle().groupId("org.ops4j.pax.web").artifactId("pax-web-spi").versionAsInProject(),
				mavenBundle().groupId("org.ops4j.pax.web").artifactId("pax-web-jetty-bundle").versionAsInProject(),
				mavenBundle().groupId("org.ops4j.pax.web").artifactId("pax-web-extender-war").versionAsInProject(),

				// Logging
				mavenBundle().groupId("ch.qos.logback").artifactId("logback-core").versionAsInProject(),
				mavenBundle().groupId("ch.qos.logback").artifactId("logback-classic").versionAsInProject(),
				mavenBundle().groupId("org.slf4j").artifactId("slf4j-api").versionAsInProject(),

				// REST-Assured Bundles
				wrappedBundle(mavenBundle().groupId("com.jayway.restassured").artifactId("rest-assured").versionAsInProject()).
					imports("org.apache.http.impl.conn,org.apache.http.impl.client,org.apache.commons.lang3,org.apache.commons.lang3.math,org.codehaus.jackson.map,groovy.lang,org.hamcrest,*"),
				wrappedBundle(mavenBundle().groupId("org.hamcrest").artifactId("hamcrest-all").versionAsInProject()),
				mavenBundle().groupId("org.codehaus.groovy").artifactId("groovy-all").version("1.8.8"),
				mavenBundle().groupId("org.apache.commons").artifactId("commons-lang3").version("3.1"),
				mavenBundle().groupId("commons-collections").artifactId("commons-collections").version("3.2.1"),
				mavenBundle().groupId("org.apache.httpcomponents").artifactId("httpcore-osgi").version("4.2.2"),
				mavenBundle().groupId("org.apache.httpcomponents").artifactId("httpclient-osgi").version("4.2.2"),
				mavenBundle().groupId("org.codehaus.jackson").artifactId("jackson-core-asl").version("1.8.5"),
				mavenBundle().groupId("org.codehaus.jackson").artifactId("jackson-mapper-asl").version("1.8.5"),
				mavenBundle().groupId("org.codehaus.jackson").artifactId("jackson-jaxrs").version("1.8.5"),
				wrappedBundle(mavenBundle().groupId("org.apache.httpcomponents").artifactId("httpmime").version("4.2.2")),
				wrappedBundle(mavenBundle("oauth.signpost", "signpost-commonshttp4", "1.2.1.2")),
				wrappedBundle(mavenBundle("oauth.signpost", "signpost-core", "1.2.1.2")),
				wrappedBundle(mavenBundle("org.ccil.cowan.tagsoup", "tagsoup", "1.2.1")),

				// jClouds and dependencies
				mavenBundle().groupId("com.google.inject").artifactId("guice").versionAsInProject(),
				mavenBundle().groupId("org.jclouds").artifactId("jclouds-core").versionAsInProject(),
				mavenBundle().groupId("org.jclouds").artifactId("jclouds-blobstore").versionAsInProject(),
				mavenBundle().groupId("org.jclouds.api").artifactId("filesystem").versionAsInProject(),
				mavenBundle().groupId("org.jclouds.common").artifactId("aws-common").versionAsInProject(),
				mavenBundle().groupId("org.jclouds.provider").artifactId("aws-s3").versionAsInProject(),
				mavenBundle().groupId("org.jclouds.api").artifactId("s3").versionAsInProject(),
				mavenBundle().groupId("org.jclouds.common").artifactId("azure-common").versionAsInProject(),
				mavenBundle().groupId("org.jclouds.provider").artifactId("azureblob").versionAsInProject(),
				mavenBundle().groupId("org.apache.servicemix.bundles").artifactId("org.apache.servicemix.bundles.aopalliance").versionAsInProject(),
				mavenBundle().groupId("org.apache.servicemix.bundles").artifactId("org.apache.servicemix.bundles.javax-inject").versionAsInProject(),
				mavenBundle().groupId("org.apache.servicemix.bundles").artifactId("org.apache.servicemix.bundles.oauth-commons").versionAsInProject(),
				mavenBundle().groupId("org.apache.servicemix.bundles").artifactId("org.apache.servicemix.bundles.java-xmlbuilder").versionAsInProject(),
				mavenBundle().groupId("com.google.inject.extensions").artifactId("guice-assistedinject").versionAsInProject(),
				mavenBundle().groupId("com.google.code.gson").artifactId("gson").versionAsInProject(),
				mavenBundle().groupId("org.bouncycastle").artifactId("bcprov-jdk16").versionAsInProject(),
				mavenBundle().groupId("org.99soft.guice").artifactId("rocoto").versionAsInProject(),

				// ElasticInbox Bundles
				mavenBundle().groupId("com.google.guava").artifactId("guava").versionAsInProject(),
				mavenBundle().groupId("com.fasterxml.jackson.core").artifactId("jackson-core").versionAsInProject(),
				mavenBundle().groupId("com.fasterxml.jackson.core").artifactId("jackson-databind").versionAsInProject(),
				mavenBundle().groupId("com.fasterxml.jackson.core").artifactId("jackson-annotations").versionAsInProject(),
				mavenBundle().groupId("com.ning").artifactId("compress-lzf").versionAsInProject(),
				mavenBundle().groupId("com.sun.jersey").artifactId("jersey-core").versionAsInProject(),
				mavenBundle().groupId("com.sun.jersey").artifactId("jersey-server").versionAsInProject(),
				mavenBundle().groupId("com.sun.jersey").artifactId("jersey-servlet").versionAsInProject(),
				mavenBundle().groupId("javax.mail").artifactId("mail").versionAsInProject(),
				mavenBundle().groupId("commons-io").artifactId("commons-io").versionAsInProject(),
				mavenBundle().groupId("commons-lang").artifactId("commons-lang").versionAsInProject(),
				scanDir("../bundles/com.ecyrd.speed4j/target/"),
				scanDir("../modules/common/target/"),
				scanDir("../modules/config/target/"),
				scanDir("../modules/core/target/"),
				scanDir("../modules/rest/target/")

				// remote debugging
				//, vmOption( "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005" )
		);
	}

	public BundleContext getBundleContext() {
		return bc;
	}

	/**
	 * This is hack which initializes account. Ideally we should put this into @BeforeClass
	 * and @AfterClass. However PaxExam does not support it at this moment (see PAXEXAM-288).
	 *
	 * This method should be called at the beginning of each test manually.
	 * @throws InterruptedException
	 */
	public static synchronized void initAccount()
	{
		// delete account
		expect().statusCode(204).when().delete(REST_PATH);

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// ignore
		}

		// create account
		expect().statusCode(201).when().post(REST_PATH);
	}

	//@Test
	public void bundleContextTest()
	{
		logger.info("BundleContext of bundle injected: {}", getBundleContext().getBundle().getSymbolicName());

		for (Bundle b : getBundleContext().getBundles()) {
			logger.info("Bundle {} [state={}]", b.getSymbolicName(), b.getState());
		}
	}

	/**
	 * Returns resource size
	 *
	 * @param name
	 * @return
	 * @throws IOException
	 */
	public long getResourceSize(String messageFile) throws IOException
	{
		InputStream in = null;

		try {
			in = this.getClass().getResourceAsStream(messageFile);
			return in.available();
		} finally {
			in.close();
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is part of the DITA Open Toolkit project hosted on
     Sourceforge.net. See the accompanying license.txt file in the
     main toolkit package for applicable licenses.-->
<!-- (C) Copyright IBM Corporation 2005, 2009 All Rights Reserved. -->
<strings xml:lang="ro-ro">        <!-- Romanian -->

  <str name="tutorialNext">Următorul</str>
  <str name="tutorialPrevious">Anteriorul</str>
  <str name="Modules in this tutorial">Module în acest seminar</str>
  <str name="Lessons in this tutorial">Lecţii în acest seminar</str>
  <str name="Lessons in this module">Lecţii în acest modul</str>

</strings>


text:
Contract Overview

                  {{ addr.balance | number: 10 }}

                  MUX Balance

                  {{ addr.ethfiat | number: 10 }}

                  0 Mined

                  {{ addr.count }} Transactions

                    WATCH
                    WATCHING

                        {{ addr.follow_count }}0
                        WATCHING

                   Transactions

                   Internal Transactions

                   Contract Source

                           TxHash
                           Block
                           From
                           To
                           ETC
                           gas
                           Age

                           TxHash
                           Block
                           From
                           To
                           ETC
                           gas
                           Age

              <contract-source></contract-source>


text:
import React, { Component } from 'react'
import keydown, { Keys } from 'react-keydown'

class Performance extends Component {
  componentWillReceiveProps({keydown}) {
    if (keydown.event) {
      switch (keydown.event.which) {
        case Keys.left:
          this.props.router.push('switches')
          break
        case Keys.right:
          this.props.router.push('reusable-components')
          break
        default:
          break
      }
    }
  }

  render() {
    return (

          Performance

DOM

API to manipulate an HTML website

Virtual DOM

In-memory representation of DOM

React Performance

Diff between its virtual DOM and real DOM - only update necessary nodes

Batch Updates

    )
  }
}

export default keydown(Performance)


text:
package org.pm4j.deprecated.core.pm.filter;

import java.util.List;

import org.pm4j.core.pm.PmAttr;
import org.pm4j.core.pm.PmBean;
import org.pm4j.core.pm.PmCommand;

@Deprecated
public interface DeprPmFilterSet extends PmBean<DeprFilterSet> {

  /** Default identifier for user defined filter sets. */
  static final String USER_FILTER_SET_ID = "userFilterSet";

  PmAttr<List<DeprPmFilterItem>> getFilterItems();

  PmAttr<DeprCombinedBy> getCombinedBy();

  PmCommand getCmdApply();

  PmCommand getCmdClear();
}


text:
date: 2016-11-24
layout: log
location: Niles, MI to Lafayette, IN
coffee:
restaurants:
office:
beers:
hikes:
achievements:
personal_growth:
highlight:
description:
private_notes:
---

> Michigan's in the rear view now

Let the journey begin. Drove two and a half hours to Grandma's in the morning, Blue saying goodbye to the Mitten for the foreseeable future. Turkey, mashed potatoes, and all the good stuff at Grandma Hanstra's. Family, food, and football (but not really football, it's usually just kind of on in the background, isn't it?). Went around the room and said something we're thankful for. Food coma the rest of the day.


text:
package dominio;

import javax.jdo.annotations.PersistenceCapable;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.services.i18n.TranslatableString;

@javax.jdo.annotations.Queries({
    @javax.jdo.annotations.Query(name = "buscarNombre", language = "JDOQL",value = "SELECT "+ "FROM dominio.clasificacionSugerida "+ "WHERE nombre.indexOf(:name) >= 0 ")
})
@javax.jdo.annotations.Unique(name="ClasificacionSugerida_nombre_key", members = {"nombre"})

@DomainObject(objectType = "ClasificacionSugerida", bounded = true)
@PersistenceCapable
public class ClasificacionSugerida
{
	private String nombre;
	private String descripcion;

	@javax.jdo.annotations.Column(allowsNull = "false",length = 40)
	@MemberOrder (sequence = "2")
	public String getDescripcion()
	{
		return descripcion;
	}

	public void setDescripcion(String descripcion)
	{
		this.descripcion = descripcion;
	}
	@javax.jdo.annotations.Column(allowsNull = "false",length = 40)
	@MemberOrder (sequence = "1")
	public String getNombre() {
		return nombre;
	}
	public void setNombre(String nombre)
	{
		this.nombre = nombre;
	}

	public TranslatableString title()
	{
	      return TranslatableString.tr("{name}", "name", getNombre());
	}

}


text:
package org.apache.camel.component.aws.sdb;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.DefaultComponent;

public class SdbComponent extends DefaultComponent {

    public SdbComponent() {
        this(null);
    }

    public SdbComponent(CamelContext context) {
        super(context);

        registerExtension(new SdbComponentVerifierExtension());
    }

    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        SdbConfiguration configuration = new SdbConfiguration();
        setProperties(configuration, parameters);

        if (remaining == null || remaining.trim().length() == 0) {
            throw new IllegalArgumentException("Domain name must be specified.");
        }
        configuration.setDomainName(remaining);

        if (configuration.getAmazonSDBClient() == null && (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) {
            throw new IllegalArgumentException("amazonSDBClient or accessKey and secretKey must be specified");
        }

        SdbEndpoint endpoint = new SdbEndpoint(uri, this, configuration);
        return endpoint;
    }
}


text:
package com.nexuslink.wenavi.presenter;

import com.nexuslink.wenavi.callback.ServerResultCallback;
import com.nexuslink.wenavi.contract.ChatContract;
import com.nexuslink.wenavi.model.ChatItem;
import com.nexuslink.wenavi.model.jmessage.JMessageServerModel;

import java.util.List;

import cn.jpush.im.android.api.model.Conversation;

/**
 * Created by 18064 on 2018/2/2.
 */

public class ChatPresenter implements ChatContract.Presenter, ServerResultCallback {

    private ChatContract.View view;

    private JMessageServerModel model;

    public ChatPresenter(ChatContract.View view) {
        this.view = view;
        model = JMessageServerModel.getInstance();
        model.setCallback(this);
    }

    @Override
    public List<ChatItem> loadChatList(String targetUsername) {
        return model.getChatList(targetUsername);
    }

    @Override
    public <T> void onSuccess(T result, int code) {

    }

    @Override
    public void onFail(String exception, int code) {
        view.shortToast(exception);
    }
}


text:
PACKAGE_NAME=nodelib
#PACKAGE_VERSION is configurable can be passed as an argument.
PACKAGE_VERSION=${1:-d6a7960}
PACKAGE_URL=https://github.com/nodelib/nodelib

yum install -y yum-utils git jq

NODE_VERSION=v12.22.4
#installing nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
source ~/.bashrc
nvm install $NODE_VERSION

OS_NAME=$(cat /etc/os-release | grep ^PRETTY_NAME | cut -d= -f2)

#Check if package exists
if [ -d "$PACKAGE_NAME" ] ; then
  rm -rf $PACKAGE_NAME
  echo "$PACKAGE_NAME  | $PACKAGE_VERSION | $OS_NAME | GitHub | Removed existing package if any"

fi

if ! git clone $PACKAGE_URL $PACKAGE_NAME; then
        echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------"
        echo "$PACKAGE_URL $PACKAGE_NAME"
        echo "$PACKAGE_NAME  |  $PACKAGE_URL |  $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Clone_Fails"
        exit 1
fi

cd  $PACKAGE_NAME
git checkout $PACKAGE_VERSION
PACKAGE_VERSION=$(jq -r ".version" package.json)
# run the test command from test.sh

if ! npm install && npm audit fix && npm audit fix --force; then
    echo "------------------$PACKAGE_NAME:install_fails-------------------------------------"
    echo "$PACKAGE_URL $PACKAGE_NAME"
    echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_Fails"
    exit 1
fi

#"lerna bootstrap" is used to install all dependencies and any cross-dependencies between packages.
     npx lerna bootstrap
     npm run compile

if ! npm run test; then
    echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------"
    echo "$PACKAGE_URL $PACKAGE_NAME"
    echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_success_but_test_Fails"
    exit 1
else
    echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
    echo "$PACKAGE_URL $PACKAGE_NAME"
    echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub  | Pass |  Both_Install_and_Test_Success"
    exit 0
fi

# All different requested version has same commit id so can be tested in one go all the packages.
# We need to create single script (nodelib) for all sub packages.

#@nodelib/fs.scandir@2.1.5   d6a7960
#@nodelib/fs.stat@2.0.5      d6a7960
#@nodelib/fs.walk@1.2.7      d6a7960


text:
package audio.rabid.dev.roe.testobjects;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import audio.rabid.dev.roe.models.Server;

/**
 * Created by charles on 10/30/15.
 */
public class DummyObjectMockServer extends Server {

    private static DummyObjectMockServer instance = new DummyObjectMockServer();

    public static DummyObjectMockServer getInstance() {
        return instance;
    }

    private DummyObjectMockServer() {
        super(null);
    }

    private int currentPK = 10;

    public int readCount = 0;

    public int deletedCount = 0;

    public int createCount = 0;

    public int updatedCount = 0;

    boolean networkAvailable = true;

    public void setNetworkAvailable(boolean available) {
        networkAvailable = available;
    }

    private void checkConnection() throws NetworkException {
        if (!networkAvailable) try {
            throw new NetworkException(new Response(404, new JSONObject().put("error", "Network Disabled"), null));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public synchronized JSONObject getItem(Class<?> clazz, String serverId) throws NetworkException {
        checkConnection();
        readCount++;
        try {
            return DummyObjectSource.getInstance().toJSON(new DummyObject("dummy" + serverId, 0, null)).put("id", Integer.parseInt(serverId));
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public synchronized JSONObject createItem(Class<?> clazz, JSONObject item) throws NetworkException {
        checkConnection();
        createCount++;
        try {
            return item.put("id", currentPK++);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public synchronized List<JSONObject> getItems(Class<?> clazz, JSONObject search) throws NetworkException {
        checkConnection();
        List<JSONObject> items = new ArrayList<>();
        try {
            for (int i = 0; i < 10; i++) {
                readCount++;
                JSONObject data = DummyObjectSource.getInstance().toJSON(new DummyObject("dummy" + (currentPK++), 0, null)).put("id", currentPK);
                items.add(data);
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return items;
    }

    @Override
    public synchronized JSONObject updateItem(Class<?> clazz, String serverId, JSONObject data) throws NetworkException {
        checkConnection();
        updatedCount++;
        return data;
    }

    @Override
    public synchronized JSONObject deleteItem(Class<?> clazz, String serverId) throws NetworkException {
        checkConnection();
        deletedCount++;
        return new JSONObject();
    }

    public boolean isErrorResponse(Response response) {
        return !networkAvailable;
    }
}


text:
<?php

namespace ITDoors\ControllingBundle\Classes;

/**
 * ControllingAccess class
 */
class ControllingAccess extends BasicControllingAccess
{
    /**
     * @return bool
     */
    public function canEdit ()
    {
        return true;
    }
    /**
     * @return bool
     */
    public function canSeeAll ()
    {
        return true;
    }
    /**
     * @return bool
     */
    public function canAddNote ()
    {
        return true;
    }
    /**
     * @return bool
     */
    public function canAddResponsible ()
    {
        return true;
    }
    /**
     * @return bool
     */
    public function canChangeStatusCourt ()
    {
        return true;
    }
    /**
     * @return bool
     */
    public function canChangeStatus ()
    {
        return true;
    }
    /**
     * @return bool
     */
    public function canSeeExpectedData ()
    {
        return true;
    }
    /**
     * @return bool
     */
    public function canSeeExpectedPay ()
    {
        return true;
    }
}


text:
package stainless
package codegen.runtime

abstract class Monitor {
  def onInvocation(): Unit

  def typeParams(params: Array[Int], tps: Array[Int], newTps: Array[Int]): Array[Int]

  def typeSubstitute(id: Int, closures: Array[AnyRef]): Int

  def onChooseInvocation(id: Int, tps: Array[Int], args: Array[AnyRef]): AnyRef

  def onForallInvocation(id: Int, tps: Array[Int], args: Array[AnyRef]): Boolean
}


text:
#include "map/displacement_mode_manager.hpp"

DisplacementModeManager::DisplacementModeManager(TCallback && callback)
  : m_callback(move(callback)), m_mask(0)
{
}

void DisplacementModeManager::Set(Slot slot, bool show)
{
  std::lock_guard<std::mutex> lock(m_mu);

  uint32_t const bit = static_cast<uint32_t>(1) << slot;
  uint32_t const mask = m_mask;
  if (show)
    m_mask = mask | bit;
  else
    m_mask = mask & ~bit;

  // We are only intersected in states "mask is zero" and "mask is not
  // zero". Therefore, do nothing if the new state is the same as the
  // previous state.
  if ((mask == 0) == (m_mask == 0))
    return;

  if (m_mask != 0)
    m_callback(true /* show */);
  else
    m_callback(false /* show */);
}


text:
package org.camunda.bpm.engine.rest.impl.history;

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

import javax.ws.rs.core.MultivaluedMap;

import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.history.HistoricActivityStatisticsQuery;
import org.camunda.bpm.engine.rest.dto.AbstractQueryDto;
import org.camunda.bpm.engine.rest.dto.CamundaQueryParam;
import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter;
import org.camunda.bpm.engine.rest.dto.converter.DateConverter;
import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter;
import com.fasterxml.jackson.databind.ObjectMapper;

public class HistoricActivityStatisticsQueryDto extends AbstractQueryDto<HistoricActivityStatisticsQuery> {

  protected static final String SORT_ORDER_ACTIVITY_ID = "activityId";

  protected String processDefinitionId;

  protected Boolean includeCanceled;
  protected Boolean includeFinished;
  protected Boolean includeCompleteScope;
  protected Boolean includeIncidents;

  protected Date startedAfter;
  protected Date startedBefore;
  protected Date finishedAfter;
  protected Date finishedBefore;

  protected String[] processInstanceIdIn;

  public HistoricActivityStatisticsQueryDto(ObjectMapper objectMapper, String processDefinitionId, MultivaluedMap<String, String> queryParameters) {
    super(objectMapper, queryParameters);
    this.processDefinitionId = processDefinitionId;
  }

  /*
   * This is a path param and set from within the resource method
   */
  public void setProcessDefinitionId(String processDefinitionId) {
    this.processDefinitionId = processDefinitionId;
  }

  @CamundaQueryParam(value = "canceled", converter = BooleanConverter.class)
  public void setIncludeCanceled(Boolean includeCanceled) {
    this.includeCanceled = includeCanceled;
  }

  @CamundaQueryParam(value = "finished", converter = BooleanConverter.class)
  public void setIncludeFinished(Boolean includeFinished) {
    this.includeFinished = includeFinished;
  }

  @CamundaQueryParam(value = "completeScope", converter = BooleanConverter.class)
  public void setIncludeCompleteScope(Boolean includeCompleteScope) {
    this.includeCompleteScope = includeCompleteScope;
  }

  @CamundaQueryParam(value = "incidents", converter = BooleanConverter.class)
  public void setIncludeIncidents(Boolean includeClosedIncidents) {
    this.includeIncidents = includeClosedIncidents;
  }

  @CamundaQueryParam(value = "startedAfter", converter = DateConverter.class)
  public void setStartedAfter(Date startedAfter) {
    this.startedAfter = startedAfter;
  }

  @CamundaQueryParam(value = "startedBefore", converter = DateConverter.class)
  public void setStartedBefore(Date startedBefore) {
    this.startedBefore = startedBefore;
  }

  @CamundaQueryParam(value = "finishedAfter", converter = DateConverter.class)
  public void setFinishedAfter(Date finishedAfter) {
    this.finishedAfter = finishedAfter;
  }

  @CamundaQueryParam(value = "finishedBefore", converter = DateConverter.class)
  public void setFinishedBefore(Date finishedBefore) {
    this.finishedBefore = finishedBefore;
  }

  @CamundaQueryParam(value = "processInstanceIdIn", converter = StringArrayConverter.class)
  public void setProcessInstanceIdIn(String[] processInstanceIdIn) {
    this.processInstanceIdIn = processInstanceIdIn;
  }

  @Override
  protected boolean isValidSortByValue(String value) {
    return SORT_ORDER_ACTIVITY_ID.equals(value);
  }

  @Override
  protected HistoricActivityStatisticsQuery createNewQuery(ProcessEngine engine) {
    return engine.getHistoryService().createHistoricActivityStatisticsQuery(processDefinitionId);
  }

  @Override
  protected void applyFilters(HistoricActivityStatisticsQuery query) {

    if (includeCanceled != null && includeCanceled) {
      query.includeCanceled();
    }

    if (includeFinished != null && includeFinished) {
      query.includeFinished();
    }

    if (includeCompleteScope != null && includeCompleteScope) {
      query.includeCompleteScope();
    }

    if (includeIncidents !=null && includeIncidents) {
      query.includeIncidents();
    }

    if (startedAfter != null) {
      query.startedAfter(startedAfter);
    }

    if (startedBefore != null) {
      query.startedBefore(startedBefore);
    }

    if (finishedAfter != null) {
      query.finishedAfter(finishedAfter);
    }

    if (finishedBefore != null) {
      query.finishedBefore(finishedBefore);
    }

    if (processInstanceIdIn != null) {
      query.processInstanceIdIn(processInstanceIdIn);
    }
  }

  @Override
  protected void applySortBy(HistoricActivityStatisticsQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
    if (SORT_ORDER_ACTIVITY_ID.equals(sortBy)) {
      query.orderByActivityId();
    }
  }
}


text:
package akka.util

import language.implicitConversions

import java.util.concurrent.TimeUnit
import scala.concurrent.duration.{ Duration, FiniteDuration }

@SerialVersionUID(1L)
case class Timeout(duration: FiniteDuration) {

  /**
   * Construct a Timeout from the given time unit and factor.
   */
  def this(length: Long, unit: TimeUnit) = this(Duration(length, unit))
}

/**
 * A Timeout is a wrapper on top of Duration to be more specific about what the duration means.
 */
object Timeout {

  /**
   * A timeout with zero duration, will cause most requests to always timeout.
   */
  val zero: Timeout = new Timeout(Duration.Zero)

  /**
   * Construct a Timeout from the given time unit and factor.
   */
  def apply(length: Long, unit: TimeUnit): Timeout = new Timeout(length, unit)

  implicit def durationToTimeout(duration: FiniteDuration): Timeout = new Timeout(duration)
}


text:
package com.koch.ambeth.cache.stream.float32;

import com.koch.ambeth.cache.stream.AbstractInputSourceConverter;
import com.koch.ambeth.cache.stream.AbstractInputSourceValueHolder;

public class FloatInputSourceConverter extends AbstractInputSourceConverter {
	@Override
	protected AbstractInputSourceValueHolder createValueHolderInstance() {
		return new FloatInputSourceValueHolder();
	}
}


text:
### VALE
- fast virtual ethernet

### netmap pipes
- shared memory packet transport channel

### details
- for both userspace & kernel clients
- vale - in-kernel
- faster than sockets, bpf, tun/tap, native switches, pipes
- 14.88 million packets per second with 1 core on a 10 Gbit NIC
- 20 Mpps per core for VALE ports
- 100 Mpps for netmap pipes
- userspace clients can send/receive raw packets through memory mapped buffers
- supports non-blocking IO via ioctls
- supports sync & blocking IO via file descriptor
- standard OS mechanisms e.g. select, poll, epool, kqueue
- port are ring buffers in a mmapped region
- one ring for transmit/receive of virtual port
- bind a fd to a port & netmap client can send or receive packets in batches via the ring
- can implement zero-copy forwarding between ports
- All NICS in netmap mode use same memory region
- region is accessible to all processes who own the /dev/netmap fds bound to NICs
- independent VALE & netmap pipe ports by default use separate memory regions but can be configured otherwise

### VALE & netmap pipes can be created dynamically
- providing high speed packet IO between processes
- providing high speed packet IO between VMs
- providing high speed packet IO between NICs
- providing high speed packet IO between host stack

For best performance, netmap requires explicit support in device drivers

netmap <-> port <-> NIC
netmap <-> port <-> host stack
netmap <-> port <-> VALE switch

fd = open("/dev/netmap");
ioctl(fd, NIOCREGIF, (struct nmreq *)arg);

- above will create port , ring, vale dynamically

What happens behind the scenes:
While a NIC is in netmap mode, OS will believe the interface is up & running.
OS-generated packets for that NIC end up into a netmap ring & another ring is used to send packets to the OS network stack.
A close on the fd removes the binding & returns the NIC to normal mode i.e.
- reconnect the data path to the host stack
- destroys the virtual port


text:
package org.keycloak.testsuite.console.page.realm;

import org.jboss.arquillian.graphene.page.Page;
import org.keycloak.testsuite.page.Form;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;

import java.util.concurrent.TimeUnit;

import static java.lang.String.valueOf;
import static org.apache.commons.lang3.text.WordUtils.capitalize;
import static org.keycloak.testsuite.util.WaitUtils.waitUntilElement;

/**
 *
 * @author Petr Mensik
 */
public class TokenSettings extends RealmSettings {

    @Override
    public String getUriFragment() {
        return super.getUriFragment() + "/token-settings";
    }

    @Page
    private TokenSettingsForm form;

    public TokenSettingsForm form() {
        return form;
    }

    public class TokenSettingsForm extends Form {

        @FindBy(id = "ssoSessionIdleTimeout")
        private WebElement sessionTimeout;

        @FindBy(name = "ssoSessionIdleTimeoutUnit")
        private Select sessionTimeoutUnit;

        @FindBy(id = "ssoSessionMaxLifespan")
        private WebElement sessionLifespanTimeout;

        @FindBy(name = "ssoSessionMaxLifespanUnit")
        private Select sessionLifespanTimeoutUnit;

        public void setSessionTimeout(int timeout, TimeUnit unit) {
            setTimeout(sessionTimeoutUnit, sessionTimeout, timeout, unit);
        }

        public void setSessionTimeoutLifespan(int time, TimeUnit unit) {
            setTimeout(sessionLifespanTimeoutUnit, sessionLifespanTimeout, time, unit);
        }

        private void setTimeout(Select timeoutElement, WebElement unitElement,
                int timeout, TimeUnit unit) {
            waitUntilElement(sessionTimeout).is().present();
            timeoutElement.selectByValue(capitalize(unit.name().toLowerCase()));
            unitElement.clear();
            unitElement.sendKeys(valueOf(timeout));
        }

    }
}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInite5b7fb190fece0d00ea241a3ebf692ad::getLoader();


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

<polymer-element name="leaflet-marker-map" class="dc-element">

  <template>

      <link rel="stylesheet" href="leaflet.css" />
      <link rel="stylesheet" href="MarkerCluster.css" />
      <link rel="stylesheet" href="MarkerCluster.Default.css" />

  </template>

</polymer-element>


text:
package org.grails.plugins.rest.impl;

import java.util.List;

import org.codehaus.groovy.grails.commons.GrailsClass;
import org.codehaus.groovy.grails.orm.hibernate.SessionFactoryHolder;
import org.grails.plugins.rest.DataRetriever;
import org.grails.plugins.rest.DomainClassResolver;
import org.grails.plugins.rest.url.DomainClassElement;
import org.grails.plugins.rest.url.Element;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

public class HqlDataRetriever implements DataRetriever {

	private final DomainClassResolver domainClassResolver;
	private final SessionFactoryHolder sessionFactoryHolder;

	public HqlDataRetriever(DomainClassResolver domainClassResolver, SessionFactoryHolder sessionFactoryHolder) {
		this.domainClassResolver = domainClassResolver;
		this.sessionFactoryHolder = sessionFactoryHolder;
	}

	@Override
	public Object retrieve(List<Element> elements) throws Exception {
		DomainClassElement rootElement = (DomainClassElement) elements.get(0);
		GrailsClass root = domainClassResolver.resolve(rootElement.name);
		HqlQuery hql = new HqlQueryBuilder().buildFromElements(root, elements);
		SessionFactory sessionFactory = sessionFactoryHolder.getSessionFactory();
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery(hql.getQuery());
		return query.list();
	}

}


text:
IDE
===

Koding's new IDE has been overhauled. Much more to come but in the meanwhile, you can play with these features immediately or have a look around the code base.

### Try the live version [**here**](https://koding.com/IDE).

![IDE](https://koding.com/a/site.landing/images/slideshow/ss-ide-collapsed.png)

### Features

* **Multiple language support.** Go, NodeJS, Ruby, Python, PHP, Java, C, C++, Javascript, Coffeescript, etc. whatever your language of choice, the IDE supports it and gives you gorgeous syntax highlighting.
* **Shortcuts.** Use our extensive keyboard shortcuts to control everything inside the IDE.
* **Themes.** Easily switch the default color theme and font to one from a growing list of choices.
* **Workspaces.** Use workspaces to organize your project. Workpsaces keep everything neat and tidy.
* **Previews.** Easily preview your work using the built-in browser. No more tab switching.
* **Collapsable Panes.** Collapse the IDE main frame to get more screen real estate.
* **Common editor settings.** Autocomplete, soft tabs, line numbers, word wrap, tab size, auto-indenting..are all there.
* **Resize and Split panes.** Open several IDE tabs and resize them the way you want.
* **Graphical permissions.** Don't like setting permissions on the command line, do it via a handy GUI.
* **Multi-cursor support.** Create multiple cursors and selections in order to make lots of similar edits at once.
* **Code folding.** Easily fold away fragments of code that you don't need to look at.

We appreciate any contribution to this repo so feel free to contribute!

See you on [Koding](https://koding.com)!


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>记忆游戏</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/style.css">

            记忆游戏

正在努力加载中……


text:
from __future__ import unicode_literals, division, absolute_import
from builtins import *  # noqa pylint: disable=unused-import, redefined-builtin

import re
import logging

from flexget import plugin
from flexget.event import event
from flexget.plugins.internal.urlrewriting import UrlRewritingError
from flexget.utils import requests
from flexget.utils.soup import get_soup

log = logging.getLogger('serienjunkies')

regex_single_ep = re.compile(r'(S\d+E\d\d+)(?!-E)', re.I)
regex_multi_ep = re.compile(r'(?P<season>S\d\d)E(?P<startep>\d\d+)-E?(?P<stopep>\d\d+)', re.I)
regex_season = re.compile(r'(?<=\.|\-)S\d\d(?:[-\.]S\d\d)*(?!E\d\d+)', re.I)

regex_language_container = re.compile(r'Sprache')

regex_is_german = re.compile(r'german|deutsch', re.I)
regex_is_foreign = re.compile(
    r'englisc?h|französisch|japanisch|dänisch|norwegisch|niederländisch|ungarisch|italienisch|portugiesisch', re.I)
regex_is_subtitle = re.compile(r'Untertitel|Subs?|UT', re.I)

LANGUAGE = ['german', 'foreign', 'subtitle', 'dual']
HOSTER = ['ul', 'cz', 'so', 'all']

DEFAULT_LANGUAGE = 'dual'
DEFAULT_HOSTER = 'ul'

class UrlRewriteSerienjunkies(object):
    """
    Serienjunkies urlrewriter
    Version 1.0.2

    Language setting works like a whitelist, the selected is needed,
    but others are still possible.

    Configuration
    language: [german|foreign|subtitle|dual] default "foreign"
    hoster: [ul|cz|so|all] default "ul"
    """

    schema = {
        'type': 'object',
        'properties': {
            'language': {'type': 'string', 'enum': LANGUAGE},
            'hoster': {'type': 'string', 'enum': HOSTER}
        },
        'additionalProperties': False
    }

    def on_task_start(self, task, config):
        self.config = config or {}
        self.config.setdefault('hoster', DEFAULT_HOSTER)
        self.config.setdefault('language', DEFAULT_LANGUAGE)

    # urlrewriter API
    def url_rewritable(self, task, entry):
        url = entry['url']
        if url.startswith('http://www.serienjunkies.org/') or url.startswith('http://serienjunkies.org/'):
            return True
        return False

    # urlrewriter API
    def url_rewrite(self, task, entry):
        series_url = entry['url']
        search_title = re.sub('\[.*\] ', '', entry['title'])

        download_urls = self.parse_downloads(series_url, search_title)
        if not download_urls:
            entry.reject('No Episode found')
        else:
            entry['url'] = download_urls[-1]
            entry['description'] = ", ".join(download_urls)

        # Debug Information
        log.debug('TV Show URL: %s', series_url)
        log.debug('Episode: %s', search_title)
        log.debug('Download URL: %s', download_urls)

    @plugin.internet(log)
    def parse_downloads(self, series_url, search_title):
        page = requests.get(series_url).content
        try:
            soup = get_soup(page)
        except Exception as e:
            raise UrlRewritingError(e)

        urls = []
        # find all titles
        episode_titles = self.find_all_titles(search_title)
        if not episode_titles:
            raise UrlRewritingError('Unable to find episode')

        for ep_title in episode_titles:
            # find matching download
            episode_title = soup.find('strong', text=re.compile(ep_title, re.I))
            if not episode_title:
                continue

            # find download container
            episode = episode_title.parent
            if not episode:
                continue

            # find episode language
            episode_lang = episode.find_previous('strong', text=re.compile('Sprache')).next_sibling
            if not episode_lang:
                log.warning('No language found for: %s', series_url)
                continue

            # filter language
            if not self.check_language(episode_lang):
                log.warning('languages not matching: %s <> %s', self.config['language'], episode_lang)
                continue

            # find download links
            links = episode.find_all('a')
            if not links:
                log.warning('No links found for: %s', series_url)
                continue

            for link in links:
                if not link.has_attr('href'):
                    continue

                url = link['href']
                pattern = 'http:\/\/download\.serienjunkies\.org.*%s_.*\.html' % self.config['hoster']

                if re.match(pattern, url) or self.config['hoster'] == 'all':
                    urls.append(url)
                else:
                    continue
        return urls

    def find_all_titles(self, search_title):
        search_titles = []
        # Check type
        if regex_multi_ep.search(search_title):
            log.debug('Title seems to describe multiple episodes')
            first_ep = int(regex_multi_ep.search(search_title).group('startep'))
            last_ep = int(regex_multi_ep.search(search_title).group('stopep'))
            season = regex_multi_ep.search(search_title).group('season') + 'E'
            for i in range(first_ep, last_ep + 1):
                # ToDO: Umlaute , Mehrzeilig etc.
                search_titles.append(regex_multi_ep.sub(season + str(i).zfill(2) + '[\\\\w\\\\.\\\\(\\\\)]*',
                                                        search_title))
        elif regex_season.search(search_title):
            log.debug('Title seems to describe one or more season')
            search_string = regex_season.search(search_title).group(0)
            for s in re.findall('(?<!\-)S\d\d(?!\-)', search_string):
                search_titles.append(regex_season.sub(s + '[\\\\w\\\\.]*', search_title))
            for s in re.finditer('(?<!\-)S(\d\d)-S(\d\d)(?!\-)', search_string):
                season_start = int(s.group(1))
                season_end = int(s.group(2))
                for i in range(season_start, season_end + 1):
                    search_titles.append(regex_season.sub('S' + str(i).zfill(2) + '[\\\\w\\\\.]*', search_title))
        else:
            log.debug('Title seems to describe a single episode')
            search_titles.append(re.escape(search_title))
        return search_titles

    def check_language(self, languages):
        # Cut additional Subtitles
        languages = languages.split('|', 1)[0]

        language_list = re.split(r'[,&]', languages)

        try:
            if self.config['language'] == 'german':
                if regex_is_german.search(language_list[0]):
                    return True
            elif self.config['language'] == 'foreign':
                if (regex_is_foreign.search(language_list[0]) and len(language_list) == 1) or \
                        (len(language_list) > 1 and not regex_is_subtitle.search(language_list[1])):
                    return True
            elif self.config['language'] == 'subtitle':
                if len(language_list) > 1 and regex_is_subtitle.search(language_list[1]):
                    return True
            elif self.config['language'] == 'dual':
                if len(language_list) > 1 and not regex_is_subtitle.search(language_list[1]):
                    return True
        except (KeyError, re.error):
            pass

        return False

@event('plugin.register')
def register_plugin():
    plugin.register(UrlRewriteSerienjunkies, 'serienjunkies', interfaces=['urlrewriter', 'task'], api_ver=2)


text:
/*******************************************************************************
*
*  Filename    : SaveUtils.hpp
*  Description : Saving utils to combat ROOT's sub-par PDF outputs
*  Author      : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*******************************************************************************/
#ifndef MANAGERUTILS_PLOTUTILS_SAVEUTILS
#define MANAGERUTILS_PLOTUTILS_SAVEUTILS

#include "TCanvas.h"

namespace mgr {
/*******************************************************************************
*   SaveToPDF - saving TCanvas to PDF file, invokes PDF correction ghostscript
*******************************************************************************/
void SaveToPDF( TCanvas*, const std::string& );

/*******************************************************************************
*   SaveToRoot - saving TCanvas to ROOT File
*******************************************************************************/
void SaveToROOT( TCanvas*, const std::string& filename, const std::string& objname );

}

#endif/* end of include guard: MANAGERUTILS_PLOTUTILS_SAVEUTILS */


text:
adapter Package
===============

:mod:`adapter` Package
----------------------

.. automodule:: Sea.adapter
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`materials` Module
-----------------------

.. automodule:: Sea.adapter.materials
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`object_maps` Module
-------------------------

.. automodule:: Sea.adapter.object_maps
    :members:
    :undoc-members:
    :show-inheritance:

Subpackages
-----------

.. toctree::

    Sea.adapter.base
    Sea.adapter.components
    Sea.adapter.connections
    Sea.adapter.couplings
    Sea.adapter.excitations
    Sea.adapter.materials
    Sea.adapter.subsystems
    Sea.adapter.system


text:
{{::('loginDialogT.pleaseSignIn'|$translate)}}

{{::('loginDialogT.howRegister'|$translate)}}

{{::('loginDialogT.anyPersonSignUp'|$translate)}} accounts.cbd.int/signup

{{::('loginDialogT.makeSure'|$translate)}}

{{::('loginDialogT.forgotPassword'|$translate)}}

{{::('loginDialogT.clickHere'|$translate)}} accounts.cbd.int/password/reset {{::('loginDialogT.resetPassword'|$translate)}}

{{::('loginDialogT.displayProblems'|$translate)}}

 The  {{::('loginDialogT.recentVersions'|$translate)}}

{{::('loginDialogT.technicalSupport'|$translate)}}

            {{::('loginDialogT.seeFaq'|$translate)}}