text:
var EventBindings = require('event_bindings');
var binding = require('binding').Binding.create('webview');
var contextMenuNatives = requireNative('context_menus');
var sendRequest = require('sendRequest').sendRequest;

binding.registerCustomHook(function(bindingsAPI) {
  var apiFunctions = bindingsAPI.apiFunctions;

  var webviewContextMenus = {};
  webviewContextMenus.generatedIdHandlers = {};
  webviewContextMenus.stringIdHandlers = {};

  // Per item event handler.
  var ename = 'webview.contextMenus';
  webviewContextMenus.event = new EventBindings.Event(ename);

  webviewContextMenus.getIdFromCreateProperties = function(prop) {
    if (typeof(prop.id) !== 'undefined')
      return prop.id;
    return prop.generatedId;
  };

  webviewContextMenus.handlersForId = function(instanceId, id) {
    if (typeof(id) === 'number') {
      if (!webviewContextMenus.generatedIdHandlers[instanceId]) {
        webviewContextMenus.generatedIdHandlers[instanceId] = {};
      }
      return webviewContextMenus.generatedIdHandlers[instanceId];
    }

    if (!webviewContextMenus.stringIdHandlers[instanceId]) {
      webviewContextMenus.stringIdHandlers[instanceId] = {};
    }
    return webviewContextMenus.stringIdHandlers[instanceId];
  };

  webviewContextMenus.ensureListenerSetup = function() {
    if (webviewContextMenus.listening) {
      return;
    }
    webviewContextMenus.listening = true;
    webviewContextMenus.event.addListener(function() {
      // An extension context menu item has been clicked on - fire the onclick
      // if there is one.
      var id = arguments[0].menuItemId;
      var instanceId = arguments[0].webviewInstanceId;
      delete arguments[0].webviewInstanceId;
      var onclick = webviewContextMenus.handlersForId(instanceId, id)[id];
      if (onclick) {
        $Function.apply(onclick, null, arguments);
      }
    });
  };

  apiFunctions.setHandleRequest('contextMenusCreate', function() {
    var args = arguments;
    var id = contextMenuNatives.GetNextContextMenuId();
    args[1].generatedId = id;

    var optArgs = {
      customCallback: this.customCallback,
    };

    sendRequest(this.name, args, this.definition.parameters, optArgs);
    return webviewContextMenus.getIdFromCreateProperties(args[1]);
  });

  apiFunctions.setCustomCallback('contextMenusCreate',
                                 function(name, request, response) {
    if (chrome.runtime.lastError) {
      return;
    }

    var instanceId = request.args[0];
    var id = webviewContextMenus.getIdFromCreateProperties(request.args[1]);
    var onclick = request.args.length ? request.args[1].onclick : null;
    if (onclick) {
      webviewContextMenus.ensureListenerSetup();
      webviewContextMenus.handlersForId(instanceId, id)[id] = onclick;
    }
  });

  apiFunctions.setCustomCallback('contextMenusUpdate',
                                 function(name, request, response) {
    if (chrome.runtime.lastError) {
      return;
    }
    var instanceId = request.args[0];
    var id = request.args[1];
    if (request.args[2].onclick) {
      webviewContextMenus.handlersForId(instanceId, id)[id] =
          request.args[2].onclick;
    }
  });

  apiFunctions.setCustomCallback('contextMenusRemove',
                                  function(name, request, response) {
    if (chrome.runtime.lastError) {
      return;
    }
    var instanceId = request.args[0];
    var id = request.args[1];
    delete webviewContextMenus.handlersForId(instanceId, id)[id];
  });

  apiFunctions.setCustomCallback('contextMenusRemoveAll',
                                 function(name, request, response) {
    if (chrome.runtime.lastError) {
      return;
    }
    var instanceId = request.args[0];
    webviewContextMenus.stringIdHandlers[instanceId] = {};
    webviewContextMenus.generatedIdHandlers[instanceId] = {};
  });

});

exports.WebView = binding.generate();


text:
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsMathUtils.h"

#include "gfxQuartzNativeDrawing.h"
#include "gfxQuartzSurface.h"
#include "cairo-quartz.h"
// see cairo-quartz-surface.c for the complete list of these
enum {
    kPrivateCGCompositeSourceOver = 2
};

// private Quartz routine needed here
extern "C" {
    CG_EXTERN void CGContextSetCompositeOperation(CGContextRef, int);
}

gfxQuartzNativeDrawing::gfxQuartzNativeDrawing(gfxContext* ctx,
                                               const gfxRect& nativeRect,
                                               gfxFloat aBackingScale)
    : mContext(ctx), mNativeRect(nativeRect), mBackingScale(aBackingScale)
{
    mNativeRect.RoundOut();
}

CGContextRef
gfxQuartzNativeDrawing::BeginNativeDrawing()
{
    NS_ASSERTION(!mQuartzSurface, "BeginNativeDrawing called when drawing already in progress");

    gfxPoint deviceOffset;
    nsRefPtr<gfxASurface> surf = mContext->CurrentSurface(&deviceOffset.x, &deviceOffset.y);
    if (!surf || surf->CairoStatus())
        return nullptr;

    // if this is a native Quartz surface, we don't have to redirect
    // rendering to our own CGContextRef; in most cases, we are able to
    // use the CGContextRef from the surface directly.  we can extend
    // this to support offscreen drawing fairly easily in the future.
    if (surf->GetType() == gfxASurface::SurfaceTypeQuartz &&
        (surf->GetContentType() == gfxASurface::CONTENT_COLOR ||
         (surf->GetContentType() == gfxASurface::CONTENT_COLOR_ALPHA))) {
        mQuartzSurface = static_cast<gfxQuartzSurface*>(surf.get());
        mSurfaceContext = mContext;

        // grab the CGContextRef
        mCGContext = cairo_quartz_get_cg_context_with_clip(mSurfaceContext->GetCairo());
        if (!mCGContext)
            return nullptr;

        gfxMatrix m = mContext->CurrentMatrix();
        CGContextTranslateCTM(mCGContext, deviceOffset.x, deviceOffset.y);

        // I -think- that this context will always have an identity
        // transform (since we don't maintain a transform on it in
        // cairo-land, and instead push/pop as needed)

        gfxFloat x0 = m.x0;
        gfxFloat y0 = m.y0;

        // We round x0/y0 if we don't have a scale, because otherwise things get
        // rendered badly
        // XXX how should we be rounding x0/y0?
        if (!m.HasNonTranslationOrFlip()) {
            x0 = floor(x0 + 0.5);
            y0 = floor(y0 + 0.5);
        }

        CGContextConcatCTM(mCGContext, CGAffineTransformMake(m.xx, m.yx,
                                                             m.xy, m.yy,
                                                             x0, y0));

        // bug 382049 - need to explicity set the composite operation to sourceOver
        CGContextSetCompositeOperation(mCGContext, kPrivateCGCompositeSourceOver);
    } else {
        nsIntSize backingSize(NSToIntFloor(mNativeRect.width * mBackingScale),
                              NSToIntFloor(mNativeRect.height * mBackingScale));
        mQuartzSurface = new gfxQuartzSurface(backingSize,
                                              gfxASurface::ImageFormatARGB32);
        if (mQuartzSurface->CairoStatus())
            return nullptr;
        mSurfaceContext = new gfxContext(mQuartzSurface);

        // grab the CGContextRef
        mCGContext = cairo_quartz_get_cg_context_with_clip(mSurfaceContext->GetCairo());
        CGContextScaleCTM(mCGContext, mBackingScale, mBackingScale);
        CGContextTranslateCTM(mCGContext, -mNativeRect.X(), -mNativeRect.Y());
    }

    return mCGContext;
}

