text:
#include "common.h"
#include "args.h"
#include "player.h"
#include "helper.h"
#include "stream.h"
#include "audio.h"
#include <stdio.h>
#include <process.h>
#include "decoder.h"

#define _DIRECTX

MPArgs *Args;
struct frame fr;
esPlayerError LastError = peNoError;
HANDLE ThreadQueueEvent = NULL;
HANDLE SeekEvent, SeekEvent2, FinishEvent;
unsigned long NewSeekPosition;

int xxx = 0;

void HardAudioReset(MPPlayer *ptr)
{
    FinishBuffer();
    try {
        Done_MPAudio();
    }
    catch(...) {}
    try {
        Init_MPAudio();
    }
    catch(...) {
        LastError = peOutputError;
        throw 1;
        return;
    }
}

void SynthesisFilterInit()
{
    typedef int (*func)(real *,int,unsigned char * , int *);
    typedef int (*func_mono)(real *,unsigned char * , int *);

    static func funcs[2][4] =
    {
        { synth_1to1,
            synth_2to1,
            synth_4to1,
            synth_ntom} ,
        { synth_1to1_8bit,
        synth_2to1_8bit,
        synth_4to1_8bit ,
        synth_ntom_8bit}
    };

    static func_mono funcs_mono[2][2][4] =
    {
        { { synth_1to1_mono2stereo ,
            synth_2to1_mono2stereo ,
            synth_4to1_mono2stereo ,
            synth_ntom_mono2stereo } ,
        { synth_1to1_8bit_mono2stereo ,
        synth_2to1_8bit_mono2stereo ,
        synth_4to1_8bit_mono2stereo ,
        synth_ntom_8bit_mono2stereo } } ,
        { { synth_1to1_mono ,
        synth_2to1_mono ,
        synth_4to1_mono ,
        synth_ntom_mono } ,
        { synth_1to1_8bit_mono ,
        synth_2to1_8bit_mono ,
        synth_4to1_8bit_mono ,
        synth_ntom_8bit_mono } }
    };

    fr.synth = (synthProc) funcs[Args->Force8bit][fr.down_sample];
    fr.synth_mono = funcs_mono[Args->ForceMono][Args->Force8bit][fr.down_sample];

    fr.block_size = 128 >> (Args->ForceMono + Args->Force8bit + fr.down_sample);

    if(Args->Force8bit)
    {
        Args->AudioBits=8;
        make_conv16to8_table();
    }
}

unsigned long __stdcall PlayThread(void *ptr)
{
    MMRESULT mmRes;
    //int clip;
    long numframes = -1;
    MSG msg;
    PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
    try
    {
        Init_MPAudio();
    }
    catch(...)
    {
        LastError = peOutputError;
        SetEvent(ThreadQueueEvent);
        SetEvent(FinishEvent);
        ExitThread(0);
        return 0;
    }
    SetEvent(ThreadQueueEvent);
    long OldRate = 0, NewRate = 0;
    int OldBits = 0, OldChannel = 0;
    //unsigned long left,right;
    unsigned long FrameNum = 0;
    long OldScaleFactor = 32768;
    MPPlayer *Player = (MPPlayer *)ptr;
    Args->IsVBR = false;
    try
    {
        while(numframes)
        {
            if (WaitForSingleObject(SeekEvent, 0) == WAIT_OBJECT_0)
            {
                if (Args->OutputMode == omMMSystem)
                {
                    mmRes = waveOutReset(WaveDevice);
                    ProcessAudioMessages();
                    BufferCount = 0;
                }
                if (Seek_Stream(NewSeekPosition))
                    NewSeekPosition = -1;
                else
                    NewSeekPosition = 0;
                SetEvent(SeekEvent2);
            }
            ProcessAudioMessages();
            OldBits = fr.bitrate_index;
            try
            {
                once_more:
                BOOL Res = ReadFrame();
                if (Res == -2)
                    break;
                if(Res) Args->CurrentPos++;
                /*if(Args->CurrentPos > MaxFrames)
                    break; */
                if(Player->UserBreak)
                {
                    break;
                }
                if (Args->CurrentPos < Args->StartFrame)
                {
                    continue;
                }

                if (Args->CurrentPos > Args->EndFrame)
                {
                    break;
                }
                if(!Res && Res !=-2) goto once_more;
                numframes--;
                if (OldScaleFactor != Args->ScaleFactor)
                {
                    make_decode_tables(Args->ScaleFactor);
                    OldScaleFactor = Args->ScaleFactor;
                }
                if (fr.header_change)
                {
                    int reset_audio=0;
                    if ((Args->SampleRate >= 48000)  && (Args->OutputMode == omMMSystem))
                    {
                        fr.down_sample = 1;
                        Args->SampleRate = Args->SampleRate/2;
                        Args->ForceFreq = Args->SampleRate;
                        Init_MPEGDecoder(fr.down_sample);

                    }
                    if(Args->ForceFreq < 0)
                    {
                        if(Args->SampleRate != freqs[fr.sampling_frequency>>(fr.down_sample)])
                        {
                            Args->SampleRate = freqs[fr.sampling_frequency>>(fr.down_sample)];
                            reset_audio=1;
                        }
                    }
                    else
                    if (Args->SampleRate != Args->ForceFreq)
                    {
                        Args->SampleRate = Args->ForceFreq;
                        reset_audio=1;
                    }
                    if ((OldBits != fr.bitrate_index) && (OldBits != 0))
                    {
                        Args->IsVBR = true;
                    }
                    if(reset_audio) {
                        HardAudioReset(Player);
                    }
                    fr.header_change = 0;
                }
                if(fr.error_protection) GetBits(16);
                xxx = Args->CurrentPos;
                if(fr.WhatLayer==3) /*clip=*/do_layer3(); else
                if(fr.WhatLayer==2) /*clip=*/do_layer2(); else
                if(fr.WhatLayer==1) /*clip=*/do_layer1();
                if (Player->PauseFlag)
                {
                    if (Args->OutputMode = omMMSystem) Pause_Audio();
                    Player->ThreadSync = 1;
                    while(Player->PauseFlag)
                    {
                        Sleep(77);
                        if (Player->UserBreak) break;
                        if (WaitForSingleObject(SeekEvent, 0) == WAIT_OBJECT_0)
                        {
                            if (Args->OutputMode == omMMSystem)
                            {
                                mmRes = waveOutReset(WaveDevice);
                                ProcessAudioMessages();
                                BufferCount = 0;
                            }
                            if (Seek_Stream(NewSeekPosition))
                                NewSeekPosition = -1;
                            else
                                NewSeekPosition = 0;
                            SetEvent(SeekEvent2);
                        }
                    }
                    if (Args->OutputMode = omMMSystem) Resume_Audio();
                }
            }
            catch (...)
            {
                throw;
            }
        }
    } catch (...)
    {
        int kkk = 1;
    }
    if(!Player->UserBreak)
    {
        try
        {
            AudioFlush();
            FinishBuffer();
        }
        catch (...)
        {
        }
        if (Decoder_Initialized)
        {
            Done_MPEGDecoder();
            Decoder_Initialized = false;
        }
        Reset_Stream();
        Done_MPAudio();
        Player->FPlayerMode = pmStopped;
    }
    else
    {
        if (Args->OutputMode == omMMSystem)
        {
            AudioFlush();
            mmRes = waveOutReset(WaveDevice);
            ProcessAudioMessages();
            BufferCount = 0;
        }
        if (Decoder_Initialized)
        {
            Done_MPEGDecoder();
            Decoder_Initialized = false;
        }
        Reset_Stream();
        Done_MPAudio();
        Player->FPlayerMode = pmOpened;
    }
    Player->UserBreak=0;
    SetEvent(FinishEvent);
    ExitThread(0);
    return 0;
}

MPPlayer::~MPPlayer() {
    if (PlayerMode() > pmClosed) Close();
    if (Args) delete Args;
    CloseHandle(FinishEvent);
    CloseHandle(SeekEvent);
    CloseHandle(SeekEvent2);
}

MPPlayer::MPPlayer() {
    ModuleTag = 0x14581458;
    FinishEvent = CreateEvent(NULL, false, false, NULL);
    SeekEvent = CreateEvent(NULL, false, false, NULL);
    SeekEvent2 = CreateEvent(NULL, false, false, NULL);
    Args = new MPArgs();
    if (!Args) throw 1;
    Args->InputMode=imFile;
    Args->OutputMode=omMMSystem;
    Args->Player = this;
    FPlayerMode = pmClosed;
    UserBreak = false;
    LastError = peNoError;
    fr.single = -1;
    fr.down_sample = 0;

    equalizer_cnt=0;
    for(int i=0; i<32; i++) {
        equalizer[0][i]=equalizer[1][i]=1.0;
        equalizer_sum[0][i]=equalizer_sum[1][i]=0.0;
    }
};