void
gfxQuartzNativeDrawing::EndNativeDrawing()
{
    NS_ASSERTION(mQuartzSurface, "EndNativeDrawing called without BeginNativeDrawing");

    cairo_quartz_finish_cg_context_with_clip(mSurfaceContext->GetCairo());
    mQuartzSurface->MarkDirty();
    if (mSurfaceContext != mContext) {
        gfxContextMatrixAutoSaveRestore save(mContext);

        // Copy back to destination
        mContext->Translate(mNativeRect.TopLeft());
        mContext->Scale(1.0f / mBackingScale, 1.0f / mBackingScale);
        mContext->DrawSurface(mQuartzSurface, mQuartzSurface->GetSize());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.anji.tournament.test;

import com.anji.tournament.IteratedPlayer;

/**
 * @author Philip Tucker
 */
public class TestIteratedPlayer extends TestPlayer implements IteratedPlayer {

private int iterationsRemaining = 0;

/**
 * @param aName
 */
public TestIteratedPlayer( String aName ) {
	super( aName );
}

/**
 * @see com.anji.tournament.IteratedPlayer#reset(int)
 */
public void reset( int aNumIterations ) {
	super.reset();
	iterationsRemaining = aNumIterations;
}

/**
 * play game
 */
public void play() {
	super.play();
	--iterationsRemaining;
}

/**
 * @return iterations remaining
 */
public int getIterationsRemaining() {
	return iterationsRemaining;
}
}


text:
import {h, Component} 					from 'preact/preact';
//import Shallow			 				from 'shallow/shallow';

import UIIcon							from 'com/ui/icon/icon';
import UIImage							from 'com/ui/image/image';
import UIButton							from 'com/ui/button/button';
import UIDropdown						from 'com/ui/dropdown/dropdown';

import $User							from 'shrub/js/user/user';

export default class ViewBarUser extends Component {
	constructor( props ) {
		super(props);

		this.onLogout = this.onLogout.bind(this);
	}

	onLogout() {
		$User.Logout()
		.then(r => {
			location.reload();
		});
	}

	render( props ) {
		let {user} = props;

		// Bail if we don't have a valid user
		if ( !user )
			return null;

		// Construct avatar details
		let UserURL = '/users/'+user.slug+'/';
		let UserAvatar = '//'+STATIC_DOMAIN+'/other/dummy/user64.png';
		if ( user.meta && user.meta.avatar )
			UserAvatar = '//'+STATIC_DOMAIN+user.meta.avatar+".40x40.fit.png";

		return (
			<UIDropdown class="-user" right>
				<UIImage alt="Your Profile" src={UserAvatar} block />
				<UIButton href={UserURL}><UIIcon>user</UIIcon>My Profile</UIButton>
				<UIButton href={UserURL+'games'}><UIIcon>gamepad</UIIcon>My Games</UIButton>

				<UIButton onclick={this.onLogout}><UIIcon>logout</UIIcon>Logout</UIButton>
			</UIDropdown>
		);
	}
}


text:
#include <windows.h>

#include <gl/gl.h>

#include <stdio.h>

#include "Settings.h"
#include "Text.h"

#define FONT_NAME "Arial"
#define FONT_SIZE 16
#define FONT_BOLD true
#define FONT_ITALIC false
#define FONT_UNDERLINE false
#define FONT_STRIKEOUT false
#define FONT_THICKNESS 0.1f

#define ALLOW_FONT_SCALING false
#define FT_FONT_SIZE_THRESHOLD 32

#define FREETYPE_DLL "freetype6.dll"

bool CText::FreeType_loaded=false;
HMODULE CText::FreeType=NULL;
ptr_FT_Init_FreeType CText::pFT_Init_FreeType=NULL;
ptr_FT_Done_FreeType CText::pFT_Done_FreeType=NULL;
ptr_FT_New_Face CText::pFT_New_Face=NULL;
ptr_FT_Done_Face CText::pFT_Done_Face=NULL;
ptr_FT_Set_Char_Size CText::pFT_Set_Char_Size=NULL;
ptr_FT_Get_Char_Index CText::pFT_Get_Char_Index=NULL;
ptr_FT_Load_Glyph CText::pFT_Load_Glyph=NULL;
ptr_FT_Done_Glyph CText::pFT_Done_Glyph=NULL;
ptr_FT_Get_Glyph CText::pFT_Get_Glyph=NULL;
ptr_FT_Glyph_To_Bitmap CText::pFT_Glyph_To_Bitmap=NULL;

CText::CText()
{
	Construct();
}

CText::~CText()
{
	Free();
}

void CText::Construct()
{
	ZeroMemory(FT_tex,sizeof(FT_tex));
	ZeroMemory(charsize,sizeof(charsize));
	charheight=0.0f;
	listbase=0;
	sizescale=1.0f;
	UseFT=false;
	loaded=false;
}

bool CText::Init()
{
#define LoadFTFunc(ptr, type, name) (FreeType_loaded&=(ptr=(type)GetProcAddress(FreeType,name))!=NULL)

	if (FreeType_loaded)
		return true;

	SetDllDirectory(CSettings::DataDir);
	FreeType=LoadLibrary(FREETYPE_DLL);
	SetDllDirectory(NULL);

	if (FreeType)
	{
		FreeType_loaded=true;
		LoadFTFunc(pFT_Init_FreeType,ptr_FT_Init_FreeType,"FT_Init_FreeType");
		LoadFTFunc(pFT_Done_FreeType,ptr_FT_Done_FreeType,"FT_Done_FreeType");
		LoadFTFunc(pFT_New_Face,ptr_FT_New_Face,"FT_New_Face");
		LoadFTFunc(pFT_Done_Face,ptr_FT_Done_Face,"FT_Done_Face");
		LoadFTFunc(pFT_Set_Char_Size,ptr_FT_Set_Char_Size,"FT_Set_Char_Size");
		LoadFTFunc(pFT_Get_Char_Index,ptr_FT_Get_Char_Index,"FT_Get_Char_Index");
		LoadFTFunc(pFT_Load_Glyph,ptr_FT_Load_Glyph,"FT_Load_Glyph");
		LoadFTFunc(pFT_Done_Glyph,ptr_FT_Done_Glyph,"FT_Done_Glyph");
		LoadFTFunc(pFT_Get_Glyph,ptr_FT_Get_Glyph,"FT_Get_Glyph");
		LoadFTFunc(pFT_Glyph_To_Bitmap,ptr_FT_Glyph_To_Bitmap,"FT_Glyph_To_Bitmap");
	}

	return FreeType_loaded;
}

void CText::Shutdown()
{
	FreeType_loaded=false;
	if (FreeType)
	{
		FreeLibrary(FreeType);
		FreeType=NULL;
	}
}

void CText::Free()
{
	if (glIsList(listbase))
		glDeleteLists(listbase,NUM_CHARS);
	if (UseFT)
	{
		glDeleteTextures(NUM_CHARS,(GLuint *)FT_tex);
	}
	Construct();
}

bool CText::BuildOutlineFont(const char *name, int size, bool bold, bool italic, bool underline, bool strikeout, float thickness)
{
	if (loaded)
	{
		Free();
	}

	UseFT=false;

	GLYPHMETRICSFLOAT gmf[NUM_CHARS];
	HFONT font;
	listbase=glGenLists(NUM_CHARS);
	if (listbase)
	{
		HDC hDC=GetDC(CSettings::hwnd);
//		size=-MulDiv(size,GetDeviceCaps(hDC,LOGPIXELSY),72);
		size=-size; // size dont depend on system font size
		if (hDC)
		{
			font=CreateFont(size,							// Height Of Font
							0,								// Width Of Font
							0,								// Angle Of Escapement
							0,								// Orientation Angle
							bold?FW_BOLD:FW_NORMAL,			// Font Weight
							italic,							// Italic
							underline,						// Underline
							strikeout,						// Strikeout
							ANSI_CHARSET,					// Character Set Identifier
							OUT_TT_PRECIS,					// Output Precision
							CLIP_DEFAULT_PRECIS,			// Clipping Precision
							ANTIALIASED_QUALITY,			// Output Quality
							FF_DONTCARE|DEFAULT_PITCH,		// Family And Pitch
							name);							// Font Name
			if (font)
			{
				HGDIOBJ OldObj=SelectObject(hDC,font);
				loaded=(wglUseFontOutlines(	hDC,							// Select The Current DC
											0,								// Starting Character
											NUM_CHARS,						// Number Of Display Lists To Build
											listbase,						// Starting Display Lists
											0.0f,							// Deviation From The True Outlines
											thickness,						// Font Thickness In The Z Direction
											WGL_FONT_POLYGONS,				// Use Polygons, Not Lines
											gmf)!=0);						// Address Of Buffer To Recieve Data
				if (loaded)
				{
					for (int i=0;i<NUM_CHARS;i++)
					{
						charsize[i][0]=gmf[i].gmfCellIncX;
						charsize[i][1]=gmf[i].gmfCellIncY;
					}
					charheight=(float)size;
				}
				SelectObject(hDC,OldObj);
				DeleteObject(font);
			}
			ReleaseDC(CSettings::hwnd,hDC);
		}
	}

	if (!loaded)
	{
		Free();
	}

	return loaded;
}

bool CText::BuildFTFont(const char *name, int size)
{
	if (!FreeType_loaded)
		return false;

	if (loaded)
	{
		Free();
	}

	UseFT=true;

	bool smallfont=(size<FT_FONT_SIZE_THRESHOLD && ALLOW_FONT_SCALING==true);
	if (smallfont)
	{
		sizescale=(float)((double)size/(double)FT_FONT_SIZE_THRESHOLD);
		size=FT_FONT_SIZE_THRESHOLD;
	}

	char fontpath[MAX_PATH];
	GetWindowsDirectory(fontpath,sizeof(fontpath));
	strcat(fontpath,"\\FONTS\\");
	strcat(fontpath,name);
	strcat(fontpath,".TTF");

	FT_Library library;
	if (pFT_Init_FreeType(&library))
		return false;

	FT_Face face;
	if (pFT_New_Face(library,fontpath,0,&face))
	{
		pFT_Done_FreeType(library);
		return false;
	}
	pFT_Set_Char_Size(face,size<<6,size<<6,96,96);

	listbase=glGenLists(NUM_CHARS);
	glGenTextures(NUM_CHARS,(GLuint*)FT_tex);

	loaded=true;
	for(int i=0;i<NUM_CHARS;i++)
	{
		if (!MakeFTChar(face, i, listbase, FT_tex, charsize, smallfont))
		{
			loaded=false;
			break;
		}
	}

	pFT_Done_Face(face);
	pFT_Done_FreeType(library);

	if (loaded)
	{
		charheight=(float)size;
	}
	else
	{
		Free();
	}

	return loaded;
}

int CText::next_p2(int a)
{
	int rval=2;
	while (rval<a) rval<<=1;
	return rval;
}

bool CText::MakeFTChar(FT_Face face, char ch, int list_base, int textures[NUM_CHARS], float charsizes[NUM_CHARS][2], bool mipmaps)
{
	const int ich = ch;

	if(pFT_Load_Glyph(face,pFT_Get_Char_Index(face,ich),FT_LOAD_DEFAULT))
		return false;

	FT_Glyph glyph;
	if(pFT_Get_Glyph(face->glyph,&glyph))
		return false;

	bool empty=(pFT_Glyph_To_Bitmap(&glyph,FT_RENDER_MODE_NORMAL,0,1)!=0);
	FT_BitmapGlyph bitmap_glyph=(FT_BitmapGlyph)glyph;
	FT_Bitmap& bitmap=bitmap_glyph->bitmap;

	int width=1, height=1;
	if (!empty)
	{
		width=next_p2(bitmap.width);
		height=next_p2(bitmap.rows);

		unsigned char *expanded_data=(unsigned char *)malloc(2*width*height);
		if (!expanded_data)
		{
			pFT_Done_Glyph(glyph);
			return false;
		}

		for(int j=0; j<height; j++)
		{
			for(int i=0; i<width; i++)
			{
				expanded_data[2*(i+j*width)]=255;
				expanded_data[2*(i+j*width)+1] =
					(i>=bitmap.width || j>=bitmap.rows) ?
					0 : bitmap.buffer[i + bitmap.width*j];
			}
		}

		glBindTexture(GL_TEXTURE_2D, textures[ich]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		if (mipmaps)
		{
			glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST_MIPMAP_NEAREST);
			if (gluBuild2DMipmaps(GL_TEXTURE_2D,2,width,height,GL_LUMINANCE_ALPHA,GL_UNSIGNED_BYTE,expanded_data)!=0)
			{
				free(expanded_data);
				pFT_Done_Glyph(glyph);
				return false;
			}
		}
		else
		{
			glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
			glTexImage2D(	GL_TEXTURE_2D,
							0,
							GL_RGBA,
							width,
							height,
							0,
							GL_LUMINANCE_ALPHA,
							GL_UNSIGNED_BYTE,
							expanded_data);
		}

		free(expanded_data);
	}

	glNewList(list_base+ich,GL_COMPILE);
	{
		if (!empty)
		{
			glBindTexture(GL_TEXTURE_2D,textures[ich]);
			glPushMatrix();

			glTranslatef((float)bitmap_glyph->left, (float)(bitmap_glyph->top-bitmap.rows),0);

			float	x= (float)bitmap.width / (float)width,
					y= (float)bitmap.rows / (float)height;

			glBegin(GL_QUADS);
			{
				glNormal3f(0,0,1);
				glTexCoord2f(0,0); glVertex2f(0,(float)bitmap.rows);
				glTexCoord2f(x,0); glVertex2f((float)bitmap.width, (float)bitmap.rows);
				glTexCoord2f(x,y); glVertex2f((float)bitmap.width, 0);
				glTexCoord2f(0,y); glVertex2f(0,0);
			}
			glEnd();

			glPopMatrix();
		}

		glTranslatef((float)(face->glyph->advance.x>>6), 0, 0);
	}
	glEndList();

	charsizes[ich][0]=((float)face->glyph->advance.x/64.0f);
	charsizes[ich][1]=((float)face->size->metrics.height/64.0f);

	pFT_Done_Glyph(glyph);

	return true;
}

void CText::Print(const char *fmt, ...)					// Custom GL "Print" Routine
{
	char text[256];										// Holds Our String
	va_list ap;											// Pointer To List Of Arguments

	if (!loaded || !fmt)								// If There's No Text
		return;											// Do Nothing

	va_start(ap, fmt);									// Parses The String For Variables
		vsprintf(text, fmt, ap);						// And Converts Symbols To Actual Numbers
	va_end(ap);											// Results Are Stored In Text

	glPushAttrib(GL_LIST_BIT);							// Pushes The Display List Bits
	glListBase(listbase);								// Sets The Base Character to 0
	if (sizescale!=1.0f)
		glScalef(sizescale,sizescale,sizescale);
	glCallLists(strlen(text), GL_UNSIGNED_BYTE, text);	// Draws The Display List Text
	if (sizescale!=1.0f)
		glScalef(1.0f/sizescale,1.0f/sizescale,1.0f/sizescale);
	glPopAttrib();										// Pops The Display List Bits
}

bool CText::GetTextSize(const char *text, float *width, float *height)
{
	if (!loaded || !text || (!width && !height))
		return false;

	float w=0.0f;
	float h=charsize[' '][1];
	for (const char *c=text; *c; c++)
	{
		w+=charsize[(int)*c][0];
		h=max(h,charsize[(int)*c][1]);
	}

	if (width) *width=w*sizescale;
	if (height) *height=h*sizescale;

	return true;
}


text:
@implementation TUNetworkConfig

+ (TUNetworkConfig *)config {
    static TUNetworkConfig *config = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        config = [[self alloc] init];
    });
    return config;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self reset];
    }
    return self;
}

- (void)reset {
    _publicParameters = @{};
    _userId = @"0";
}

- (NSString *)configUserId {
    return self.userId;
}

/// 请求的protocol
- (NSString *)requestURLProtocol {
    return @"http://";
}

/// 请求的Host
- (NSString *)requestHost {
    return @"";
}

/// 请求的超时时间
- (NSTimeInterval)requestTimeoutInterval {
    return 60;
}

/// 请求的安全选项
- (AFSecurityPolicy *)requestSecurityPolicy {
    return [AFSecurityPolicy defaultPolicy];
}

/// Http请求的方法
- (TURequestMethod)requestMethod {
    return TURequestMethodGet;
}

/// 请求的SerializerType
- (TURequestSerializerType)requestSerializerType {
    return TURequestSerializerTypeHTTP;
}

- (NSDictionary *)requestPublicParameters {
    return self.publicParameters;
}

/// 请求公参的位置
- (TURequestPublicParametersType)requestPublicParametersType {
    return TURequestPublicParametersTypeBody;
}

/// 请求校验
- (BOOL)requestVerifyResult:(id)result {
    if (result) {
        return YES;
    }
    return NO;
}

@end


text:
/**
 * Created by stanley on 11/27/14.
 */

var tags;
var tags_template = '

';