esPlayerError MPPlayer::ESGetLastError() {
    esPlayerError res = LastError;
    LastError = peNoError;
    return res;
}

bool MPPlayer::SetInName (const char *FileName){
    if (PlayerMode() != pmClosed) {
        LastError = peIncorrectMode;
        return false;
    }
    if (Args->InName) free(Args->InName);
    Args->InName = (char *) xstrdup((LPTSTR) FileName);
    return true;
}

bool MPPlayer::SetOutName(const char *FileName){
    if (PlayerMode() >= pmPlaying) {
        LastError = peIncorrectMode;
        return false;
    }
    if (Args->OutName) free(Args->OutName);
    Args->OutName = (char *) xstrdup((LPTSTR) FileName);
    return true;
}

bool MPPlayer::SetInMode (esInputMode InMode){
    if (PlayerMode() > pmClosed) {
        LastError = peIncorrectMode;
        return false;
    }
    Args->InputMode = InMode;
    return true;
}

bool MPPlayer::SetOutMode(esOutputMode OutMode){
    if (PlayerMode() >= pmPlaying) {
        LastError = peIncorrectMode;
        return false;
    }
#ifndef _DIRECTX
    if (OutMode == omDirectSound) {
        LastError = peNotImplemented;
        return false;
    }
#endif
    Args->OutputMode = OutMode;
    return true;
}

bool MPPlayer::Open(){
    if ((PlayerMode() != pmClosed) || ((Args->InputMode == imFile) && (!Args->InName))) {
        if (PlayerMode() != pmClosed)
            LastError = peIncorrectMode;
        else
            LastError = peInputError;
        return false;
    }
    PauseFlag = 0;
    try {
        Init_Stream();
    } catch (...) {
        LastError = peInputError;
        return false;
    }
    FPlayerMode = pmOpened;
    return true;
}

bool MPPlayer::InitStream(){
    if ((PlayerMode() != pmOpened) && (PlayerMode() != pmStopped))
    {
        LastError = peIncorrectMode;
        return false;
    }
    try
    {
        memset(&fr, 0, sizeof(fr));
        fr.single = -1;
        if (!ReadFrame())
        {
            Reset_Stream();
            return false;
        }
        Reset_Stream();
    }
    catch ( ... )
    {
        return false;
    }
    Args->SampleRate = freqs[fr.sampling_frequency];
    if(fr.single>=0) Args->ForceMono=1;
    if(Args->ForceMono) {
        if(fr.single<0) fr.single=3;
        Args->Channels=1;
    }
    if(fr.down_sample==1)
    {
        Args->SampleRate = Args->SampleRate/2;
        Args->ForceFreq = Args->SampleRate;
    }
    if (fr.down_sample==2)
    {
        Args->SampleRate = Args->SampleRate/4;
        Args->ForceFreq = Args->SampleRate;
    }
    if ((Args->SampleRate >= 48000)  && (Args->OutputMode == omMMSystem))
    {
        /*
            This doesn't work :(((
            fr.down_sample = 3;
            synth_ntom_set_step(12, 11);
            Args->ForceFreq = Args->SampleRate = 44100;
        */
        fr.down_sample = 1;
        Args->SampleRate = Args->SampleRate/2;
        Args->ForceFreq = Args->SampleRate;
    }
    SynthesisFilterInit();
    try {
        // create decoder
        Init_MPEGDecoder(fr.down_sample);
        make_decode_tables(Args->ScaleFactor);
    }
    catch(...){
        LastError = peInternalError;
        return false;
    }
    FPlayerMode = pmReady;
    return true;
}

bool MPPlayer::Play() {
    if (PlayerMode() != pmReady)
    {
        LastError = peIncorrectMode;
        return false;
    }
    if ((Args->OutputMode == omCallback) && ((!Args->BufferCB) || (!Args->OutActionCB)))
    {
        LastError = peNoCallback;
        return false;
    }
    if (Args->EndPos == 0) SetLimits(Args->StartPos, Args->EndPos);
    fr.header_change = 0;

    ThreadQueueEvent = CreateEvent(NULL, false, false, NULL);
    if (!ThreadQueueEvent)
    {
        LastError = peInternalError;
        return false;
    }
    ResetEvent(FinishEvent);
    if (PlayThreadHan)
    {
        CloseHandle(PlayThreadHan);
        PlayThreadHan = NULL;
    }
    PlayThreadHan = CreateThread(NULL, 0, PlayThread, this, 0, &PlayerThreadID);
    if (!PlayThreadHan)
    {
        LastError = peInternalError;
        return false;
    }
    WaitForSingleObject(ThreadQueueEvent, INFINITE);
    CloseHandle(ThreadQueueEvent);

    if (LastError != peNoError)
        return false;
    SetThreadPriority(PlayThreadHan, Args->PlayPriority);
    FPlayerMode = pmPlaying;
    return true;
}

bool MPPlayer::Pause(){
    if ((PlayerMode() == pmPlaying) || (PlayerMode() == pmPaused)) {
        PauseFlag = true;
        FPlayerMode = pmPaused;
        return true;
    } else {
        LastError = peIncorrectMode;
        return false;
    }
}

bool MPPlayer::Resume(){
    if ((PlayerMode() == pmPlaying) || (PlayerMode() == pmPaused)) {
        PauseFlag = false;
        FPlayerMode = pmPlaying;
        return true;
    } else {
        LastError = peIncorrectMode;
        return false;
    }
}

bool MPPlayer::Stop()
{
    if ((PlayerMode() == pmPlaying) || (PlayerMode() == pmPaused))
    {
        UserBreak = 1;
        WaitForSingleObject(FinishEvent, INFINITE);
        if (PlayThreadHan)
        {
            CloseHandle(PlayThreadHan);
            PlayThreadHan = NULL;
        }
        LastError = peNoError;
        return true;
    }
    if (PlayerMode() == pmStopped)
    {
            FPlayerMode = pmOpened;
            return true;
    } else {
        LastError = peIncorrectMode;
        return false;
    }
}

bool MPPlayer::Close(){
    if ((PlayerMode() == pmPlaying) || (PlayerMode() == pmPaused)) Stop();
    if (StreamInit) {
        Done_Stream();
        StreamInit = false;
    }
    FPlayerMode = pmClosed;
    return true;
}

unsigned long MPPlayer::GetSize(){
    if (PlayerMode() > pmOpened) {
        return Totalms();
    } else {
        LastError = peIncorrectMode;
        return -1;
    }
}

unsigned long MPPlayer::GetPos()
{
    if (PlayerMode() >= pmStopped)
    {
        if (PlayerMode() == pmStopped)
        {
            return Totalms();
        }
        return Currentms();
    }
    else
    {
        LastError = peIncorrectMode;
        return -1;
    }
}

bool MPPlayer::CanSetPos()
{
    if (PlayerMode() >= pmOpened)
    {
        return Args->Seekable;
    }
    else
    {
        LastError = peIncorrectMode;
        return false;
    }
}

bool MPPlayer::SetPos(unsigned long NewPos){
    if ((PlayerMode() == pmPlaying) || (PlayerMode() == pmPaused))
    {
        NewSeekPosition = NewPos;
        SetEvent(SeekEvent);
        WaitForSingleObject(SeekEvent2, INFINITE);
        return (NewSeekPosition == -1);
    } else {
        LastError = peIncorrectMode;
        return false;
    }
}

bool MPPlayer::SetAudioBuffers(unsigned long buffers, unsigned long size){
    if (PlayerMode() >= pmReady)
    {
        LastError = peIncorrectMode;
        return false;
    } else
    {
        if (buffers) Args->Buffers = buffers;
        if (size) Args->BufferSize = size;
    }
    return true;
}

bool MPPlayer::SetOutputDevice(unsigned long DevNum) {
    if (PlayerMode() != pmClosed) {
        LastError = peIncorrectMode;
        return false;
    } else {
        Args->AudioDevice = DevNum;
        return true;
    }
}

bool MPPlayer::SetLimits(unsigned long StartPos, unsigned long EndPos)
{
    Args->StartPos = StartPos;
    if ((EndPos != 0) && (EndPos < StartPos))
    {
         Args->EndPos = 0xFFFFFFFF;
    } else
    {
        Args->EndPos = EndPos;
    }
    if (PlayerMode() >= pmReady)
    {
        Args->StartFrame = Args->StartPos / Frame2ms();
        if ((!Args->EndPos)  || (Args->EndPos == 0xFFFFFFFF))
        {
            Args->EndPos = 0xFFFFFFFF;
            Args->EndFrame = 0xFFFFFFFF;
        } else
            Args->EndFrame = Args->EndPos / Frame2ms();
    }
    return true;
}