$(document.body).on('click', '#skills_add_link', function(e) {
    e.preventDefault();
    $(this).css('visibility', 'hidden');

    var $tags = $('#current-tag-list');
    var skills = $tags.attr('name').split(',');

    $tags.css('display', 'none');

    if (in_progress == 1)
        return false;
    in_progress = 1;
    var $skills_elem = $('#skills');
    $skills_elem.load('skills', function() {
        if (skills[0] == "")
            tags = skills_tags('#my-tag-list', false);
        else
            tags = skills_tags('#my-tag-list', false, skills);
        $('#update_skills_btn').on('click', function() {
            e.preventDefault();
            var sorted_tags = tags.getTags().sort();
            var $info_msg = $('#info-msg-skills');

            var data = {
                skills: sorted_tags.join(",")
            };

            $.ajax({
                type: 'POST',
                url: 'skills',
                data: data,
                success: function(msg) {
                    if (msg.successful) {
                        $info_msg.css('color', 'green');
                        $info_msg.html(' Update Successful').fadeIn().delay(1500).fadeOut();
                        $('#skills_add_link').fadeOut(0).delay(2300).fadeIn();

                        $tags.remove(); // remove current tags (editable version)
                        $('#tag_anchor').after(function() {
                            return Mustache.render(tags_template, data);
                        });
                        skills_tags('#current-tag-list', true, sorted_tags);
                        if (sorted_tags.join(",") == '')
                            $('#current-tag-list').css('display', 'none');
                    }
                    else {
                        $info_msg.css('color', 'darkred');
                        $info_msg.html(' Something went wrong :|').fadeIn().delay(1500).fadeOut();
                        $('#skills_panel').remove();
                        $('#current-tag-list').css('display', 'block');
                    }
                    $skills_elem.html("");
                    in_progress = 0;
                },
                error: function(msg) {
                    $info_msg.css('color', 'darkred');
                    $info_msg.html(' Something went wrong :|').fadeIn().delay(1500).fadeOut();
                    $skills_elem.html("");
                    $('#skills_panel').remove();
                    $('#current-tag-list').css('display', 'block');
                    in_progress = 0;
                }
            });
        });
    });
});

function remove_skills_add_panel() {
    in_progress = 0;
    $('#skills_panel').remove();
    $('#current-tag-list').css('display', 'block');
}


text:
Evolutionary
============

*Evolutionary.jl* is a Julia package for evolutionary and genetic algorithms. It provides implementation of :math:`(\mu/\rho \; \stackrel{+}{,} \;\lambda)`-Evolution Strategy, :math:`(\mu/\mu_I, \;\lambda)`-Covariance Matrix Adaptation Evolution Strategy and Genetic Algorithms, as well as a rich set of mutation, recombination, crossover and selection functions.

**Contents:**

.. toctree::
   :maxdepth: 2

   algo/index.rst
   oper/index.rst


text:
            <ng-include src="'templates/jobs.html'"></ng-include>

            <ng-include src="'templates/log.html'"></ng-include>

        <button class="sidepane-button" ng-click="switchToTab('jobs')">Jobs</button>
        <button class="sidepane-button" ng-click="switchToTab('log')">Log</button>


text:
@interface TapCounter : NSObject

@end


text:
`LiveAnnouncer` is used to announce messages for screen-reader users using an `aria-live` region.
See [the W3C's WAI-ARIA](https://www.w3.org/TR/wai-aria/states_and_properties#aria-live)
for more information on aria-live regions.

#### Methods

##### `announce(message: string, politeness?: 'off' | 'polite' | 'assertive'): void`
Announce the given message via aria-live region. The politeness argument determines the
`aria-live` attribute on the announcer element, defaulting to 'polite'.

#### Examples
The LiveAnnouncer is injected into a component:
```ts
@Component({
  selector: 'my-component'
  providers: [LiveAnnouncer]
})
export class MyComponent {

  constructor(liveAnnouncer: LiveAnnouncer) {
    liveAnnouncer.announce("Hey Google");
  }
}
```


text:
package ysoserial.payloads.util;

import java.util.concurrent.Callable;

import ysoserial.Deserializer;
import ysoserial.Serializer;
import static ysoserial.Deserializer.deserialize;
import static ysoserial.Serializer.serialize;
import ysoserial.payloads.ObjectPayload;
import ysoserial.payloads.ObjectPayload.Utils;
import ysoserial.secmgr.ExecCheckingSecurityManager;

/*
 * utility class for running exploits locally from command line
 */
@SuppressWarnings("unused")
public class PayloadRunner {

    public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception {
		// ensure payload generation doesn't throw an exception
		byte[] serialized = new ExecCheckingSecurityManager().callWrapped(new Callable<byte[]>(){
			public byte[] call() throws Exception {
				final String command = args.length > 0 && args[0] != null ? args[0] : getDefaultTestCmd();

				System.out.println("generating payload object(s) for command: '" + command + "'");

				ObjectPayload<?> payload = clazz.newInstance();
                final Object objBefore = payload.getObject(command);

				System.out.println("serializing payload");
				byte[] ser = Serializer.serialize(objBefore);
				Utils.releasePayload(payload, objBefore);
                return ser;
		}});

		try {
			System.out.println("deserializing payload");
			final Object objAfter = Deserializer.deserialize(serialized);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

    private static String getDefaultTestCmd() {
	    return getFirstExistingFile(
	        "C:\\Windows\\System32\\calc.exe",
            "/Applications/Calculator.app/Contents/MacOS/Calculator",
            "/usr/bin/gnome-calculator",
            "/usr/bin/kcalc"
        );
    }

    private static String getFirstExistingFile(String ... files) {
        return "calc.exe";
//        for (String path : files) {
//            if (new File(path).exists()) {
//                return path;
//            }
//        }
//        throw new UnsupportedOperationException("no known test executable");
    }
}


text:
#!/usr/bin/js

Extension.load("system");
Extension.load("stream");

system.stdout.writeln("stream reading test for files");

/* Actual test */
var s = new Stream("stdin");
var buf = s.readUntilEOF();
system.stdout.writeln("readed: '" + buf + "'");


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

<title>Triangle</title>
<meta name="date" content="2013-03-07">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.tyrlib2.graphics.renderables

Class Triangle

java.lang.Object

com.tyrlib2.graphics.scene.SceneObject

com.tyrlib2.graphics.scene.BoundedSceneObject

com.tyrlib2.graphics.renderer.BoundedRenderable

com.tyrlib2.graphics.renderer.Renderable

com.tyrlib2.graphics.renderables.Triangle

All Implemented Interfaces:

IRenderable

public class Triangle
extends Renderable

Field Summary

Fields

Modifier and Type
Field and Description

static short[]
DRAW_ORDER

Constructor Summary

Constructors

Constructor and Description

Triangle(Material material,
        Vector3[] points)

Method Summary

Methods inherited from class com.tyrlib2.graphics.renderer.Renderable

attachTo, createShallowCopy, getMaterial, getMesh, init, render, setMaterial, setMesh

Methods inherited from class com.tyrlib2.graphics.renderer.BoundedRenderable

getBoundingBox, getUntransformedBoundingBox, setBoundingBoxVisible

Methods inherited from class com.tyrlib2.graphics.scene.BoundedSceneObject

detach, isDity, onTransformed, setClean

Methods inherited from class com.tyrlib2.graphics.scene.SceneObject

getAbsolutePos, getModelMatrix, getParent, getRelativePos

Methods inherited from class java.lang.Object

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

Field Detail

DRAW_ORDER

public static final short[] DRAW_ORDER

Constructor Detail

Triangle

public Triangle(Material material,
        Vector3[] points)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package memcachedreceiver

import (
	"context"
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
	testcontainers "github.com/testcontainers/testcontainers-go"
	"github.com/testcontainers/testcontainers-go/wait"
	"go.opentelemetry.io/collector/component/componenttest"
	"go.opentelemetry.io/collector/consumer/consumertest"
	"go.opentelemetry.io/collector/pdata/pmetric"

	"github.com/open-telemetry/opentelemetry-collector-contrib/internal/scrapertest"
)

func TestIntegration(t *testing.T) {
	ctx := context.Background()
	req := testcontainers.ContainerRequest{
		Image:        "docker.io/library/memcached:1.6-alpine",
		ExposedPorts: []string{"11211/tcp"},
		WaitingFor:   wait.ForListeningPort("11211/tcp"),
	}
	container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
		ContainerRequest: req,
		Started:          true,
	})
	require.Nil(t, err)

	mappedPort, err := container.MappedPort(ctx, "11211")
	require.Nil(t, err)

	hostIP, err := container.Host(ctx)
	require.Nil(t, err)

	f := NewFactory()
	cfg := f.CreateDefaultConfig().(*Config)
	cfg.Endpoint = fmt.Sprintf("%s:%s", hostIP, mappedPort.Port())

	consumer := new(consumertest.MetricsSink)

	rcvr, err := f.CreateMetricsReceiver(context.Background(), componenttest.NewNopReceiverCreateSettings(), cfg, consumer)
	require.NoError(t, err, "failed creating metrics receiver")
	require.NoError(t, rcvr.Start(context.Background(), componenttest.NewNopHost()))

	require.Eventuallyf(t, func() bool {
		return len(consumer.AllMetrics()) > 0
	}, 15*time.Second, 1*time.Second, "failed to receive at least 5 metrics")
	require.NoError(t, rcvr.Shutdown(context.Background()))

	actualMetrics := consumer.AllMetrics()[0]

	expectedFileBytes, err := os.ReadFile("./testdata/expected_metrics/test_scraper/expected.json")
	require.NoError(t, err)
	unmarshaller := &pmetric.JSONUnmarshaler{}
	expectedMetrics, err := unmarshaller.UnmarshalMetrics(expectedFileBytes)
	require.NoError(t, err)

	require.NoError(t, scrapertest.CompareMetrics(expectedMetrics, actualMetrics, scrapertest.IgnoreMetricValues()))
}


text:
//******************************************
//  Copyright (C) 2014-2015 Charles Nurse  *
//                                         *
//  Licensed under MIT License             *
//  (see included LICENSE)                 *
//                                         *
// *****************************************

// Influenced by http://sameproblemmorecode.blogspot.nl/2013/07/petapoco-as-its-meant-to-be-with.html
// https://github.com/luuksommers/PetaPoco

using System;
using PetaPoco;

namespace FamilyTreeProject.Dnn.Data
{
    public class FluentColumnMap
    {
        public ColumnInfo ColumnInfo { get; set; }
        public Func<object, object> FromDbConverter { get; set; }
        public Func<object, object> ToDbConverter { get; set; }

        public FluentColumnMap() { }
        public FluentColumnMap(ColumnInfo columnInfo) : this(columnInfo, null) { }
        public FluentColumnMap(ColumnInfo columnInfo, Func<object, object> fromDbConverter) : this(columnInfo, fromDbConverter, null) { }
        public FluentColumnMap(ColumnInfo columnInfo, Func<object, object> fromDbConverter, Func<object, object> toDbConverter)
        {
            ColumnInfo = columnInfo;
            FromDbConverter = fromDbConverter;
            ToDbConverter = toDbConverter;
        }
    }
}


text:
'use strict';

class Page {
    constructor(name, pathpattern) {
        this._name = name;
        this._dom = document.querySelector('#' + name);
        this._pathpattern = pathpattern;
    }

    in (data) {
        return new Promise((resolve, reject) => {
            const onTransitionEnd = () => {
                this._dom.removeEventListener('transitionend', onTransitionEnd);
                resolve();
            };

            this._dom.classList.add('visible');
            this._dom.addEventListener('transitionend', onTransitionEnd);
        });
    }

    out(data) {
        return new Promise((resolve, reject) => {
            const onTransitionEnd = () => {
                this._dom.removeEventListener('transitionend', onTransitionEnd);
                resolve();
            };

            this._dom.classList.remove('visible');
            this._dom.addEventListener('transitionend', onTransitionEnd);
        });
    }

    update(data) {
        console.log(data);
        return Promise.resolve();
    }

}


text:
// <copyright file="Constructor_Should.cs" company="YAGNI">
// All rights reserved.
// </copyright>
// <summary>Holds unit tests of LogType entity model constructor.</summary>

using System.Collections.Generic;
using LibrarySystem.Models.Logs;
using NUnit.Framework;

namespace LibrarySystem.Models.UnitTests.Logs.LogTests
{
    [TestFixture]
    public class Constructor_Should
    {
        [Test]
        [Category("Models.Logs.LogType.Constructor")]
        public void InstantiateLogType_WhenNoArgumentsArePassed()
        {
            // Arrange
            // Act
            var logType = new LogType();

            // Assert
            Assert.That(logType, Is.InstanceOf<LogType>());
        }

        [Test]
        [Category("Models.Logs.LogType.Constructor")]
        public void InstantiateLogTypeWithIdProperty_WhenNoArgumentsArePassed()
        {
            // Arrange
            // Act
            var logType = new LogType();

            // Assert
            Assert.That(logType, Has.Property("Id"));
        }

        [Test]
        [Category("Models.Logs.LogType.Constructor")]
        public void InstantiateLogTypeWithNameProperty_WhenNoArgumentsArePassed()
        {
            // Arrange
            // Act
            var logType = new LogType();

            // Assert
            Assert.That(logType, Has.Property("Name"));
        }

        [Test]
        [Category("Models.Logs.LogType.Constructor")]
        public void InstantiateLogTypeWithLogsProperty_WhenNoArgumentsArePassed()
        {
            // Arrange
            // Act
            var logType = new LogType();

            // Assert
            Assert.That(logType, Has.Property("Logs"));
        }

        [Test]
        [Category("Models.Logs.LogType.Constructor")]
        public void InstantiateLogsCollection_WhenNoArgumentsArePassed()
        {
            // Arrange
            // Act
            var logType = new LogType();

            // Assert
            Assert.That(logType.Logs.Count, Is.Zero);
            Assert.That(logType.Logs, Is.TypeOf<HashSet<Log>>());
        }
    }
}


text:
"""
Copyright (c) 2016 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, unicode_literals

try:
    # py2
    from ConfigParser import ConfigParser
    # Although io.StringIO is available in python2, it
    # always expects unicode during write. Since
    # ConfigParser.ConfigParser does not support
    # writing unicode, io cannot be used.
    from StringIO import StringIO
except ImportError:
    # py3
    from configparser import ConfigParser
    from io import StringIO

from textwrap import dedent

import json
import re
import os

from atomic_reactor.constants import DEFAULT_DOWNLOAD_BLOCK_SIZE, PLUGIN_ADD_FILESYSTEM_KEY
from atomic_reactor.plugin import PreBuildPlugin, BuildCanceledException
from atomic_reactor.plugins.exit_remove_built_image import defer_removal
from atomic_reactor.koji_util import create_koji_session, TaskWatcher, stream_task_output
from atomic_reactor.util import get_retrying_requests_session
from atomic_reactor import util

class AddFilesystemPlugin(PreBuildPlugin):
    """
    Creates a base image by using a filesystem generated through Koji

    Submits an image build task to Koji based on image build
    configuration file to create the filesystem to be used in
    creating the base image:
    https://docs.pagure.org/koji/image_build/

    Once image build task is complete the tarball is downloaded and
    it's imported into docker. This creates a new image. The existing
    FROM instruction value is replaced with the ID of this new image.

    The "FROM" instruction should be in the following format:
        FROM koji/image-build[:image-build-conf]
    Where image-build-conf is the file name of the image build
    configuration to be used. If omitted, image-build.conf is used.
    This file is expected to be in the same folder as the Dockerfile.

    Runs as a pre build plugin in order to properly adjust base image.
    """

    key = PLUGIN_ADD_FILESYSTEM_KEY
    is_allowed_to_fail = False

    DEFAULT_IMAGE_BUILD_CONF = dedent('''\
        [image-build]
        name = default-name
        arches = x86_64
        format = docker
        disk_size = 10

        install_tree = {install_tree}
        repo = {repo}

        ksurl = {ksurl}
        kickstart = kickstart.ks

        [factory-parameters]
        create_docker_metadata = False
        ''')

    def __init__(self, tasker, workflow, koji_hub,
                 koji_proxyuser=None, koji_ssl_certs_dir=None,
                 koji_krb_principal=None, koji_krb_keytab=None,
                 from_task_id=None, poll_interval=5,
                 blocksize=DEFAULT_DOWNLOAD_BLOCK_SIZE,
                 repos=None, architectures=None,
                 architecture=None):
        """
        :param tasker: DockerTasker instance
        :param workflow: DockerBuildWorkflow instance
        :param koji_hub: str, koji hub (xmlrpc)
        :param koji_proxyuser: str, proxy user
        :param koji_ssl_certs_dir: str, path to "cert", "ca", and "serverca"
        :param koji_krb_principal: str, name of Kerberos principal
        :param koji_krb_keytab: str, Kerberos keytab
        :param from_task_id: int, use existing Koji image task ID
        :param poll_interval: int, seconds between polling Koji while waiting
                              for task completion
        :param blocksize: int, chunk size for streaming files from koji
        :param repos: list<str>: list of yum repo URLs to be used during
                      base filesystem creation. First value will also
                      be used as install_tree. Only baseurl value is used
                      from each repo file.
        :param architectures: list<str>, list of arches to build on (orchestrator)
        :param architecture: str, arch to build on (worker)
        """
        # call parent constructor
        super(AddFilesystemPlugin, self).__init__(tasker, workflow)
        self.koji_hub = koji_hub
        self.koji_auth_info = {
            'proxyuser': koji_proxyuser,
            'ssl_certs_dir': koji_ssl_certs_dir,
            'krb_principal': koji_krb_principal,
            'krb_keytab': koji_krb_keytab,
        }
        self.from_task_id = from_task_id
        self.poll_interval = poll_interval
        self.blocksize = blocksize
        self.repos = repos or []
        self.architectures = architectures
        self.is_orchestrator = True if self.architectures else False
        self.architecture = architecture
        self.scratch = util.is_scratch_build()

    def is_image_build_type(self, base_image):
        return base_image.strip().lower() == 'koji/image-build'

    def extract_base_url(self, repo_url):
        session = get_retrying_requests_session()
        response = session.get(repo_url)
        response.raise_for_status()
        repo = ConfigParser()
        repo.readfp(StringIO(response.text))

        return [repo.get(section, 'baseurl') for section in repo.sections()
                if repo.has_option(section, 'baseurl')]

    def get_default_image_build_conf(self):
        vcs_info = self.workflow.source.get_vcs_info()
        ksurl = '{}#{}'.format(vcs_info.vcs_url, vcs_info.vcs_ref)

        base_urls = []
        for repo in self.repos:
            for url in self.extract_base_url(repo):
                # Imagefactory only supports $arch variable.
                url = url.replace('$basearch', '$arch')
                base_urls.append(url)

        install_tree = base_urls[0] if base_urls else ''

        repo = ','.join(base_urls)

        kwargs = {
            'ksurl': ksurl,
            'install_tree': install_tree,
            'repo': repo,
        }

        return StringIO(self.DEFAULT_IMAGE_BUILD_CONF.format(**kwargs))

    def parse_image_build_config(self, config_file_name):

        # Logic taken from koji.cli.koji.handle_image_build.
        # Unable to re-use koji's code because "cli" is not
        # a package of koji and this logic is intermingled
        # with CLI specific instructions.

        args = []
        opts = {}

        config = ConfigParser()
        config.readfp(self.get_default_image_build_conf())
        config.read(config_file_name)

        if self.architectures:
            config.set('image-build', 'arches', ','.join(self.architectures))
        elif self.architecture:
            config.set('image-build', 'arches', self.architecture)
        # else just use what was provided by the user in image-build.conf

        config_str = StringIO()
        config.write(config_str)
        self.log.debug('Image Build Config: \n%s', config_str.getvalue())

        image_name = None

        section = 'image-build'
        for option in ('name', 'version', 'arches', 'target', 'install_tree'):
            value = config.get(section, option)
            if not value:
                raise ValueError('{} cannot be empty'.format(option))
            if option == 'arches':
                value = [arch for arch in value.split(',') if arch]
            elif option == 'name':
                image_name = value
            args.append(value)
            config.remove_option(section, option)

        for option, value in config.items(section):
            if option in ('repo', 'format'):
                value = [v for v in value.split(',') if v]
            elif option in ('disk_size'):
                value = int(value)
            opts[option] = value

        section = 'ova-options'
        if config.has_section(section):
            ova = []
            for k, v in config.items(section):
                ova.append('{}={}'.format(k, v))
            opts['ova_option'] = ova

        section = 'factory-parameters'
        if config.has_section(section):
            factory = []
            for option, value in config.items(section):
                factory.append((option, value))
            opts['factory_parameter'] = factory

        return image_name, args, {'opts': opts}

    def get_filesystem_regex(self, image_name):
        prefix = image_name
        if self.architecture:
            prefix = '{}.*{}'.format(prefix, self.architecture)

        pattern = ('{}.*(\.tar|\.tar\.gz|\.tar\.bz2|\.tar\.xz)$'
                   .format(prefix))
        filesystem_regex = re.compile(pattern, re.IGNORECASE)

        return filesystem_regex

    def build_filesystem(self, image_build_conf):
        # Image build conf file should be in the same folder as Dockerfile
        build_file_dir = self.workflow.source.get_build_file_path()[1]
        image_build_conf = os.path.join(build_file_dir, image_build_conf)
        if not os.path.exists(image_build_conf):
            raise RuntimeError('Image build configuration file not found: {}'
                               .format(image_build_conf))

        image_name, args, kwargs = self.parse_image_build_config(image_build_conf)

        if self.scratch:
            kwargs['opts']['scratch'] = True

        filesystem_regex = self.get_filesystem_regex(image_name)
        if self.from_task_id:
            task_id = self.from_task_id
        else:
            task_id = self.session.buildImageOz(*args, **kwargs)
        return task_id, filesystem_regex

    def find_filesystem(self, task_id, filesystem_regex):
        for f in self.session.listTaskOutput(task_id):
            f = f.strip()
            match = filesystem_regex.match(f)
            if match:
                return task_id, match.group(0)

        # Not found in this task, search sub tasks
        for sub_task in self.session.getTaskChildren(task_id):
            found = self.find_filesystem(sub_task['id'], filesystem_regex)
            if found:
                return found

        return None

    def download_filesystem(self, task_id, filesystem_regex):
        found = self.find_filesystem(task_id, filesystem_regex)
        if found is None:
            raise RuntimeError('Filesystem not found as task output: {}'
                               .format(filesystem_regex.pattern))
        task_id, file_name = found

        self.log.info('Streaming filesystem: %s from task ID: %s',
                      file_name, task_id)

        contents = stream_task_output(self.session, task_id, file_name,
                                      self.blocksize)

        return contents

    def import_base_image(self, filesystem):
        result = self.tasker.d.import_image_from_stream(filesystem)
        # Response not deserialized:
        #   https://github.com/docker/docker-py/issues/1060
        self.log.info('import base image result: %s', result)
        result = json.loads(result)
        return result['status']

    def run_image_task(self, image_build_conf):
        task_id, filesystem_regex = self.build_filesystem(image_build_conf)

        try:
            task = TaskWatcher(self.session, task_id, self.poll_interval)
            task.wait()
        except BuildCanceledException:
            self.log.info("Build was canceled, canceling task %s", task_id)
            try:
                self.session.cancelTask(task_id)
                self.log.info('task %s canceled', task_id)
            except Exception as exc:
                self.log.info("Exception while canceling a task (ignored): %r", exc)

        if task.failed():
            try:
                # Koji may re-raise the error that caused task to fail
                task_result = self.session.getTaskResult(task_id)
            except Exception as exc:
                task_result = repr(exc)
            raise RuntimeError('image task, {}, failed: {}'
                               .format(task_id, task_result))

        return task_id, filesystem_regex

    def stream_filesystem(self, task_id, filesystem_regex):
        filesystem = self.download_filesystem(task_id, filesystem_regex)

        new_base_image = self.import_base_image(filesystem)
        self.workflow.builder.set_base_image(new_base_image)
        defer_removal(self.workflow, new_base_image)

        return new_base_image

    def run(self):
        base_image = self.workflow.builder.base_image
        if base_image.namespace != 'koji' or base_image.repo != 'image-build':
            self.log.info('Base image not supported: %s', base_image)
            return

        image_build_conf = base_image.tag
        if not image_build_conf or image_build_conf == 'latest':
            image_build_conf = 'image-build.conf'

        self.session = create_koji_session(self.koji_hub, self.koji_auth_info)

        task_id, filesystem_regex = self.run_image_task(image_build_conf)

        new_base_image = None
        if not self.is_orchestrator:
            new_base_image = self.stream_filesystem(task_id, filesystem_regex)

        return {
            'base-image-id': new_base_image,
            'filesystem-koji-task-id': task_id,
        }


text:
package com.moonlightpixels.jrpg.save.internal.format;

import com.moonlightpixels.jrpg.save.internal.SavedGameState;

public interface SavedGameFormat<T> {
    T toFormat(SavedGameState savedGameState) throws FormatEncodingException;
    SavedGameState fromFormat(T data) throws FormatDecodingException;
}


text: python main_gan.py &


text:
<?php
    # Constant: USE_ZLIB
    # Use zlib to provide GZIP compression
    if (version_compare(PHP_VERSION, "5.4.4", "<")) define('USE_ZLIB', true);
    else define('USE_ZLIB', false);

    $valid_files = "jquery.js plugins.js redactor/redactor.min.js";
    if (!in_array($_GET['file'], explode(" ", $valid_files)) and strpos($_GET['file'], "/themes/") === false)
        exit("Access Denied.");

    if (substr_count($_GET['file'], "..") > 0 )
        exit("GTFO.");

    if (extension_loaded('zlib') and USE_ZLIB and !ini_get("zlib.output_compression")) {
        ob_start("ob_gzhandler");
        header("Content-Encoding: gzip");
    } else
        ob_start();

    header("Content-Type: application/x-javascript");

    if (strpos($_GET['file'], "/themes/") === 0) {
        # Constant: MAIN_DIR
        # Absolute path to the Chyrp root
        define('MAIN_DIR', dirname(dirname(dirname(__FILE__))));

        header("Last-Modified: ".@date("r", filemtime(MAIN_DIR.$_GET['file'])));

        if (file_exists(MAIN_DIR.$_GET['file']))
            readfile(MAIN_DIR.$_GET['file']);
        else
            echo "alert('File not found: ".addslashes($_GET['file'])."')";
    } elseif (file_exists($_GET['file'])) {
        header("Last-Modified: ".@date("r", filemtime($_GET['file'])));
        readfile($_GET['file']);
    } else
        echo "alert('File not found: ".addslashes($_GET['file'])."')";

    ob_end_flush();


text:
#ifndef COIN_SOMFNAME_H
#define COIN_SOMFNAME_H

#include <Inventor/fields/SoMField.h>
#include <Inventor/fields/SoSubField.h>
#include <Inventor/SbName.h>

class COIN_DLL_API SoMFName : public SoMField {
  typedef SoMField inherited;

  SO_MFIELD_HEADER(SoMFName, SbName, const SbName &);

public:
  static void initClass(void);

  void setValues(const int start, const int num, const char * strings[]);
  void setValue(const char * str);
};

#endif // !COIN_SOMFNAME_H


text:
package uk.gov.gchq.gaffer.operation;

import uk.gov.gchq.koryphe.Summary;

/**
 * @deprecated use a {@link uk.gov.gchq.gaffer.data.elementdefinition.view.View} instead to specify whether
 * Edges/Entities that are 'equal to' or 'related to' seeds are wanted.
 * See filtering documentation.
 * A {@code SeedMatching} adds seed matching to operations.
 */
@Deprecated
public interface SeedMatching {
    /**
     * @param seedMatching a {@link SeedMatchingType} describing how the seeds should be
     *                     matched to the identifiers in the graph.
     * @see SeedMatchingType
     * @deprecated use a {@link uk.gov.gchq.gaffer.data.elementdefinition.view.View} instead to specify whether
     * Edges/Entities that are 'equal to' or 'related to' seeds are wanted.
     * See filtering documentation.
     */
    @Deprecated
    void setSeedMatching(final SeedMatchingType seedMatching);

    /**
     * @return a {@link SeedMatchingType} describing how the seeds should be
     * matched to the identifiers in the graph.
     * @deprecated use a {@link uk.gov.gchq.gaffer.data.elementdefinition.view.View} instead to specify whether
     * Edges/Entities that are 'equal to' or 'related to' seeds are wanted.
     * See filtering documentation.
     */
    @Deprecated
    SeedMatchingType getSeedMatching();

    /**
     * A {@code SeedMatchingType} defines how the seeds in the operation should be matched.
     */
    @Summary("How should the seeds be matched?")
    enum SeedMatchingType {
        EQUAL, RELATED
    }

    interface Builder<OP extends SeedMatching, B extends Builder<OP, ?>> extends Operation.Builder<OP, B> {
        default B seedMatching(final SeedMatchingType seedMatchingType) {
            _getOp().setSeedMatching(seedMatchingType);
            return _self();
        }
    }
}


text:
package org.sagebionetworks.repo.manager.wiki;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sagebionetworks.reflection.model.PaginatedResults;
import org.sagebionetworks.repo.manager.AuthorizationManager;
import org.sagebionetworks.repo.model.ACCESS_TYPE;
import org.sagebionetworks.repo.model.AuthorizationUtils;
import org.sagebionetworks.repo.model.ConflictingUpdateException;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.dao.WikiPageKey;
import org.sagebionetworks.repo.model.dao.WikiPageKeyHelper;
import org.sagebionetworks.repo.model.dbo.file.FileHandleDao;
import org.sagebionetworks.repo.model.file.FileHandle;
import org.sagebionetworks.repo.model.file.FileHandleResults;
import org.sagebionetworks.repo.model.v2.dao.V2WikiPageDao;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiMarkdownVersion;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiOrderHint;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage;
import org.sagebionetworks.repo.transactions.WriteTransaction;
import org.sagebionetworks.repo.web.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * V2 WikiManager implementation.
 * (Derived from org.sagebionetworks.repo.manager.wiki.WikiManagerImpl)
 * @author hso
 *
 */
public class V2WikiManagerImpl implements V2WikiManager {

	static private Log log = LogFactory.getLog(V2WikiManagerImpl.class);

	private static final String USER_IS_NOT_AUTHORIZED_TEMPLATE = "User is not authorized to '%1$s' a WikiPage with an ownerId: '%2$s' of type: '%3$s'";

	private static final Long MAX_WIKI_MARKDOWN_RANK = 100L;

	public static final long MAX_LIMIT = 50;

	@Autowired
	V2WikiPageDao wikiPageDao;

	@Autowired
	FileHandleDao fileMetadataDao;

	@Autowired
	AuthorizationManager authorizationManager;

	/**
	 * Default for Spring!
	 */
	public V2WikiManagerImpl(){}

	/**
	 * The IoC constructor.
	 * @param wikiPageDao
	 * @param authorizationManager
	 */
	public V2WikiManagerImpl(V2WikiPageDao wikiPageDao,
			AuthorizationManager authorizationManager, FileHandleDao fileMetadataDao) {
		super();
		this.wikiPageDao = wikiPageDao;
		this.authorizationManager = authorizationManager;
		this.fileMetadataDao = fileMetadataDao;
	}

	@WriteTransaction
	@Override
	public V2WikiPage createWikiPage(UserInfo user, String objectId, ObjectType objectType, V2WikiPage wikiPage) throws NotFoundException, UnauthorizedException{
		if(user == null) throw new IllegalArgumentException("user cannot be null");
		if(objectId == null) throw new IllegalArgumentException("objectId cannot be null");
		if(objectType == null) throw new IllegalArgumentException("objectType cannot be null");
		if(wikiPage == null) throw new IllegalArgumentException("wikiPage cannot be null");
		// Check that the user is allowed to perform this action
		if(!authorizationManager.canCreateWiki(user, objectId, objectType).isAuthorized()){
			throw new UnauthorizedException(String.format(USER_IS_NOT_AUTHORIZED_TEMPLATE, ACCESS_TYPE.CREATE.name(), objectId, objectType.name()));
		}

		// Set created by and modified by
		wikiPage.setCreatedBy(user.getId().toString());
		wikiPage.setModifiedBy(wikiPage.getCreatedBy());

		// First build up the map of names to FileHandles
		Map<String, FileHandle> nameToHandleMap = buildFileNameMap(wikiPage);

		// For a create the user must be the creator of each file handle used.
		List<String> newFileHandlesToInsert = new ArrayList<String>();
		for(FileHandle handle: nameToHandleMap.values()){
			newFileHandlesToInsert.add(handle.getId());
		}

		FileHandle markdownFileHandle = fileMetadataDao.get(wikiPage.getMarkdownFileHandleId());
		newFileHandlesToInsert.add(markdownFileHandle.getId());

		// Create a list of file handles associated with this wiki page to check permissions
		List<FileHandle> fileHandlesToCheck = new ArrayList<FileHandle>();
		// Add markdown file handle
		fileHandlesToCheck.add(markdownFileHandle);
		// Add attachments
		for(FileHandle handle: nameToHandleMap.values()) {
			fileHandlesToCheck.add(handle);
		}

		// Validate that the user can assign all file handles
		for(FileHandle handle: fileHandlesToCheck){
			// the user must have access to the raw FileHandle to assign it to an object.
			AuthorizationUtils.canAccessRawFileHandleByCreator(user, handle.getId(), handle.getCreatedBy()).checkAuthorizationOrElseThrow();
		}
		// pass to the DAO
		return wikiPageDao.create(wikiPage, nameToHandleMap, objectId, objectType, newFileHandlesToInsert);
	}

	/**
	 * Build up the Map of FileHandle.fileNames to FileHandles  If there are duplicate names in the input list,
	 * then then the handle with the most recent creation date will be used.
	 * @param page
	 * @return
	 * @throws DatastoreException
	 * @throws NotFoundException
	 */
	Map<String, FileHandle> buildFileNameMap(V2WikiPage page) throws DatastoreException, NotFoundException{
		Map<String, FileHandle> results = new HashMap<String, FileHandle>();
		// First lookup each FileHandle
		List<FileHandle> handles = new LinkedList<FileHandle>();
		if(page.getAttachmentFileHandleIds() != null){
			for(String id: page.getAttachmentFileHandleIds()){
				FileHandle handle = fileMetadataDao.get(id);
				handles.add(handle);
			}
		}
		// Now sort the list by createdOn
		Collections.sort(handles,  new Comparator<FileHandle>(){
			@Override
			public int compare(FileHandle one, FileHandle two) {
				return one.getCreatedOn().compareTo(two.getCreatedOn());
			}});
		// Now process the results
		for(FileHandle handle: handles){
			FileHandle old = results.put(handle.getFileName(), handle);
			if(old != null){
				// Log the duplicates
				log.info("Duplicate attachment file name found for WikiPage. The older FileHandle will be replaced with the newer FileHandle.  Old FileHandle: "+old );
			}
		}
		return results;
	}

	@Override
	public V2WikiPage getRootWikiPage(UserInfo user, String objectId,	ObjectType objectType) throws NotFoundException, UnauthorizedException {
		// Look up the root wiki
		Long rootWikiId = wikiPageDao.getRootWiki(objectId, objectType);
		WikiPageKey key = WikiPageKeyHelper.createWikiPageKey(objectId, objectType, rootWikiId.toString());
		// The security check is done in the default method.
		return getWikiPage(user, key, null);
	}

	@Override
	public V2WikiPage getWikiPage(UserInfo user, WikiPageKey key, Long version) throws NotFoundException, UnauthorizedException {
		// Validate that the user has read access
		validateReadAccess(user, key);
		// Pass to the DAO
		return wikiPageDao.get(key, version);
	}

	/**
	 * Validate that the user has read access to the owner object.
	 * @param user
	 * @param key
	 * @throws NotFoundException
	 */
	private void validateReadAccess(UserInfo user, WikiPageKey key)
			throws NotFoundException {
		if(user == null) throw new IllegalArgumentException("UserInfo cannot be null");
		if(key == null) throw new IllegalArgumentException("WikiPageKey cannot be null");
		// Check that the user is allowed to perform this action
		if(!authorizationManager.canAccess(user, key.getOwnerObjectId(), key.getOwnerObjectType(), ACCESS_TYPE.READ).isAuthorized()){
			throw new UnauthorizedException(String.format(USER_IS_NOT_AUTHORIZED_TEMPLATE, ACCESS_TYPE.READ.name(), key.getOwnerObjectId(), key.getOwnerObjectType().name()));
		}
	}

	/**
	 * Validate that the user has update access to the owner object.
	 * @param user
	 * @param key
	 * @throws NotFoundException
	 */
	private void validateUpdateAccess(UserInfo user, WikiPageKey key)
			throws NotFoundException {
		if(user == null) throw new IllegalArgumentException("UserInfo cannot be null");
		if(key == null) throw new IllegalArgumentException("WikiPageKey cannot be null");
		// Check that the user is allowed to perform this action
		if(!authorizationManager.canAccess(user, key.getOwnerObjectId(), key.getOwnerObjectType(), ACCESS_TYPE.UPDATE).isAuthorized()){
			throw new UnauthorizedException(String.format(USER_IS_NOT_AUTHORIZED_TEMPLATE, ACCESS_TYPE.READ.name(), key.getOwnerObjectId(), key.getOwnerObjectType().name()));
		}
	}

	@WriteTransaction
	@Override
	public void deleteWiki(UserInfo user, WikiPageKey key) throws UnauthorizedException, DatastoreException{
		if(user == null) throw new IllegalArgumentException("UserInfo cannot be null");
		if(key == null) throw new IllegalArgumentException("WikiPageKey cannot be null");
		// Check that the user is allowed to perform this action
		try {
			if(!authorizationManager.canAccess(user, key.getOwnerObjectId(), key.getOwnerObjectType(), ACCESS_TYPE.DELETE).isAuthorized()){
				throw new UnauthorizedException(String.format(USER_IS_NOT_AUTHORIZED_TEMPLATE, ACCESS_TYPE.DELETE.name(), key.getOwnerObjectId(), key.getOwnerObjectType().name()));
			}
		} catch (NotFoundException e) {
			// If the owner does not exist then it is okay to delete the wiki
			log.info("Deleting a Wikipage where the owner does not exist: "+key.toString());
		}
		// Pass to the DAO
		wikiPageDao.delete(key);
	}

	@WriteTransaction
	@Override
	public V2WikiPage updateWikiPage(UserInfo user, String objectId, ObjectType objectType, V2WikiPage wikiPage) throws NotFoundException, UnauthorizedException, ConflictingUpdateException {
		if(user == null) throw new IllegalArgumentException("UserInfo cannot be null");
		if(objectId == null) throw new IllegalArgumentException("ObjectType cannot be null");
		if(objectType == null) throw new IllegalArgumentException("ObjectType cannot be null");
		if(wikiPage == null) throw new IllegalArgumentException("wikiPage cannot be null");
		// Check that the user is allowed to perform this action
		if(!authorizationManager.canAccess(user, objectId,	objectType, ACCESS_TYPE.UPDATE).isAuthorized()){
			throw new UnauthorizedException(String.format(USER_IS_NOT_AUTHORIZED_TEMPLATE, ACCESS_TYPE.UPDATE.name(), objectId, objectType.name()));
		}

		// Before we can update the Wiki we need to lock.
		String currentEtag = wikiPageDao.lockForUpdate(wikiPage.getId());
		if(!currentEtag.equals(wikiPage.getEtag())){
			throw new ConflictingUpdateException("ObjectId: "+objectId+" was updated since you last fetched it, retrieve it again and reapply the update");
		}

		// Delete Wiki versions for rank > MAX_RANK
		Long versionAtMaxRank = wikiPageDao.getWikiVersionByRank(WikiPageKeyHelper.createWikiPageKey(objectId, objectType, wikiPage.getId()), MAX_WIKI_MARKDOWN_RANK);
		wikiPageDao.deleteWikiVersions(WikiPageKeyHelper.createWikiPageKey(objectId, objectType, wikiPage.getId()), versionAtMaxRank);

		// Set modified by
		wikiPage.setModifiedBy(user.getId().toString());

		// First build up the complete map of names to FileHandles of the wiki's attachments
		Map<String, FileHandle> nameToHandleMap = buildFileNameMap(wikiPage);

		// Get all the file handles used for this wiki in its history
		List<Long> allFileHandles = wikiPageDao.getFileHandleReservationForWiki(WikiPageKeyHelper.createWikiPageKey(objectId, objectType, wikiPage.getId()));
		Set<Long> existingFileHandleIds = new HashSet<Long>(allFileHandles);
		List<Long> allMarkdownHandles = wikiPageDao.getMarkdownFileHandleIdsForWiki(WikiPageKeyHelper.createWikiPageKey(objectId, objectType, wikiPage.getId()));
		for(Long markdownId: allMarkdownHandles) {
			existingFileHandleIds.add(markdownId);
		}

		// Get all the file handles associated with this wiki that we have to check
		FileHandle markdownFileHandle = fileMetadataDao.get(wikiPage.getMarkdownFileHandleId());
		List<FileHandle> fileHandlesToCheck = new ArrayList<FileHandle>();
		fileHandlesToCheck.add(markdownFileHandle);
		for(FileHandle handle: nameToHandleMap.values()) {
			fileHandlesToCheck.add(handle);
		}

		// Validate that the user can assign all file handles that are new.
		// Compare all stored attachments for a given wiki to the list of attachments for this updated version
		List<String> newFileHandlesToInsert = new ArrayList<String>();
		for(FileHandle handle: fileHandlesToCheck) {
			// If this file handle is not in the wiki's reservation of attachments, check permissions
			if(!existingFileHandleIds.contains(Long.valueOf(handle.getId()))){
				// the user must have access to the raw FileHandle to assign it to an object.
				authorizationManager.canAccessRawFileHandleByCreator(user, handle.getId(), handle.getCreatedBy()).checkAuthorizationOrElseThrow();
				// Add this to the list of file handles to insert for this update
				newFileHandlesToInsert.add(handle.getId());
			}
		}
		// Set etag
		wikiPage.setEtag(UUID.randomUUID().toString());
		// Pass to the DAO
		return wikiPageDao.updateWikiPage(wikiPage, nameToHandleMap, objectId, objectType, newFileHandlesToInsert);
	}

	@Override
	public PaginatedResults<V2WikiHeader> getWikiHeaderTree(UserInfo user, String ownerId, ObjectType type, Long limit, Long offset) throws DatastoreException, NotFoundException {
		if(user == null) throw new IllegalArgumentException("UserInfo cannot be null");
		if(ownerId == null) throw new IllegalArgumentException("ownerId cannot be null");
		if(type == null) throw new IllegalArgumentException("ownerId cannot be null");
		if(limit == null){
			limit = MAX_LIMIT;
		}
		if(limit > MAX_LIMIT){
			throw new IllegalArgumentException("Limit cannot exceed: "+MAX_LIMIT);
		}
		if(offset == null){
			offset = 0L;
		}
		// Check that the user is allowed to perform this action
		if(!authorizationManager.canAccess(user,ownerId, type, ACCESS_TYPE.READ).isAuthorized()){
			throw new UnauthorizedException(String.format(USER_IS_NOT_AUTHORIZED_TEMPLATE, ACCESS_TYPE.READ.name(), ownerId, type.name()));
		}
		List<V2WikiHeader> list = wikiPageDao.getHeaderTree(ownerId, type, limit, offset);
		return PaginatedResults.createWithLimitAndOffset(list, limit, offset);
	}

	@Override
	public V2WikiOrderHint getOrderHint(UserInfo user, String objectId,	ObjectType objectType) throws NotFoundException {
		if(user == null) throw new IllegalArgumentException("UserInfo cannot be null");
		if(objectId == null) throw new IllegalArgumentException("ObjectId cannot be null");
		if(objectType == null) throw new IllegalArgumentException("ObjectType cannot be null");

		// Look up the root wiki
		Long rootWikiId = wikiPageDao.getRootWiki(objectId, objectType);
		WikiPageKey key = WikiPageKeyHelper.createWikiPageKey(objectId, objectType, rootWikiId.toString());

		// Check that user has read access.
		validateReadAccess(user, key);

		return wikiPageDao.getWikiOrderHint(key);
	}

	@WriteTransaction
	@Override
	public V2WikiOrderHint updateOrderHint(UserInfo user, V2WikiOrderHint orderHint) throws NotFoundException {
		if(user == null) throw new IllegalArgumentException("UserInfo cannot be null");
		if (orderHint == null) throw new IllegalArgumentException("OrderHint cannot be null");

		// Look up the root wiki
		Long rootWikiId = wikiPageDao.getRootWiki(orderHint.getOwnerId(), orderHint.getOwnerObjectType());
		WikiPageKey key = WikiPageKeyHelper.createWikiPageKey(orderHint.getOwnerId(), orderHint.getOwnerObjectType(), rootWikiId.toString());

		// Check that user has update access.
		validateUpdateAccess(user, key);

		// Before we can update the Wiki we need to lock.
		String currentEtag = wikiPageDao.lockWikiOwnersForUpdate(key.getWikiPageId());
		if(!currentEtag.equals(orderHint.getEtag())) {
			throw new ConflictingUpdateException("ObjectId: "+orderHint.getOwnerId()+" was updated since you last fetched it, retrieve it again and reapply the update");
		}

		orderHint.setEtag(UUID.randomUUID().toString());

		return wikiPageDao.updateOrderHint(orderHint, key);
	}

	@Override
	public FileHandleResults getAttachmentFileHandles(UserInfo user, WikiPageKey key, Long version) throws NotFoundException {
		// Validate that the user has read access
		validateReadAccess(user, key);
		List<String> handleIds = wikiPageDao.getWikiFileHandleIds(key, version);
		return fileMetadataDao.getAllFileHandles(handleIds, true);
	}

	@Override
	public String getFileHandleIdForFileName(UserInfo user, WikiPageKey wikiPageKey, String fileName, Long version) throws NotFoundException, UnauthorizedException {
		// Validate that the user has read access
		validateReadAccess(user, wikiPageKey);
		// Look-up the fileHandle ID
		return wikiPageDao.getWikiAttachmentFileHandleForFileName(wikiPageKey, fileName, version);
	}

	@WriteTransaction
	@Override
	public V2WikiPage restoreWikiPage(UserInfo user, String objectId,
			ObjectType objectType, Long version, String wikiId) throws NotFoundException,
			UnauthorizedException {
		if(user == null) throw new IllegalArgumentException("UserInfo cannot be null");
		if(objectId == null) throw new IllegalArgumentException("ObjectType cannot be null");
		if(objectType == null) throw new IllegalArgumentException("ObjectType cannot be null");
		if(wikiId == null) throw new IllegalArgumentException("Wiki id cannot be null");
		// Check that the user is allowed to perform this action
		if(!authorizationManager.canAccess(user, objectId, objectType, ACCESS_TYPE.UPDATE).isAuthorized()){
			throw new UnauthorizedException(String.format(USER_IS_NOT_AUTHORIZED_TEMPLATE, ACCESS_TYPE.UPDATE.name(), objectId, objectType.name()));
		}

		WikiPageKey key = WikiPageKeyHelper.createWikiPageKey(objectId, objectType, wikiId);
		// Get the most recent version of the wiki page for its etag
		V2WikiPage wiki = wikiPageDao.get(key, null);

		V2WikiMarkdownVersion versionOfContents = wikiPageDao.getVersionOfWikiContent(key, version);

		// Set up a new V2 WikiPage
		V2WikiPage newWikiVersion = new V2WikiPage();
		newWikiVersion.setId(wikiId);
		newWikiVersion.setEtag(wiki.getEtag());
		newWikiVersion.setParentWikiId(wiki.getParentWikiId());
		//Preserve creation metadata
		newWikiVersion.setCreatedBy(wiki.getCreatedBy());
		newWikiVersion.setCreatedOn(wiki.getCreatedOn());
		// Assign restored content to the wiki page
		newWikiVersion.setMarkdownFileHandleId(versionOfContents.getMarkdownFileHandleId());
		newWikiVersion.setAttachmentFileHandleIds(versionOfContents.getAttachmentFileHandleIds());
		newWikiVersion.setTitle(versionOfContents.getTitle());
		// Update the page with these changes
		return updateWikiPage(user, objectId, objectType, newWikiVersion);
	}

	@Override
	public PaginatedResults<V2WikiHistorySnapshot> getWikiHistory(
			UserInfo user, String ownerId, ObjectType type, WikiPageKey wikiPageKey, Long limit, Long offset)
			throws NotFoundException, DatastoreException {
		if(user == null) throw new IllegalArgumentException("UserInfo cannot be null");
		if(ownerId == null) throw new IllegalArgumentException("ownerId cannot be null");
		if(type == null) throw new IllegalArgumentException("ownerId cannot be null");
		if(limit == null) throw new IllegalArgumentException("limit cannot be null");
		if(offset == null) throw new IllegalArgumentException("offset cannot be null");
		// Check that the user is allowed to perform this action
		if(!authorizationManager.canAccess(user,ownerId, type, ACCESS_TYPE.READ).isAuthorized()){
			throw new UnauthorizedException(String.format(USER_IS_NOT_AUTHORIZED_TEMPLATE, ACCESS_TYPE.READ.name(), ownerId, type.name()));
		}
		List<V2WikiHistorySnapshot> snapshots = wikiPageDao.getWikiHistory(wikiPageKey, limit, offset);
		return PaginatedResults.createWithLimitAndOffset(snapshots, limit, offset);
	}

	@Override
	public String getMarkdownFileHandleId(UserInfo user,
			WikiPageKey wikiPageKey, Long version) throws NotFoundException,
			UnauthorizedException {
		// Validate that the user has read access
		validateReadAccess(user, wikiPageKey);
		// Look-up the fileHandle ID
		return wikiPageDao.getMarkdownHandleId(wikiPageKey, version);
	}

	@Override
	public WikiPageKey getRootWikiKey(UserInfo user, String ownerId,
			ObjectType type) throws NotFoundException {
		Long rootWikiId = wikiPageDao.getRootWiki(ownerId, type);
		WikiPageKey key = WikiPageKeyHelper.createWikiPageKey(ownerId, type, rootWikiId.toString());
		// Validate that the user has read access
		validateReadAccess(user, key);
		return key;
	}
}


text:
<template name="carDetails">

				{{#with car}}

Detalles Vehiculo {{carBrand.name}} {{model}}

							Precio: {{formatCurrency currency price}}

							Modelo: {{model}}

							Motor: {{motor}}

							Transmisión: {{transmission}}

							Año: {{year}}

							Color: {{color}}

							Dirección: {{direction}}

							Tracción: {{traction}}

							Millas/Kms: {{milesKms}}

							Combustible: {{gasoline}}

							Stereo: {{stereo}}

							Vidrios: {{windows}}

				{{/with}}

				{{#with user}}

Datos Contacto

						 Nombre: {{profile.name}}

						 Direccion: {{profile.address}}

						Ciudad: {{profile.city}}

						Telefono: {{profile.phoneNumber1}}

						Telefono: {{profile.phoneNumber2}}

						Correo Electronico: {{userEmail}}

				{{/with}}

				<button class="fluid ui blue button">Contactar</button>

				<button class="fluid ui blue button">Compartir</button>

			{{#if currentUser.services.facebook}}

				{{> fbSidebar}}

			{{/if}}

Comentarios

					{{#each comments}}
					{{> publicationComments}}
					{{else}}
					 No hay comentarios por el momento
					{{/each}}
					{{#if currentUser}}
					{{#with car}}
					<form class="ui reply form">

							<textarea></textarea>

							 Agregar Comentario

					</form>
					{{/with}}
					{{/if}}

</template>


text:
/*
 * EaNavigatorPanel.java
 *
 * Created on September 19, 2002, 5:28 PM
 */
package cern.gp.explorer;

import java.awt.BorderLayout;
import java.beans.IntrospectionException;

import javax.swing.JList;

import org.openide.explorer.view.ListView;

import cern.gp.nodes.GPNode;
import cern.gp.nodes.impl.NodeUtils;

/**
 * An Explorer GUI Component that displays Children of a root node as a List.
 * It is recommended that the developer uses the NodeFactory and ChildrenListManager or ChildrenMapManager
 * to create the Node hierarchy to be explored.
 *
 * @author  Vito Baggiolini
 * @version $Revision: 1.2 $  $Date: 2006/09/25 08:52:36 $
 */
public class ListExplorer extends GPListExplorerPanel {

  private final ListViewListAccess listViewListAccess;

  //
  // -- CONSTRUCTORS -----------------------------------------------
  //

  /**
   * Creates an explorer with the default model and the default view
   */
  public ListExplorer() {
    this(new GPListView());
  }

  /**
   * create a ListExplorer and set the nodes to display
   * @param nodes the nodes to display
   */
  public ListExplorer(GPNode[] nodes) {
    this();
    this.setListNodes(nodes);
  }

  /**
   * Creates an explorer with the specified view
   * @param view the ListView to be used in this explorer
   */
  protected ListExplorer(ListViewListAccess view) {
    super();
    this.listViewListAccess = view;
    setLayout(new BorderLayout());
    add(view.getListView(), BorderLayout.CENTER);
  }

  //
  // -- PUBLIC METHODS ---------------------------------------------
  //

  /**
   * getter method
   * @return the ListView instance used in this explorer
   */
  public ListViewListAccess getListAccess() {
    return listViewListAccess;
  }

  /**
   * Set the list of nodes to be displayed. This method first checks whether all nodes have a common
   * parent and calls the method {@link #setRootNode(GPNode)} (with you should have called instead of this one).
   * If not, it creates a root node and creates a ChildrenManager for the nodes. In other words, you cannot use
   * this method if you want to use your own ChildrenManager implementation to control the displayed list of nodes.
   * Use this method preferably if you have an array of nodes without a common parent, and if you do not need
   * to use your own ChildrenManager.
   * <P>Note that you can still get hold of the siblings of one of your GPNode object with the
   * {@link GPNode#getNodeCollection} method.
   *
   * @param nodes the array nodes to be displayed in the ListExplorer
   */
  public final void setListNodes(GPNode[] nodes) {
    // this method is final because it is called from the constructor.
    // You can override and un-final it, but you have to make sure that your overridden method
    // is ready when it is called from the constructor of this class!
    // Beware: Calling an instance method in a derived class from the constructor of the
    // super class is dangerous, e.g. because the method might use unitialized variables in
    // the (not yet initialized) derived class.
    if (nodes.length <=0) { return; }
    if (NodeUtils.haveOneCommonParent(nodes)) {
      setRootNode(nodes[0].getParent());
    } else {
      try {
        Object rootBean = new NamedBean("");
        setRootBean(rootBean);
        this.setRootNode(createRootNode(rootBean, nodes));
      } catch (IntrospectionException ex) {
        ex.printStackTrace();
      }
    }
  }

  //
  // -- INNER CLASSES ---------------------------------------------
  //

  //
  // -- INNER CLASS ----------------------------------------------
  //

  /**
   * This class is a regular list view that gives access to the underlying list from Swing.
   *
   * @version $Id: ListExplorer.java,v 1.2 2006/09/25 08:52:36 acaproni Exp $
   * @author Lionel Mestre
   */
  private static class GPListView extends ListView implements ListViewListAccess {

    public GPListView() {
      super();
    }

    public JList getList() {
      return super.list;
    }

    /* (non-Javadoc)
     * @see cern.gp.explorer.ListViewListAccess#getListView()
     */
    public ListView getListView() {
      return this;
    }
  }

}


text:
        <canvas style="border: solid 1px; " id="canvas" width="600" height="600"></canvas>

            <input type="radio" name="mode" id="2d-radio" value="2d">
            Canvas 2D

            <input type="radio" name="mode" id="3d-radio" value="3d">
            WebGL

        <button onclick="addObjectToStage(50)">Add Objects</button>
        0


text:
// Generated by delombok at Thu Nov 16 13:48:05 CST 2017
package com.egzosn.pay.paypal.bean.order;

import com.alibaba.fastjson.annotation.JSONField;

public class RedirectUrls{
	/**
	 * Url where the payer would be redirected to after approving the payment. **Required for PayPal account payments.**
	 */
	@JSONField(name = "return_url")
	private String returnUrl;
	/**
	 * Url where the payer would be redirected to after canceling the payment. **Required for PayPal account payments.**
	 */
	@JSONField(name = "cancel_url")
	private String cancelUrl;

	/**
	 * Default Constructor
	 */
	public RedirectUrls() {
	}

	public String getReturnUrl() {
		return this.returnUrl;
	}

	public String getCancelUrl() {
		return this.cancelUrl;
	}

	public RedirectUrls setReturnUrl(final String returnUrl) {
		this.returnUrl = returnUrl;
		return this;
	}

	public RedirectUrls setCancelUrl(final String cancelUrl) {
		this.cancelUrl = cancelUrl;
		return this;
	}

	@Override

	public boolean equals(final Object o) {
		if (o == this) return true;
		if (!(o instanceof RedirectUrls)) return false;
		final RedirectUrls other = (RedirectUrls) o;
		if (!other.canEqual((Object) this)) return false;
		if (!super.equals(o)) return false;
		final Object this$returnUrl = this.getReturnUrl();
		final Object other$returnUrl = other.getReturnUrl();
		if (this$returnUrl == null ? other$returnUrl != null : !this$returnUrl.equals(other$returnUrl)) return false;
		final Object this$cancelUrl = this.getCancelUrl();
		final Object other$cancelUrl = other.getCancelUrl();
		if (this$cancelUrl == null ? other$cancelUrl != null : !this$cancelUrl.equals(other$cancelUrl)) return false;
		return true;
	}

	protected boolean canEqual(final Object other) {
		return other instanceof RedirectUrls;
	}

	@Override
	public int hashCode() {
		final int PRIME = 59;
		int result = 1;
		result = result * PRIME + super.hashCode();
		final Object $returnUrl = this.getReturnUrl();
		result = result * PRIME + ($returnUrl == null ? 43 : $returnUrl.hashCode());
		final Object $cancelUrl = this.getCancelUrl();
		result = result * PRIME + ($cancelUrl == null ? 43 : $cancelUrl.hashCode());
		return result;
	}
}


text:
.PHONY: *

help:
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

unit: ## run unit tests
	docker-compose run --rm php-fpm vendor/bin/phpunit --do-not-cache-result

cs-check: ## check coding standards
	docker-compose run --rm php-fpm vendor/bin/phpcs --no-cache

static-analysis: ## check static analysis
	docker-compose run --rm php-fpm vendor/bin/psalm

build: cs-check unit static-analysis


text:
package org.apache.camel.management;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.camel.ServiceStatus;
import org.apache.camel.builder.RouteBuilder;

/**
 * Tests mbeans is NOT registered when adding a 2nd route after CamelContext has been started,
 * because the registerNewRoutes is set to false
 *
 * @version
 */
public class ManagedRouteAddSecondRouteNotRegisterNewRoutesTest extends ManagementTestSupport {

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        // do not register new routes
        context.getManagementStrategy().getManagementAgent().setRegisterNewRoutes(false);

        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").routeId("foo").to("mock:result");
            }
        };
    }

    public void testRouteAddSecondRoute() throws Exception {
        MBeanServer mbeanServer = getMBeanServer();
        ObjectName route1 = ObjectName.getInstance("org.apache.camel:context=localhost/camel-1,type=routes,name=\"foo\"");

        // should be started
        String state = (String) mbeanServer.getAttribute(route1, "State");
        assertEquals("Should be started", ServiceStatus.Started.name(), state);

        log.info(">>>>>>>>>>>>>>>>> adding 2nd route <<<<<<<<<<<<<<");
        // add a 2nd route
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:bar").routeId("bar").to("mock:bar");
            }
        });
        log.info(">>>>>>>>>>>>>>>>> adding 2nd route DONE <<<<<<<<<<<<<<");

        // find the 2nd route
        ObjectName route2 = ObjectName.getInstance("org.apache.camel:context=localhost/camel-1,type=routes,name=\"bar\"");

        // should not be registered
        assertFalse("2nd route should not be registered", mbeanServer.isRegistered(route2));
    }

}


text:
sap.ui.define(['jquery.sap.global'],
	function(jQuery) {
	"use strict";

	/**
	 * BusyIndicator renderer.
	 * @namespace
	 */
	var BusyIndicatorRenderer = {
	};

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRenderManager the RenderManager that can be used for writing to the Render-Output-Buffer
	 * @param {sap.ui.core.Control} oBusyInd an object representation of the control that should be rendered
	 */
	BusyIndicatorRenderer.render = function (oRm, oBusyInd) {
		this.startBusyIndicator(oRm, oBusyInd);

		this.renderBusyIndication(oRm, oBusyInd);

		this.renderLabel(oRm, oBusyInd);

		this.endBusyIndicator(oRm);
	};

	BusyIndicatorRenderer.startBusyIndicator = function (oRm, oBusyInd) {
		var mAccState = {
			role: "progressbar",
			valuemin: "0",
			valuemax: "100"
		};

		oRm.write("
");
	};

	BusyIndicatorRenderer.renderTooltip = function (oRm, sTooltip) {
		if (sTooltip) {
			oRm.writeAttributeEscaped("title", sTooltip);
		}
	};

	BusyIndicatorRenderer.renderBusyIndication = function (oRm, oBusyInd) {
		if (oBusyInd.getCustomIcon()) {
			oRm.renderControl(oBusyInd._iconImage);
		} else {
			oRm.write("

");
		}
	};

	BusyIndicatorRenderer.renderLabel = function (oRm, oBusyInd) {
		if (oBusyInd.getText()) {
			oRm.renderControl(oBusyInd._busyLabel);
		}
	};

	BusyIndicatorRenderer.endBusyIndicator = function (oRm) {
		oRm.write("
");
	};

	return BusyIndicatorRenderer;

}, /* bExport= */ true);


text:
import React from "react"
import styled from "styled-components"

import Layout from "../components/layouts/layout"
import SEO from "../components/seo"
import {PageOpenerText, PageOpenerSubText} from "@styled"

const urls = {
  resume: "https://drive.google.com/file/d/1nZ4RL2F9QnA09fi8IKnDxUYXKsFj4EzC/view",
  cu: "https://www.colorado.edu/",
  pom: "https://www.pocketoutdoormedia.com/",
  helix: "https://www.helix.com/",
  apptio: "https://www.apptio.com/",
  hpe: "https://www.hpe.com/",
  hp: "https://www.hp.com/",
  petrode: "https://petrode.com/",
}

const ResumeDownload = styled.a`
  color: ${({ theme }) => theme.text}
`

const ResumeContainer = styled.div`
  margin: 30px 100px;
  max-width: 800px;
`

const Category = styled.div`
  padding: 60px 0 5px 0;
  font-size: 18px;
  font-weight: 500;
  opacity: 0.7;
`

const ContentGrid = styled.div`
  display: grid;
  grid-row-gap: 50px;
`

const ExternalLink = styled.a`
  color: ${props => props.color ? props.color : "inherit"};
  font-size: 35px;
  font-weight: 600;
  text-decoration: none;

  &:hover {
    opacity: 0.7;
  }
`

const Info = styled.div`
  font-size: 35px;
  font-weight: 600;
`

const TitleTimeline = styled.div`
  font-size: 23px;
  font-weight: 500;
`

const Content = styled.div`
  margin-top: 10px;
  font-size: 20px;
  font-weight: 400;
  max-width: 600px;
`

const InfoLink = (props) => {
  const {url, color, copy} = props;
  return(
    <ExternalLink
    color={color}
    href={url}
    target="_blank"
    rel="noopener noreferrer">
      {copy}
    </ExternalLink>
  )
}

const ResumePage = () => {

  return(
    <Layout>
      <SEO title="Resume" />
      <PageOpenerText>Resume.</PageOpenerText>
      <PageOpenerSubText>
        Or download it <ResumeDownload
        href={urls.resume}
        target="_blank"
        rel="noopener noreferrer">here</ResumeDownload> if you'd like.
      </PageOpenerSubText>
      <ResumeContainer>

        <Category>EDUCATION</Category>
        <ContentGrid>

            <InfoLink url={urls.cu} color="#CFB87C" copy="University of Colorado, Boulder"/>
            <TitleTimeline>B.S. Computer Science · 2012 - 2016</TitleTimeline>
            <Content>

GPA 3.79

            </Content>

        </ContentGrid>

        <Category>WORK</Category>
        <ContentGrid>

            <InfoLink url={urls.pom} color="#ed1c23" copy="Pocket Outdoor Media"/>
            <TitleTimeline>Software Engineer · Aug 2016 - Present</TitleTimeline>
            <Content>

Primarily Frontend. React, Typescript, Python/Django, GCP

            </Content>

            <InfoLink url={urls.helix} color="#3e4c77" copy="Helix"/>
            <TitleTimeline>Software Engineer · Aug 2019 - Present</TitleTimeline>
            <Content>

Primarily Frontend. React, Typescript, Python/Django, GCP

            </Content>

            <InfoLink url={urls.apptio} color="#f3700c" copy="Apptio"/>
            <TitleTimeline>Software Development Engineer · Nov 2016 - Feb 2019</TitleTimeline>
            <Content>

Primarily Frontend. React, Typescript, Python/Django, GCP

            </Content>

            <InfoLink url={urls.hpe} color="#3dac85" copy="HPE"/>
            <TitleTimeline>Software Development Engineer · Nov 2016 - Feb 2019</TitleTimeline>
            <Content>

Primarily Frontend. React, Typescript, Python/Django, GCP

            </Content>

            <InfoLink url={urls.hp} color="#3992d1" copy="Hewlett Packard"/>
            <TitleTimeline>Software Development Engineer · Nov 2016 - Feb 2019</TitleTimeline>
            <Content>

Primarily Frontend. React, Typescript, Python/Django, GCP

            </Content>

            <InfoLink url={urls.petrode} color="#3583dd" copy="PetroDE"/>
            <TitleTimeline>Software Development Engineer · Nov 2016 - Feb 2019</TitleTimeline>
            <Content>

Primarily Frontend. React, Typescript, Python/Django, GCP

            </Content>

        </ContentGrid>

        <Category>MORE</Category>
        <ContentGrid>

            <Info>SKILLS</Info>
            {/* <TitleTimeline>B.S. Computer Science · 2012 - 2016</TitleTimeline> */}
            <Content>

Javascript, Typescript, Python, Java

React, Node, Spring

Git, Mercurial

GCP, Docker

Agile, Scrum

            </Content>

            <Info>Interests</Info>
            {/* <TitleTimeline>B.S. Computer Science · 2012 - 2016</TitleTimeline> */}
            <Content>

Longboard freestyle, Brazilian jiu-jitsu, skateboarding, whacky socks, and FOOOOOOOD!

            </Content>

        </ContentGrid>
      </ResumeContainer>
    </Layout>
  )
}

export default ResumePage


text:
<?php

namespace App\JoboardBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use App\JoboardBundle\Entity\User;

class JoboardUsersCommand extends ContainerAwareCommand
{
   protected function configure()
   {
       $this
           ->setName('app:joboard:users')
           ->setDescription('Добавление пользователей')
           ->addArgument('username', InputArgument::REQUIRED, 'Логин')
           ->addArgument('password', InputArgument::REQUIRED, 'Пароль')
       ;
   }

   protected function execute(InputInterface $input, OutputInterface $output)
   {
       $username = $input->getArgument('username');
       $password = $input->getArgument('password');

       $em = $this->getContainer()->get('doctrine')->getManager();

       $user = new User();
       $user->setUsername($username);
       $factory = $this->getContainer()->get('security.encoder_factory');
       $encoder = $factory->getEncoder($user);
       $encodedPassword = $encoder->encodePassword($password, $user->getSalt());
       $output->writeln(sprintf('Добавляем пользователь %s с паролем %s', $username, $password));
       $user->setPassword($encodedPassword);
       $em->persist($user);
       $em->flush();

       $output->writeln(sprintf('Добавлен пользователь %s с паролем %s', $username, $password));
   }
}


text:
{% extends "centaur/base.html" %}

{% load url from future %}

{% block title %}{{error.summary}} - {% endblock %}

{% block content %}

{{error.event_count}}

            {{error.summary}} {{error.last_event|timesince}} ago
            {{error.module_path}}

    {% if events.has_previous %}

        Previous Event

    {% endif %}

    {% if events.has_next %}

        Next Event

    {% endif %}

{% for event in events %}

User

        {{event.logged_in_user_email}}

{% if event.stack_info %}

Traceback

    {% for frame in event.stack_info.frames %}

            {{ frame.filename|escape }} in {{ frame.function|escape }}

            {% if frame.context_line %}

                {% if frame.pre_context and not is_email %}

                    {% for line in frame.pre_context %}

{{ line|escape }}

{% endfor %}

                {% endif %}

{{ frame.context_line|escape }}
{% if not is_email %} ...{% endif %}

                {% if frame.post_context and not is_email  %}

                    {% for line in frame.post_context %}

{{ line|escape }}

{% endfor %}

                {% endif %}

          {% endif %}

          {% if frame.vars %}

                {% if is_email %}

Local Vars

                {% else %}
                    ▶ Local vars
                {% endif %}

                    {% for var in frame.vars|dictsort:"0" %}

                        {{ var.0|force_escape }}

{{ var.1|safe }}

                    {% endfor %}

        {% endif %}

    {% endfor %}

{% endif %}

Request

GET

    {% if event.request.GET %}

        {% for k, v in event.request.GET.items %}

            {{k}}
            {{v}}

        {% endfor %}

    {% else %}

No GET data

    {% endif %}

POST

    {% if event.request.POST %}

        {% for k, v in event.request.POST.items %}

            {{k}}
            {{v}}

        {% endfor %}

    {% else %}

No POST data

    {% endif %}

FILES

    {% if event.request.FILES %}

        {% for k, v in event.request.FILES.items %}

            {{k}}
            {{v}}

        {% endfor %}

    {% else %}

No FILES data

    {% endif %}

META

        {% for k, v in event.request.META.items %}

            {{k}}
            {{v}}

        {% endfor %}

 COOKIES

        {% for k, v in event.request.COOKIES.items %}

            {{k}}
            {{v}}

        {% endfor %}

{% endfor %}
{% endblock %}


text:
(function(factory) {
    if (typeof define === "function" && define.amd) {
        define([ "jquery", "moment" ], factory);
    }
    else if (typeof exports === "object") {
        module.exports = factory(require("jquery"), require("moment"));
    }
    else {
        factory(jQuery, moment);
    }
})(function($, moment) {

(function() {
//! moment.js locale configuration
//! locale : Finnish [fi]
//! author : Tarmo Aidantausta : https://github.com/bleadof

; 'use strict';

    var numbersPast = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '),
        numbersFuture = [
            'nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden',
            numbersPast[7], numbersPast[8], numbersPast[9]
        ];
    function translate(number, withoutSuffix, key, isFuture) {
        var result = '';
        switch (key) {
            case 's':
                return isFuture ? 'muutaman sekunnin' : 'muutama sekunti';
            case 'm':
                return isFuture ? 'minuutin' : 'minuutti';
            case 'mm':
                result = isFuture ? 'minuutin' : 'minuuttia';
                break;
            case 'h':
                return isFuture ? 'tunnin' : 'tunti';
            case 'hh':
                result = isFuture ? 'tunnin' : 'tuntia';
                break;
            case 'd':
                return isFuture ? 'päivän' : 'päivä';
            case 'dd':
                result = isFuture ? 'päivän' : 'päivää';
                break;
            case 'M':
                return isFuture ? 'kuukauden' : 'kuukausi';
            case 'MM':
                result = isFuture ? 'kuukauden' : 'kuukautta';
                break;
            case 'y':
                return isFuture ? 'vuoden' : 'vuosi';
            case 'yy':
                result = isFuture ? 'vuoden' : 'vuotta';
                break;
        }
        result = verbalNumber(number, isFuture) + ' ' + result;
        return result;
    }
    function verbalNumber(number, isFuture) {
        return number < 10 ? (isFuture ? numbersFuture[number] : numbersPast[number]) : number;
    }

    var fi = (moment.defineLocale || moment.lang).call(moment, 'fi', {
        months : 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split('_'),
        monthsShort : 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'),
        weekdays : 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split('_'),
        weekdaysShort : 'su_ma_ti_ke_to_pe_la'.split('_'),
        weekdaysMin : 'su_ma_ti_ke_to_pe_la'.split('_'),
        longDateFormat : {
            LT : 'HH.mm',
            LTS : 'HH.mm.ss',
            L : 'DD.MM.YYYY',
            LL : 'Do MMMM[ta] YYYY',
            LLL : 'Do MMMM[ta] YYYY, [klo] HH.mm',
            LLLL : 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm',
            l : 'D.M.YYYY',
            ll : 'Do MMM YYYY',
            lll : 'Do MMM YYYY, [klo] HH.mm',
            llll : 'ddd, Do MMM YYYY, [klo] HH.mm'
        },
        calendar : {
            sameDay : '[tänään] [klo] LT',
            nextDay : '[huomenna] [klo] LT',
            nextWeek : 'dddd [klo] LT',
            lastDay : '[eilen] [klo] LT',
            lastWeek : '[viime] dddd[na] [klo] LT',
            sameElse : 'L'
        },
        relativeTime : {
            future : '%s päästä',
            past : '%s sitten',
            s : translate,
            m : translate,
            mm : translate,
            h : translate,
            hh : translate,
            d : translate,
            dd : translate,
            M : translate,
            MM : translate,
            y : translate,
            yy : translate
        },
        ordinalParse: /\d{1,2}\./,
        ordinal : '%d.',
        week : {
            dow : 1, // Monday is the first day of the week.
            doy : 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    return fi;

})();

/* Finnish initialisation for the jQuery UI date picker plugin. */
/* Written by Harri Kilpiö (harrikilpio@gmail.com). */
$.fullCalendar.datepickerLang('fi', 'fi', {
closeText: 'Sulje',
prevText: '«Edellinen',
nextText: 'Seuraava»',
currentText: 'Tänään',
monthNames: ['Tammikuu','Helmikuu','Maaliskuu','Huhtikuu','Toukokuu','Kesäkuu',
'Heinäkuu','Elokuu','Syyskuu','Lokakuu','Marraskuu','Joulukuu'],
monthNamesShort: ['Tammi','Helmi','Maalis','Huhti','Touko','Kesä',
'Heinä','Elo','Syys','Loka','Marras','Joulu'],
dayNamesShort: ['Su','Ma','Ti','Ke','To','Pe','La'],
dayNames: ['Sunnuntai','Maanantai','Tiistai','Keskiviikko','Torstai','Perjantai','Lauantai'],
dayNamesMin: ['Su','Ma','Ti','Ke','To','Pe','La'],
weekHeader: 'Vk',
dateFormat: 'd.m.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''});

$.fullCalendar.lang("fi", {
	buttonText: {
		month: "Kuukausi",
		week: "Viikko",
		day: "Päivä",
		list: "Tapahtumat"
	},
	allDayText: "Koko päivä",
	eventLimitText: "lisää"
});

});