bool MPPlayer::SetPriority(long Priority)
{
    if (PlayerMode() >= pmPlaying)
    {
        return SetThreadPriority(PlayThreadHan, Priority);
    }
    else
    {
        Args->PlayPriority = Priority;
        return true;
    }
}

esPlayerMode MPPlayer::PlayerMode() {
    //esPlayerMode mode = FPlayerMode;
    //if (mode == pmStopped) FPlayerMode = pmOpened;
    return FPlayerMode;
}

bool MPPlayer::SetInCB(InFileOpenCB openCB, InFileCloseCB closeCB, InFileGetSizeCB getsizeCB,
             InFileSeekCB seekCB, InFileReadCB readCB, unsigned long UserData1) {
    if (PlayerMode() != pmClosed) {
        LastError = peIncorrectMode;
        return false;
    }
    Args->InOpenCB = openCB;
    Args->InCloseCB = closeCB;
    Args->InGetSizeCB = getsizeCB;
    Args->InSeekCB = seekCB;
    Args->InReadCB = readCB;
    Args->InCBData1 = UserData1;
    return true;
}

bool MPPlayer::SetOutCB(WaveOutCB OutCB, WaveOutActionCB OutActionCB, unsigned long UserData) {
    if (PlayerMode() >= pmPlaying) {
        LastError = peIncorrectMode;
        return false;
    } else {
        Args->BufferCB = (WaveOutCB) OutCB;
        Args->OutActionCB = (WaveOutActionCB) OutActionCB;
        Args->OutCBData = UserData;
        return true;
    }
}

bool MPPlayer::CanSetVolume(bool *Separate) {
    return Audio_CanSetVolume(Separate);
}

bool MPPlayer::SetVolume(unsigned long Volume) {
    return Audio_SetVolume(Volume);
}

bool MPPlayer::GetVolume(unsigned long *Volume){
    return Audio_GetVolume(Volume);
}

bool MPPlayer::SetDevNum(unsigned long DevNum) {
    if (PlayerMode() >= pmPlaying) {
        LastError = peIncorrectMode;
        return false;
    } else {
        Args->AudioDevice = DevNum;
        return true;
    }
}

bool MPPlayer::SetWindow(HWND Wnd) {
    if (PlayerMode() >= pmPlaying) {
        LastError = peIncorrectMode;
        return false;
    } else {
        Args->wnd = Wnd;
        return true;
    }
}

bool MPPlayer::UseOutCB(bool UseCB) {
    if (PlayerMode() >= pmPlaying) {
        LastError = peIncorrectMode;
        return false;
    } else {
        Args->UseHdrCB = UseCB;
        return true;
    }
}


text:
package example;

import java.io.File;

import org.jnetwork.HTTPServer;

public class HTTPFileServer {
	public static void main(String[] args) {
		HTTPServer server = new HTTPServer();

		try {
			server.start();
			server.serveDirectory(new File("www"));
			server.waitUntilClose();
			server.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<shape ="rectangle"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <corners ="4.0dip" />
    <solid ="@color/google_plus_red" />
</shape>


text:
'use strict';

import 'vs/css!./media/activityaction';
import nls = require('vs/nls');
import DOM = require('vs/base/browser/dom');
import { TPromise } from 'vs/base/common/winjs.base';
import { Builder, $ } from 'vs/base/browser/builder';
import { DelayedDragHandler } from 'vs/base/browser/dnd';
import { Action } from 'vs/base/common/actions';
import { BaseActionItem, Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { IActivityBarService, ProgressBadge, TextBadge, NumberBadge, IconBadge, IBadge } from 'vs/workbench/services/activity/common/activityBarService';
import Event, { Emitter } from 'vs/base/common/event';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ViewletDescriptor } from 'vs/workbench/browser/viewlet';
import { dispose } from 'vs/base/common/lifecycle';
import { IViewletService, } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPartService, Parts } from 'vs/workbench/services/part/common/partService';
import { IThemeService, ITheme } from "vs/platform/theme/common/themeService";
import { ACTIVITY_BADGE_FOREGROUND, ACTIVITY_BADGE_BACKGROUND, ACTIVITY_BAR_DRAG_AND_DROP_BACKGROUND } from "vs/workbench/common/theme";
import { highContrastBorder } from "vs/platform/theme/common/colorRegistry";

export class ActivityAction extends Action {
	private badge: IBadge;
	private _onDidChangeBadge = new Emitter<this>();

	constructor(id: string, name: string, clazz: string) {
		super(id, name, clazz);

		this.badge = null;
	}

	public get onDidChangeBadge(): Event<this> {
		return this._onDidChangeBadge.event;
	}

	public activate(): void {
		if (!this.checked) {
			this._setChecked(true);
		}
	}

	public deactivate(): void {
		if (this.checked) {
			this._setChecked(false);
		}
	}

	public getBadge(): IBadge {
		return this.badge;
	}

	public setBadge(badge: IBadge): void {
		this.badge = badge;
		this._onDidChangeBadge.fire(this);
	}
}

export class ViewletActivityAction extends ActivityAction {

	private static preventDoubleClickDelay = 300;

	private lastRun: number = 0;

	constructor(
		private viewlet: ViewletDescriptor,
		@IViewletService private viewletService: IViewletService,
		@IPartService private partService: IPartService
	) {
		super(viewlet.id, viewlet.name, viewlet.cssClass);
	}

	public run(event): TPromise<any> {
		if (event instanceof MouseEvent && event.button === 2) {
			return TPromise.as(false); // do not run on right click
		}

		// prevent accident trigger on a doubleclick (to help nervous people)
		const now = Date.now();
		if (now - this.lastRun < ViewletActivityAction.preventDoubleClickDelay) {
			return TPromise.as(true);
		}
		this.lastRun = now;

		const sideBarVisible = this.partService.isVisible(Parts.SIDEBAR_PART);
		const activeViewlet = this.viewletService.getActiveViewlet();

		// Hide sidebar if selected viewlet already visible
		if (sideBarVisible && activeViewlet && activeViewlet.getId() === this.viewlet.id) {
			return this.partService.setSideBarHidden(true);
		}

		return this.viewletService.openViewlet(this.viewlet.id, true)
			.then(() => this.activate());
	}
}

export class ActivityActionItem extends BaseActionItem {

	private static manageExtensionAction: ManageExtensionAction;
	private static toggleViewletPinnedAction: ToggleViewletPinnedAction;
	private static draggedViewlet: ViewletDescriptor;

	private $e: Builder;
	private name: string;
	private _keybinding: string;
	private cssClass: string;
	private $badge: Builder;
	private $badgeContent: Builder;
	private mouseUpTimeout: number;

	constructor(
		action: ActivityAction,
		private viewlet: ViewletDescriptor,
		@IContextMenuService private contextMenuService: IContextMenuService,
		@IActivityBarService private activityBarService: IActivityBarService,
		@IKeybindingService private keybindingService: IKeybindingService,
		@IInstantiationService instantiationService: IInstantiationService,
		@IThemeService private themeService: IThemeService
	) {
		super(null, action, { draggable: true });

		this.cssClass = action.class;
		this.name = viewlet.name;
		this._keybinding = this.getKeybindingLabel(viewlet.id);

		if (!ActivityActionItem.manageExtensionAction) {
			ActivityActionItem.manageExtensionAction = instantiationService.createInstance(ManageExtensionAction);
		}

		if (!ActivityActionItem.toggleViewletPinnedAction) {
			ActivityActionItem.toggleViewletPinnedAction = instantiationService.createInstance(ToggleViewletPinnedAction, void 0);
		}

		action.onDidChangeBadge(this.handleBadgeChangeEvenet, this, this._callOnDispose);
		this.themeService.onThemeChange(this.onThemeChange, this, this._callOnDispose);
	}

	private onThemeChange(theme: ITheme): void {
		this.updateStyles();
	}

	private updateStyles(): void {
		const theme = this.themeService.getTheme();
		const isHighContrastTheme = theme.type === 'hc';

		if (this.$badgeContent) {
			const foreground = theme.getColor(ACTIVITY_BADGE_FOREGROUND);
			const background = theme.getColor(ACTIVITY_BADGE_BACKGROUND);
			const hcBorder = theme.getColor(highContrastBorder);

			this.$badgeContent.style('color', foreground ? foreground.toString() : null);
			this.$badgeContent.style('background-color', background ? background.toString() : null);

			this.$badgeContent.style('border-style', isHighContrastTheme ? 'solid' : null);
			this.$badgeContent.style('border-width', isHighContrastTheme ? '1px' : null);
			this.$badgeContent.style('border-color', isHighContrastTheme && hcBorder ? hcBorder.toString() : null);
		}
	}

	private getKeybindingLabel(id: string): string {
		const kb = this.keybindingService.lookupKeybinding(id);
		if (kb) {
			return kb.getLabel();
		}

		return null;
	}

	public render(container: HTMLElement): void {
		super.render(container);

		this.$e = $('a.action-label').attr({
			tabIndex: '0',
			role: 'button'
		}).appendTo(this.builder);

		// Try hard to prevent keyboard only focus feedback when using mouse
		this.$e.on(DOM.EventType.MOUSE_DOWN, () => {
			this.$e.addClass('clicked');
		});

		this.$e.on(DOM.EventType.MOUSE_UP, () => {
			if (this.mouseUpTimeout) {
				clearTimeout(this.mouseUpTimeout);
			}

			this.mouseUpTimeout = setTimeout(() => {
				this.$e.removeClass('clicked');
			}, 800); // delayed to prevent focus feedback from showing on mouse up
		});

		$(container).on('contextmenu', e => {
			DOM.EventHelper.stop(e, true);

			this.showContextMenu(container);
		});

		if (this.cssClass) {
			this.$e.addClass(this.cssClass);
		}

		this.$badge = this.builder.div({ 'class': 'badge' }, (badge: Builder) => {
			this.$badgeContent = badge.div({ 'class': 'badge-content' });
		});

		this.$badge.hide();

		this.keybinding = this._keybinding; // force update

		// Activate on drag over to reveal targets
		[this.$badge, this.$e].forEach(b => new DelayedDragHandler(b.getHTMLElement(), () => {
			if (!ActivityActionItem.getDraggedViewlet() && !this.getAction().checked) {
				this.getAction().run();
			}
		}));

		// Allow to drag
		$(container).on(DOM.EventType.DRAG_START, (e: DragEvent) => {
			e.dataTransfer.effectAllowed = 'move';
			this.setDraggedViewlet(this.viewlet);

			// Trigger the action even on drag start to prevent clicks from failing that started a drag
			if (!this.getAction().checked) {
				this.getAction().run();
			}
		});

		// Drag enter
		let counter = 0; // see https://github.com/Microsoft/vscode/issues/14470
		$(container).on(DOM.EventType.DRAG_ENTER, (e: DragEvent) => {
			const draggedViewlet = ActivityActionItem.getDraggedViewlet();
			if (draggedViewlet && draggedViewlet.id !== this.viewlet.id) {
				counter++;
				this.updateFromDragging(container, true);
			}
		});

		// Drag leave
		$(container).on(DOM.EventType.DRAG_LEAVE, (e: DragEvent) => {
			const draggedViewlet = ActivityActionItem.getDraggedViewlet();
			if (draggedViewlet) {
				counter--;
				if (counter === 0) {
					this.updateFromDragging(container, false);
				}
			}
		});

		// Drag end
		$(container).on(DOM.EventType.DRAG_END, (e: DragEvent) => {
			const draggedViewlet = ActivityActionItem.getDraggedViewlet();
			if (draggedViewlet) {
				counter = 0;
				this.updateFromDragging(container, false);

				ActivityActionItem.clearDraggedViewlet();
			}
		});

		// Drop
		$(container).on(DOM.EventType.DROP, (e: DragEvent) => {
			DOM.EventHelper.stop(e, true);

			const draggedViewlet = ActivityActionItem.getDraggedViewlet();
			if (draggedViewlet && draggedViewlet.id !== this.viewlet.id) {
				this.updateFromDragging(container, false);
				ActivityActionItem.clearDraggedViewlet();

				this.activityBarService.move(draggedViewlet.id, this.viewlet.id);
			}
		});

		this.updateStyles();
	}

	private updateFromDragging(element: HTMLElement, isDragging: boolean): void {
		const theme = this.themeService.getTheme();
		const dragBackground = theme.getColor(ACTIVITY_BAR_DRAG_AND_DROP_BACKGROUND);

		element.style.backgroundColor = isDragging && dragBackground ? dragBackground.toString() : null;
	}

	public static getDraggedViewlet(): ViewletDescriptor {
		return ActivityActionItem.draggedViewlet;
	}

	private setDraggedViewlet(viewlet: ViewletDescriptor): void {
		ActivityActionItem.draggedViewlet = viewlet;
	}

	public static clearDraggedViewlet(): void {
		ActivityActionItem.draggedViewlet = void 0;
	}

	private showContextMenu(container: HTMLElement): void {
		const actions: Action[] = [ActivityActionItem.toggleViewletPinnedAction];
		if (this.viewlet.extensionId) {
			actions.push(new Separator());
			actions.push(ActivityActionItem.manageExtensionAction);
		}

		const isPinned = this.activityBarService.isPinned(this.viewlet.id);
		if (isPinned) {
			ActivityActionItem.toggleViewletPinnedAction.label = nls.localize('removeFromActivityBar', "Remove from Activity Bar");
		} else {
			ActivityActionItem.toggleViewletPinnedAction.label = nls.localize('keepInActivityBar', "Keep in Activity Bar");
		}

		this.contextMenuService.showContextMenu({
			getAnchor: () => container,
			getActionsContext: () => this.viewlet,
			getActions: () => TPromise.as(actions)
		});
	}

	public focus(): void {
		this.$e.domFocus();
	}

	public setBadge(badge: IBadge): void {
		this.updateBadge(badge);
	}

	public set keybinding(keybinding: string) {
		this._keybinding = keybinding;

		if (!this.$e) {
			return;
		}

		let title: string;
		if (keybinding) {
			title = nls.localize('titleKeybinding', "{0} ({1})", this.name, keybinding);
		} else {
			title = this.name;
		}

		this.$e.title(title);
		this.$badge.title(title);
	}

	private updateBadge(badge: IBadge): void {
		this.$badgeContent.empty();
		this.$badge.hide();

		if (badge) {

			// Number
			if (badge instanceof NumberBadge) {
				if (badge.number) {
					this.$badgeContent.text(badge.number > 99 ? '99+' : badge.number.toString());
					this.$badge.show();
				}
			}

			// Text
			else if (badge instanceof TextBadge) {
				this.$badgeContent.text(badge.text);
				this.$badge.show();
			}

			// Text
			else if (badge instanceof IconBadge) {
				this.$badge.show();
			}

			// Progress
			else if (badge instanceof ProgressBadge) {
				this.$badge.show();
			}

			this.$e.attr('aria-label', `${this.name} - ${badge.getDescription()}`);
		}
	}

	protected _updateClass(): void {
		if (this.cssClass) {
			this.$badge.removeClass(this.cssClass);
		}

		this.cssClass = this.getAction().class;
		this.$badge.addClass(this.cssClass);
	}

	protected _updateChecked(): void {
		if (this.getAction().checked) {
			this.$e.addClass('active');
		} else {
			this.$e.removeClass('active');
		}
	}

	private handleBadgeChangeEvenet(): void {
		const action = this.getAction();
		if (action instanceof ActivityAction) {
			this.updateBadge(action.getBadge());
		}
	}

	protected _updateEnabled(): void {
		if (this.getAction().enabled) {
			this.builder.removeClass('disabled');
		} else {
			this.builder.addClass('disabled');
		}
	}

	public dispose(): void {
		super.dispose();

		ActivityActionItem.clearDraggedViewlet();

		if (this.mouseUpTimeout) {
			clearTimeout(this.mouseUpTimeout);
		}

		this.$badge.destroy();
		this.$e.destroy();
	}
}

export class ViewletOverflowActivityAction extends ActivityAction {

	constructor(
		private showMenu: () => void
	) {
		super('activitybar.additionalViewlets.action', nls.localize('additionalViews', "Additional Views"), 'toggle-more');
	}

	public run(event): TPromise<any> {
		this.showMenu();

		return TPromise.as(true);
	}
}

export class ViewletOverflowActivityActionItem extends BaseActionItem {
	private $e: Builder;
	private name: string;
	private cssClass: string;
	private actions: OpenViewletAction[];

	constructor(
		action: ActivityAction,
		private getOverflowingViewlets: () => ViewletDescriptor[],
		private getBadge: (viewlet: ViewletDescriptor) => IBadge,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IViewletService private viewletService: IViewletService,
		@IKeybindingService private keybindingService: IKeybindingService,
		@IContextMenuService private contextMenuService: IContextMenuService,
	) {
		super(null, action);

		this.cssClass = action.class;
		this.name = action.label;
	}

	public render(container: HTMLElement): void {
		super.render(container);

		this.$e = $('a.action-label').attr({
			tabIndex: '0',
			role: 'button',
			title: this.name,
			class: this.cssClass
		}).appendTo(this.builder);
	}

	public showMenu(): void {
		if (this.actions) {
			dispose(this.actions);
		}

		this.actions = this.getActions();

		this.contextMenuService.showContextMenu({
			getAnchor: () => this.builder.getHTMLElement(),
			getActions: () => TPromise.as(this.actions),
			getKeyBinding: (action) => this.keybindingService.lookupKeybinding(action.id),
			onHide: () => dispose(this.actions)
		});
	}

	private getActions(): OpenViewletAction[] {
		const activeViewlet = this.viewletService.getActiveViewlet();

		return this.getOverflowingViewlets().map(viewlet => {
			const action = this.instantiationService.createInstance(OpenViewletAction, viewlet);
			action.radio = activeViewlet && activeViewlet.getId() === action.id;

			const badge = this.getBadge(action.viewlet);
			let suffix: string | number;
			if (badge instanceof NumberBadge) {
				suffix = badge.number;
			} else if (badge instanceof TextBadge) {
				suffix = badge.text;
			}

			if (suffix) {
				action.label = nls.localize('numberBadge', "{0} ({1})", action.viewlet.name, suffix);
			} else {
				action.label = action.viewlet.name;
			}

			return action;
		});
	}

	public dispose(): void {
		super.dispose();

		this.actions = dispose(this.actions);
	}
}

class ManageExtensionAction extends Action {

	constructor(
		@ICommandService private commandService: ICommandService
	) {
		super('activitybar.manage.extension', nls.localize('manageExtension', "Manage Extension"));
	}

	public run(viewlet: ViewletDescriptor): TPromise<any> {
		return this.commandService.executeCommand('_extensions.manage', viewlet.extensionId);
	}
}

class OpenViewletAction extends Action {

	constructor(
		private _viewlet: ViewletDescriptor,
		@IPartService private partService: IPartService,
		@IViewletService private viewletService: IViewletService
	) {
		super(_viewlet.id, _viewlet.name);
	}

	public get viewlet(): ViewletDescriptor {
		return this._viewlet;
	}

	public run(): TPromise<any> {
		const sideBarVisible = this.partService.isVisible(Parts.SIDEBAR_PART);
		const activeViewlet = this.viewletService.getActiveViewlet();

		// Hide sidebar if selected viewlet already visible
		if (sideBarVisible && activeViewlet && activeViewlet.getId() === this.viewlet.id) {
			return this.partService.setSideBarHidden(true);
		}

		return this.viewletService.openViewlet(this.viewlet.id, true);
	}
}

export class ToggleViewletPinnedAction extends Action {

	constructor(
		private viewlet: ViewletDescriptor,
		@IActivityBarService private activityBarService: IActivityBarService
	) {
		super('activitybar.show.toggleViewletPinned', viewlet ? viewlet.name : nls.localize('toggle', "Toggle View Pinned"));

		this.checked = this.viewlet && this.activityBarService.isPinned(this.viewlet.id);
	}

	public run(context?: ViewletDescriptor): TPromise<any> {
		const viewlet = this.viewlet || context;

		if (this.activityBarService.isPinned(viewlet.id)) {
			this.activityBarService.unpin(viewlet.id);
		} else {
			this.activityBarService.pin(viewlet.id);
		}

		return TPromise.as(true);
	}
}


text:
using System.IO;

namespace CASCExplorer
{
    public enum CASCGameType
    {
        Unknown,
        HotS,
        WoW,
        D3,
        S2,
        Agent,
        Hearthstone,
        Overwatch,
        Bna,
        Client
    }

    public class CASCGame
    {
        public static CASCGameType DetectLocalGame(string path)
        {
            if (Directory.Exists(Path.Combine(path, "HeroesData")))
                return CASCGameType.HotS;

            if (Directory.Exists(Path.Combine(path, "SC2Data")))
                return CASCGameType.S2;

            if (Directory.Exists(Path.Combine(path, "Hearthstone_Data")))
                return CASCGameType.Hearthstone;

            if (Directory.Exists(Path.Combine(path, "Data")))
            {
                if (File.Exists(Path.Combine(path, "Diablo III.exe")))
                    return CASCGameType.D3;

                if (File.Exists(Path.Combine(path, "Wow.exe")))
                    return CASCGameType.WoW;

                if (File.Exists(Path.Combine(path, "WowT.exe")))
                    return CASCGameType.WoW;

                if (File.Exists(Path.Combine(path, "WowB.exe")))
                    return CASCGameType.WoW;

                if (File.Exists(Path.Combine(path, "Agent.exe")))
                    return CASCGameType.Agent;

                if (File.Exists(Path.Combine(path, "Battle.net.exe")))
                    return CASCGameType.Bna;

                if (File.Exists(Path.Combine(path, "Overwatch Launcher.exe")))
                    return CASCGameType.Overwatch;
            }

            return CASCGameType.Unknown;
        }

        public static CASCGameType DetectOnlineGame(string uid)
        {
            if (uid.StartsWith("hero"))
                return CASCGameType.HotS;

            if (uid.StartsWith("hs"))
                return CASCGameType.Hearthstone;

            if (uid.StartsWith("s2"))
                return CASCGameType.S2;

            if (uid.StartsWith("wow"))
                return CASCGameType.WoW;

            if (uid.StartsWith("d3"))
                return CASCGameType.D3;

            if (uid.StartsWith("agent"))
                return CASCGameType.Agent;

            if (uid.StartsWith("pro"))
                return CASCGameType.Overwatch;

            if (uid.StartsWith("bna"))
                return CASCGameType.Bna;

            if (uid.StartsWith("clnt"))
                return CASCGameType.Client;

            return CASCGameType.Unknown;
        }

        public static string GetDataFolder(CASCGameType gameType)
        {
            if (gameType == CASCGameType.HotS)
                return "HeroesData";

            if (gameType == CASCGameType.S2)
                return "SC2Data";

            if (gameType == CASCGameType.Hearthstone)
                return "Hearthstone_Data";

            if (gameType == CASCGameType.WoW || gameType == CASCGameType.D3)
                return "Data";

            if (gameType == CASCGameType.Overwatch)
                return "data/casc";

            return null;
        }

        public static bool SupportsLocaleSelection(CASCGameType gameType)
        {
            return gameType == CASCGameType.D3 ||
                gameType == CASCGameType.WoW ||
                gameType == CASCGameType.HotS ||
                gameType == CASCGameType.S2 ||
                gameType == CASCGameType.Overwatch;
        }
    }
}


text:
<?php

namespace Keboola\StorageApi\Options\Components;

class SearchComponentConfigurationsOptions
{
    private $componentId;

    private $configurationId;

    private $metadataKeys;

    private $include;

    /**
     * @return string
     */
    public function getComponentId()
    {
        return $this->componentId;
    }

    /**
     * @param string $componentId
     * @return $this
     */
    public function setComponentId($componentId)
    {
        $this->componentId = $componentId;
        return $this;
    }

    /**
     * @return string
     */
    public function getConfigurationId()
    {
        return $this->configurationId;
    }

    /**
     * @param string $configurationId
     * @return $this
     */
    public function setConfigurationId($configurationId)
    {
        $this->configurationId = $configurationId;
        return $this;
    }

    /**
     * @return array
     */
    public function getMetadataKeys()
    {
        return $this->metadataKeys;
    }

    /**
     * @param array $metadataKeys
     */
    public function setMetadataKeys($metadataKeys)
    {
        $this->metadataKeys = $metadataKeys;
        return $this;
    }

    /**
     * @return array
     */
    public function getInclude()
    {
        return $this->include;
    }

    /**
     * @param array $include
     */
    public function setInclude($include)
    {
        $this->include = $include;
        return $this;
    }

    /**
     * @return string
     */
    public function getIncludeAsString()
    {
        return implode(',', $this->getInclude());
    }

    public function toParamsArray()
    {
        $params = [];

        if ($this->getComponentId()) {
            $params['idComponent'] = $this->getComponentId();
        }

        if ($this->getConfigurationId()) {
            $params['configurationId'] = $this->getConfigurationId();
        }

        if ($this->getMetadataKeys()) {
            $params['metadataKeys'] = $this->getMetadataKeys();
        }

        if ($this->getInclude()) {
            $params['include'] = $this->getIncludeAsString();
        }

        return $params;
    }
}


text:
<?php
namespace Yukar\Linq\Interfaces\Enumerable;

use Yukar\Linq\Collections\DictionaryObject;
use Yukar\Linq\Collections\ListObject;

/**
 * 単純な反復処理をサポートする機能を提供するインターフェイスです。
 */
interface IEnumerable extends ICalculation, IInspection, IExtract, IQuery, ISearch, ISet
{
    /**
     * シーケンスから新しい配列を作成します。
     *
     * @return array シーケンスから作成した新しい配列
     */
    public function toArray(): array;

    /**
     * シーケンスから新しいリストを作成します。
     *
     * @return ListObject シーケンスから作成した新しいリスト
     */
    public function toList(): ListObject;

    /**
     * シーケンスから新しい連想リストを作成します。
     *
     * @param \Closure $key_selector   各要素からキーを抽出する関数
     * @param \Closure $value_selector 各要素から値を抽出する関数
     *
     * @return DictionaryObject シーケンスから作成した新しい連想リスト
     */
    public function toDictionary(\Closure $key_selector, \Closure $value_selector = null): DictionaryObject;
}


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="testTableDefs" type="TestNG" factoryName="TestNG" nameIsGenerated="true">
    <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
      <pattern>
        <option name="PATTERN" value="uk.ac.bournemouth.kotlinsql.*" />
        <option name="ENABLED" value="true" />
      </pattern>
    </extension>
    <module name="kotlinsql_test" />
    <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
    <option name="ALTERNATIVE_JRE_PATH" />
    <option name="SUITE_NAME" value="" />
    <option name="PACKAGE_NAME" value="uk.ac.bournemouth.kotlinsql" />
    <option name="MAIN_CLASS_NAME" value="uk.ac.bournemouth.kotlinsql.testTableDefs" />
    <option name="METHOD_NAME" />
    <option name="GROUP_NAME" value="" />
    <option name="TEST_OBJECT" value="CLASS" />
    <option name="VM_PARAMETERS" value="-ea" />
    <option name="PARAMETERS" value="" />
    <option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
    <option name="OUTPUT_DIRECTORY" value="" />
    <option name="ANNOTATION_TYPE" />
    <option name="ENV_VARIABLES" />
    <option name="PASS_PARENT_ENVS" value="true" />
    <option name="TEST_SEARCH_SCOPE">
      <value defaultName="singleModule" />
    </option>
    <option name="USE_DEFAULT_REPORTERS" value="false" />
    <option name="PROPERTIES_FILE" value="" />
    <envs />
    <properties />
    <listeners />
    <method>
      <option name="Gradle.BeforeRunTask" enabled="true" tasks="testClasses" externalProjectPath="$PROJECT_DIR$" vmOptions="" scriptParameters="" />
    </method>
  </configuration>
</component>


text:
import { cloneList } from './_internals/cloneList.js'
import { curry } from './curry.js'

function adjustFn(
  index, replaceFn, list
){
  const actualIndex = index < 0 ? list.length + index : index
  if (index >= list.length || actualIndex < 0) return list

  const clone = cloneList(list)
  clone[ actualIndex ] = replaceFn(clone[ actualIndex ])

  return clone
}

export const adjust = curry(adjustFn)


text:
require 'spec_helper'

require 'google/api_client'
require 'google/api_client/version'

describe Google::APIClient::FileStore do
  let(:root_path) { File.expand_path(File.join(__FILE__, '..','..','..', '..','..')) }
  let(:json_file) { File.expand_path(File.join(root_path, 'fixtures', 'files', 'auth_stored_credentials.json')) }

  let(:credentials_hash) {{
      "access_token"=>"my_access_token",
      "authorization_uri"=>"https://accounts.google.com/o/oauth2/auth",
      "client_id"=>"123456_test_client_id@.apps.googleusercontent.com",
      "client_secret"=>"123456_client_secret",
      "expires_in"=>3600,
      "refresh_token"=>"my_refresh_token",
      "token_credential_uri"=>"https://accounts.google.com/o/oauth2/token",
      "issued_at"=>1384440275
  }}

  subject{Google::APIClient::FileStore.new('a file path')}

  it 'should have a path' do
    expect(subject.path).to be == 'a file path'
    subject.path = 'an other file path'
    expect(subject.path).to be == 'an other file path'
  end

  it 'should load credentials' do
    subject.path = json_file
    credentials = subject.load_credentials
    expect(credentials).to include('access_token', 'authorization_uri', 'refresh_token')
  end

  it 'should write credentials' do
    io_stub = StringIO.new
    expect(subject).to receive(:open).and_return(io_stub)
    subject.write_credentials(credentials_hash)
  end
end


text:
var env = require('../index.js')

describe('env-wrapper', function () {

  beforeEach(function () {
    expect(process.env.TEST_VARIABLE_PRESENT).toBe(undefined)
    expect(process.env.TEST_VARIABLE_NOT_PRESENT).toBe(undefined)
  })

  afterEach(function () {
    delete process.env.TEST_VARIABLE_PRESENT
    delete process.env.TEST_VARIABLE_NOT_PRESENT
  })

  describe('#load', function () {
    it('should load properties from a file', function () {
      env.load('./spec/test.env')
      expect(process.env.TEST_PROPERTY_ONE).toEqual('1')
    })
    it('should not throw an error if the file does not exist', function () {
      env.load('doesnt-exist.env')
    })
    it('should parse entries with embedded identifiers', function () {
      env.load('./spec/test.env')
      expect(process.env.TEST_PROPERTY_EMBEDDED).toEqual('this=has=embedded=identifiers')
    })
  })

  describe('#require', function () {
    it('should retrieve a known variable', function () {
      process.env.TEST_VARIABLE_PRESENT = 'xyz'
      expect(env.require('TEST_VARIABLE_PRESENT')).toEqual('xyz')
    })
    it('should retrieve a defaulted variable', function () {
      expect(env.require('TEST_VARIABLE_NOT_PRESENT', 'xyz')).toEqual('xyz')
    })
    it('should fail on an unknown variable with no default ', function () {
      expect(() => { env.require('TEST_VARIABLE_NOT_PRESENT') }).toThrow()
    })
  })

  describe('#get', function () {
    it('should get a known variable', function () {
      process.env.TEST_VARIABLE_PRESENT = 'xyz'
      expect(env.get('TEST_VARIABLE_PRESENT')).toEqual('xyz')
    })

    it('should get a defaulted variable', function () {
      env.require('TEST_VARIABLE_PRESENT', 'default-xyz')
      expect(env.get('TEST_VARIABLE_PRESENT')).toEqual('default-xyz')
    })

    it('should get an unknown variable', function () {
      expect(env.get('TEST_VARIABLE_PRESENT')).toBe(undefined)
    })
  })

})


text:
Given /^I have no users$/ do
  User.delete_all
end

Given /^I have a valid user$/ do
  User.delete_all
  Factory.create(:valid_user)
end

Given /^I should have ([0-9]+) user$/ do |count|
  User.count.should == count.to_i
end

Given /^I am a logged user$/ do
  User.delete_all
  @logged_in_user = Factory.create(:valid_user)
  visit login_path
  fill_in 'user_session_username', :with => @logged_in_user.username
  fill_in 'user_session_password', :with => @logged_in_user.password
  click_button "user_session_submit"
end

Given /^the user ([0-9]+) must have "(.*)" as "(.*)"/ do |id, value, field|
  user = User.find id
  user.send(field).should == value
end

Then /^I couldn't access to (.*)$/ do |page_name|

  if page_name =~ /^the ([a-zA-Z_]*) ([a-zA-Z_]*) page with id (.*) with method (.*)$/
    case $4
    when 'put'
      page.driver.put(path_to("the #{$1} #{$2} page with id #{$3}"))
    when 'delete'
      page.driver.delete(path_to("the #{$1} #{$2} page with id #{$3}"))
    else
      page.driver.post(path_to("the #{$1} #{$2} page with id #{$3}"))
    end
    page.should have_content("Vous devez vous connecter pour accéder à cette page.")
  else
    visit path_to(page_name)
    current_path = URI.parse(current_url).path
    page.should have_content("Vous devez vous connecter pour accéder à cette page.")
    current_path.should == "/"
  end

end
#
#Then /^I couldn't access to (.*) with method (.*)$/ do |page_name, method|
#  method path_to(page_name)
#
#  current_path = URI.parse(current_url).path
#  current_path.should == "/"
#  page.should have_content("Vous devez vous connecter pour accéder à cette page.")
#
#end


text:
#ifndef GRPCPP_SUPPORT_PROTO_BUFFER_WRITER_H
#define GRPCPP_SUPPORT_PROTO_BUFFER_WRITER_H

#include <grpcpp/impl/codegen/proto_buffer_writer.h>  // IWYU pragma: export

#endif  // GRPCPP_SUPPORT_PROTO_BUFFER_WRITER_H


text:
package org.encog.mathutil;

/**
 * Java will sometimes return Math.NaN or Math.Infinity when numbers get to
 * large or too small. This can have undesirable effects. This class provides
 * some basic math functions that may be in danger of returning such a value.
 * This class imposes a very large and small ceiling and floor to keep the
 * numbers within range.
 *
 * @author jheaton
 *
 */
public final class BoundMath {

	/**
	 * Calculate the cos.
	 *
	 * @param a
	 *            The value passed to the function.
	 * @return The result of the function.
	 */
	public static double cos(final double a) {
		return BoundNumbers.bound(Math.cos(a));
	}

	/**
	 * Calculate the exp.
	 *
	 * @param a
	 *            The value passed to the function.
	 * @return The result of the function.
	 */
	public static double exp(final double a) {
		return BoundNumbers.bound(Math.exp(a));
	}

	/**
	 * Calculate the log.
	 *
	 * @param a
	 *            The value passed to the function.
	 * @return The result of the function.
	 */
	public static double log(final double a) {
		return BoundNumbers.bound(Math.log(a));
	}

	/**
	 * Calculate the power of a number.
	 *
	 * @param a
	 *            The base.
	 * @param b
	 *            The exponent.
	 * @return The result of the function.
	 */
	public static double pow(final double a, final double b) {
		return BoundNumbers.bound(Math.pow(a, b));
	}

	/**
	 * Calculate the sin.
	 *
	 * @param a
	 *            The value passed to the function.
	 * @return The result of the function.
	 */
	public static double sin(final double a) {
		return BoundNumbers.bound(Math.sin(a));
	}

	/**
	 * Calculate the square root.
	 *
	 * @param a
	 *            The value passed to the function.
	 * @return The result of the function.
	 */
	public static double sqrt(final double a) {
		return Math.sqrt(a);
	}

	/**
	 * Private constructor.
	 */
	private BoundMath() {

	}

	/**
	 * Calculate TANH, within bounds.
	 * @param d The value to calculate for.
	 * @return The result.
	 */
	public static double tanh(final double d) {
		return BoundNumbers.bound(Math.tanh(d));
	}
}


text:
from cproton import PN_ACCEPTED, PN_MODIFIED, PN_RECEIVED, PN_REJECTED, PN_RELEASED, pn_delivery_abort, \
    pn_delivery_aborted, pn_delivery_attachments, pn_delivery_link, pn_delivery_local, pn_delivery_local_state, \
    pn_delivery_partial, pn_delivery_pending, pn_delivery_readable, pn_delivery_remote, pn_delivery_remote_state, \
    pn_delivery_settle, pn_delivery_settled, pn_delivery_tag, pn_delivery_update, pn_delivery_updated, \
    pn_delivery_writable, pn_disposition_annotations, pn_disposition_condition, pn_disposition_data, \
    pn_disposition_get_section_number, pn_disposition_get_section_offset, pn_disposition_is_failed, \
    pn_disposition_is_undeliverable, pn_disposition_set_failed, pn_disposition_set_section_number, \
    pn_disposition_set_section_offset, pn_disposition_set_undeliverable, pn_disposition_type, pn_work_next

from ._condition import cond2obj, obj2cond
from ._data import dat2obj, obj2dat
from ._wrapper import Wrapper

from typing import Dict, List, Optional, Type, Union, TYPE_CHECKING
if TYPE_CHECKING:
    from ._condition import Condition
    from ._endpoints import Receiver, Sender  # circular import
    from ._reactor import Connection, Session, Transport

class NamedInt(int):
    values: Dict[int, str] = {}

    def __new__(cls, i, name):
        ni = super(NamedInt, cls).__new__(cls, i)
        cls.values[i] = ni
        return ni

    def __init__(self, i: int, name: str) -> None:
        self.name = name

    def __repr__(self) -> str:
        return self.name

    def __str__(self) -> str:
        return self.name

    @classmethod
    def get(cls, i):
        return cls.values.get(i, i)

class DispositionType(NamedInt):
    values = {}

class Disposition(object):
    """
    A delivery state.

    Dispositions record the current state or final outcome of a
    transfer. Every delivery contains both a local and remote
    disposition. The local disposition holds the local state of the
    delivery, and the remote disposition holds the last known remote
    state of the delivery.
    """

    RECEIVED = DispositionType(PN_RECEIVED, "RECEIVED")
    """
    A non terminal state indicating how much (if any) message data
    has been received for a delivery.
    """

    ACCEPTED = DispositionType(PN_ACCEPTED, "ACCEPTED")
    """
    A terminal state indicating that the delivery was successfully
    processed. Once in this state there will be no further state
    changes prior to the delivery being settled.
    """

    REJECTED = DispositionType(PN_REJECTED, "REJECTED")
    """
    A terminal state indicating that the delivery could not be
    processed due to some error condition. Once in this state
    there will be no further state changes prior to the delivery
    being settled.
    """

    RELEASED = DispositionType(PN_RELEASED, "RELEASED")
    """
    A terminal state indicating that the delivery is being
    returned to the sender. Once in this state there will be no
    further state changes prior to the delivery being settled.
    """

    MODIFIED = DispositionType(PN_MODIFIED, "MODIFIED")
    """
    A terminal state indicating that the delivery is being
    returned to the sender and should be annotated by the
    sender prior to further delivery attempts. Once in this
    state there will be no further state changes prior to the
    delivery being settled.
    """

    def __init__(self, impl, local):
        self._impl = impl
        self.local = local
        self._data = None
        self._condition = None
        self._annotations = None

    @property
    def type(self):
        """
        Get the type of this disposition object.

        Defined values are:

        * :const:`RECEIVED`
        * :const:`ACCEPTED`
        * :const:`REJECTED`
        * :const:`RELEASED`
        * :const:`MODIFIED`

        :type: ``str``
        """
        return DispositionType.get(pn_disposition_type(self._impl))

    def _get_section_number(self):
        return pn_disposition_get_section_number(self._impl)

    def _set_section_number(self, n):
        pn_disposition_set_section_number(self._impl, n)

    section_number = property(_get_section_number, _set_section_number, doc="""
        The section number associated with a disposition.

        :type: ``int``
        """)

    def _get_section_offset(self):
        return pn_disposition_get_section_offset(self._impl)

    def _set_section_offset(self, n):
        pn_disposition_set_section_offset(self._impl, n)

    section_offset = property(_get_section_offset, _set_section_offset, doc="""
        The section offset associated with a disposition.

        :type: ``int``
        """)

    def _get_failed(self):
        return pn_disposition_is_failed(self._impl)

    def _set_failed(self, b):
        pn_disposition_set_failed(self._impl, b)

    failed = property(_get_failed, _set_failed, doc="""
        The failed flag for this disposition.

        :type: ``bool``
        """)

    def _get_undeliverable(self):
        return pn_disposition_is_undeliverable(self._impl)

    def _set_undeliverable(self, b):
        pn_disposition_set_undeliverable(self._impl, b)

    undeliverable = property(_get_undeliverable, _set_undeliverable, doc="""
        The undeliverable flag for this disposition.

        :type: ``bool``
        """)

    def _get_data(self):
        if self.local:
            return self._data
        else:
            return dat2obj(pn_disposition_data(self._impl))

    def _set_data(self, obj):
        if self.local:
            self._data = obj
        else:
            raise AttributeError("data attribute is read-only")

    data = property(_get_data, _set_data, doc="""
        Access the disposition as a :class:`Data` object.

        Dispositions are an extension point in the AMQP protocol. The
        disposition interface provides setters/getters for those
        dispositions that are predefined by the specification, however
        access to the raw disposition data is provided so that other
        dispositions can be used.

        The :class:`Data` object returned by this operation is valid until
        the parent delivery is settled.

        :type: :class:`Data`
        """)

    def _get_annotations(self):
        if self.local:
            return self._annotations
        else:
            return dat2obj(pn_disposition_annotations(self._impl))

    def _set_annotations(self, obj):
        if self.local:
            self._annotations = obj
        else:
            raise AttributeError("annotations attribute is read-only")

    annotations = property(_get_annotations, _set_annotations, doc="""
        The annotations associated with a disposition.

        The :class:`Data` object retrieved by this operation may be modified
        prior to updating a delivery. When a delivery is updated, the
        annotations described by the :class:`Data` are reported to the peer
        if applicable to the current delivery state, e.g. states such as
        :const:`MODIFIED`. The :class:`Data` must be empty or contain a symbol
        keyed map.

        The :class:`Data` object returned by this operation is valid until
        the parent delivery is settled.

        :type: :class:`Data`
        """)

    def _get_condition(self):
        if self.local:
            return self._condition
        else:
            return cond2obj(pn_disposition_condition(self._impl))

    def _set_condition(self, obj):
        if self.local:
            self._condition = obj
        else:
            raise AttributeError("condition attribute is read-only")

    condition = property(_get_condition, _set_condition, doc="""
        The condition object associated with a disposition.

        The :class:`Condition` object retrieved by this operation may be
        modified prior to updating a delivery. When a delivery is updated,
        the condition described by the disposition is reported to the peer
        if applicable to the current delivery state, e.g. states such as
        :const:`REJECTED`.

        :type: :class:`Condition`
        """)

class Delivery(Wrapper):
    """
    Tracks and/or records the delivery of a message over a link.
    """

    RECEIVED = Disposition.RECEIVED
    """
    A non terminal state indicating how much (if any) message data
    has been received for a delivery.
    """

    ACCEPTED = Disposition.ACCEPTED
    """
    A terminal state indicating that the delivery was successfully
    processed. Once in this state there will be no further state
    changes prior to the delivery being settled.
    """

    REJECTED = Disposition.REJECTED
    """
    A terminal state indicating that the delivery could not be
    processed due to some error condition. Once in this state
    there will be no further state changes prior to the delivery
    being settled.
    """

    RELEASED = Disposition.RELEASED
    """
    A terminal state indicating that the delivery is being
    returned to the sender. Once in this state there will be no
    further state changes prior to the delivery being settled.
    """

    MODIFIED = Disposition.MODIFIED
    """
    A terminal state indicating that the delivery is being
    returned to the sender and should be annotated by the
    sender prior to further delivery attempts. Once in this
    state there will be no further state changes prior to the
    delivery being settled.
    """

    @staticmethod
    def wrap(impl):
        if impl is None:
            return None
        else:
            return Delivery(impl)

    def __init__(self, impl):
        Wrapper.__init__(self, impl, pn_delivery_attachments)

    def _init(self) -> None:
        self.local = Disposition(pn_delivery_local(self._impl), True)
        self.remote = Disposition(pn_delivery_remote(self._impl), False)

    @property
    def tag(self):
        """
        The identifier for the delivery.

        :type: ``bytes``
        """
        return pn_delivery_tag(self._impl)

    @property
    def writable(self) -> bool:
        """
        ``True`` for an outgoing delivery to which data can now be written,
        ``False`` otherwise..
        """
        return pn_delivery_writable(self._impl)

    @property
    def readable(self) -> bool:
        """
        ``True`` for an incoming delivery that has data to read,
        ``False`` otherwise..
        """
        return pn_delivery_readable(self._impl)

    @property
    def updated(self) -> bool:
        """
        ``True`` if the state of the delivery has been updated
        (e.g. it has been settled and/or accepted, rejected etc),
        ``False`` otherwise.
        """
        return pn_delivery_updated(self._impl)

    def update(self, state: Union[int, DispositionType]) -> None:
        """
        Set the local state of the delivery e.g. :const:`ACCEPTED`,
        :const:`REJECTED`, :const:`RELEASED`.

        :param state: State of delivery
        """
        obj2dat(self.local._data, pn_disposition_data(self.local._impl))
        obj2dat(self.local._annotations, pn_disposition_annotations(self.local._impl))
        obj2cond(self.local._condition, pn_disposition_condition(self.local._impl))
        pn_delivery_update(self._impl, state)

    @property
    def pending(self) -> int:
        """
        The amount of pending message data for a delivery.
        """
        return pn_delivery_pending(self._impl)

    @property
    def partial(self) -> bool:
        """
        ``True`` for an incoming delivery if not all the data is
        yet available, ``False`` otherwise.
        """
        return pn_delivery_partial(self._impl)

    @property
    def local_state(self):
        """
        A string representation of the local state of the delivery.

        :type: ``str``
        """
        return DispositionType.get(pn_delivery_local_state(self._impl))

    @property
    def remote_state(self):
        """
        A string representation of the state of the delivery as
        indicated by the remote peer.

        :type: ``str``
        """
        return DispositionType.get(pn_delivery_remote_state(self._impl))

    @property
    def settled(self) -> bool:
        """
        ``True`` if the delivery has been settled by the remote peer,
        ``False`` otherwise.
        """
        return pn_delivery_settled(self._impl)

    def settle(self) -> None:
        """
        Settles the delivery locally. This indicates the application
        considers the delivery complete and does not wish to receive any
        further events about it. Every delivery should be settled locally.
        """
        pn_delivery_settle(self._impl)

    @property
    def aborted(self) -> bool:
        """
        ``True`` if the delivery has been aborted, ``False`` otherwise.
        """
        return pn_delivery_aborted(self._impl)

    def abort(self) -> None:
        """
        Aborts the delivery.  This indicates the application wishes to
        invalidate any data that may have already been sent on this delivery.
        The delivery cannot be aborted after it has been completely delivered.
        """
        pn_delivery_abort(self._impl)

    @property
    def work_next(self) -> Optional['Delivery']:
        """Deprecated: use on_message(), on_accepted(), on_rejected(),
        on_released(), and on_settled() instead.

        The next :class:`Delivery` on the connection that has pending
        operations.
        """
        return Delivery.wrap(pn_work_next(self._impl))

    @property
    def link(self) -> Union['Receiver', 'Sender']:
        """
        The :class:`Link` on which the delivery was sent or received.
        """
        from . import _endpoints
        return _endpoints.Link.wrap(pn_delivery_link(self._impl))

    @property
    def session(self) -> 'Session':
        """
        The :class:`Session` over which the delivery was sent or received.
        """
        return self.link.session

    @property
    def connection(self) -> 'Connection':
        """
        The :class:`Connection` over which the delivery was sent or received.
        """
        return self.session.connection

    @property
    def transport(self) -> 'Transport':
        """
        The :class:`Transport` bound to the :class:`Connection` over which
        the delivery was sent or received.
        """
        return self.connection.transport


text:
<?php

namespace App\Providers;

use App\Repositories\PeopleRepository;
use App\Repositories\ProfileRepository;
use Contracts\Repositories\ProfileRepositoryContract;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Waynestate\Api\Connector;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Storage;

class AppServiceProvider extends ServiceProvider
{
    /** @var $prefx **/
    protected $prefix = 'App';

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('image', function ($expression) {
            // Since all paramters are concated into a string we need to parse them out into an array
            $params = explode(',', $expression);

            // We have three parameters that are optional so we need to set them as blank strings if they weren't passed in
            for ($i=0; $i <= 2; $i++) {
                if (empty($params[$i])) {
                    $params[$i] = "''";
                }
            }

            return "<?php echo view('components.image-lazy', ['src' => $params[0], 'alt' => $params[1], 'class' => $params[2]])->render(); ?>";
        });

        Blade::directive('svg', function ($expression) {
            // Since all paramters are concated into a string we need to parse them out into an array
            $params = explode(',', $expression);

            // Default the label to the title
            if (empty($params[2])) {
                $params[2] = $params[0];
            }

            // We have three parameters that are optional so we need to set them as blank strings if they weren't passed in
            for ($i=0; $i <= 2; $i++) {
                if (empty($params[$i])) {
                    $params[$i] = "''";
                }
            }

            return "<?php if(view()->exists('svg.'.strtolower(trim(".$params[0].")))) { echo view('svg.'.strtolower(trim(".$params[0].")), ['name' => strtolower(trim($params[0])), 'class' => $params[1], 'label' => strtolower(trim($params[2]))])->render(); } ?>";
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if (using_styleguide()) {
            $this->prefix = 'Styleguide';
        }

        // WSU API
        $this->app->bind('Waynestate\Api\Connector', function () {
            $api = new Connector(
                config('base.wsu_api_key')
            );

            return $api;
        });

        // Bind all repositories following the filename convention
        collect(Storage::disk('base')->allFiles('contracts'))
            ->reject(function ($filename) {
                return in_array(basename($filename), ['RequestDataRepositoryContract.php', 'ProfileRepositoryContract.php']);
            })
            ->each(function ($filename) {
                $this->app->bind('Contracts\Repositories\\'.basename($filename, '.php'), $this->getPrefix().'\Repositories\\'.basename(str_replace('Contract', '', $filename), '.php'));
            });

        // Get the Site Information to determine if we load the ProfileRepository or PeopleRepository
        try {
            $site = json_decode(Storage::disk('public')->get('index.json'), true);
        } catch (FileNotFoundException $e) {
            $site = [];
        }
        if (!using_styleguide() && empty($site['site']['people']['site_id'])) {
            $this->app->bind(ProfileRepositoryContract::class, ProfileRepository::class);
        } elseif (using_styleguide()) {
            $this->app->bind(ProfileRepositoryContract::class, \Styleguide\Repositories\PeopleRepository::class);
        } else {
            $this->app->bind(ProfileRepositoryContract::class, PeopleRepository::class);
        }
    }

    /**
     * Get the prefix.
     *
     * @return string
     */
    public function getPrefix()
    {
        return $this->prefix;
    }
}


text:
module Rubinius
  module Bridge
    VERSION = "3.0"
  end
end