text:
static CGFloat const kEvstEditorsPickContentAreaHeight = 25.f;

@interface EvstMomentCellBase ()
@property (nonatomic, strong) EvstMomentCellEditorsPickView *editorsPickView;
@property (nonatomic, strong) EvstMomentCellTagsView *cellTagsView;
@property (nonatomic, strong) EvstMomentCellLikesCommentsView *cellLikesCommentsView;
@property (nonatomic, strong) EvstMomentCellDeletedOverlayView *deletedCellOverlay;
@property (nonatomic, strong) MASConstraint *userHeaderYConstraint;
@end

@implementation EvstMomentCellBase

#pragma mark - Class Init

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
  self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
  if (self) {
    [self commonSetup];
  }
  return self;
}

#pragma mark - Setup

- (void)commonSetup {
  self.opaque = YES;
  self.backgroundColor = kColorWhite;
  self.selectionStyle = UITableViewCellSelectionStyleNone;
  self.layer.shouldRasterize = YES;
  self.layer.rasterizationScale = [UIScreen mainScreen].scale;
  self.contentView.accessibilityLabel = kLocaleMomentTableCell;

  [self setupEditorsPickView];
  [self setupHeaderView];
  [self setupTagsView];
  [self setupContentView];
  [self setupFooterView];
  [self setupDoubleTapToLike];
  [self setupSpotlightGesture];
}

- (void)setupEditorsPickView {
  self.editorsPickView = [[EvstMomentCellEditorsPickView alloc] init];
  [self.contentView addSubview:self.editorsPickView];
  [self.editorsPickView makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.contentView.top);
    make.left.equalTo(self.contentView.left);
    make.right.equalTo(self.contentView.right);
    make.height.equalTo([NSNumber numberWithFloat:kEvstEditorsPickContentAreaHeight]);
  }];
  self.editorsPickView.accessibilityLabel = kLocaleEditorsPick;
  self.editorsPickView.hidden = YES;
}

- (void)setupHeaderView {
  self.cellHeaderView = [[EvstSharedCellUserHeaderView alloc] init];
  [self.contentView addSubview:self.cellHeaderView];
  [self.cellHeaderView makeConstraints:^(MASConstraintMaker *make) {
    // The top constraint is set in the configure method based on whether it's an editor's pick or not
    make.left.equalTo(self.contentView.left);
    make.right.equalTo(self.contentView.right);
    make.height.equalTo([NSNumber numberWithDouble:kEvstSharedCellUserHeaderViewHeight]);
  }];
}

- (void)setupTagsView {
  self.cellTagsView = [[EvstMomentCellTagsView alloc] init];
  [self.contentView addSubview:self.cellTagsView];
  [self.cellTagsView makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.equalTo(self.contentView.bottom).offset(-(kEvstMomentLikesCommentsViewHeight + kEvstMomentContentPadding + 2.f)).priorityHigh();
    make.left.equalTo(self.contentView.left);
    make.right.equalTo(self.contentView.right);
  }];
}

- (void)setupContentView {
  self.cellContentView = [self contentViewInstance];
  [self.contentView addSubview:self.cellContentView];
  [self.cellContentView makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.cellHeaderView.bottom).offset(-kEvstDefaultPadding);
    make.left.equalTo(self.contentView.left);
    make.right.equalTo(self.contentView.right);
  }];
}

- (id)contentViewInstance {
  ZAssert(NO, @"Subclasses should override this method and provide their own implementation.");
  return nil;
}

- (void)setupFooterView {
  self.cellLikesCommentsView = [[EvstMomentCellLikesCommentsView alloc] init];
  [self.contentView addSubview:self.cellLikesCommentsView];
  [self.cellLikesCommentsView makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.equalTo(self.contentView.bottom);
    make.left.equalTo(self.contentView.left);
    make.right.equalTo(self.contentView.right);
    make.height.equalTo([NSNumber numberWithDouble:kEvstMomentLikesCommentsViewHeight]);
  }];
}

- (void)setupBottomSeparator {
  UIImageView *bottomSeparator = [[UIImageView alloc] initWithImage:[EvstCommon tableSeparatorLine]];
  [self.contentView addSubview:bottomSeparator];
  [bottomSeparator makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.contentView.left);
    make.right.equalTo(self.contentView.right);
    make.bottom.equalTo(self.contentView.bottom);
    make.height.equalTo([NSNumber numberWithFloat:0.5f]);
  }];
}

- (void)setupDoubleTapToLike {
  UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTapGesture:)];
  tapGesture.numberOfTapsRequired = 2;
  tapGesture.cancelsTouchesInView = YES;
  tapGesture.delaysTouchesBegan = YES;
  [self.contentView addGestureRecognizer:tapGesture];
}

- (void)setupSpotlightGesture {
  UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSpotlightGesture:)];
  tapGesture.numberOfTapsRequired = 2;
  tapGesture.numberOfTouchesRequired = 2;
  tapGesture.cancelsTouchesInView = YES;
  tapGesture.delaysTouchesBegan = YES;
  [self.contentView addGestureRecognizer:tapGesture];
}

#pragma mark - Double Tap To Like

- (void)handleDoubleTapGesture:(UITapGestureRecognizer *)sender {
  if (sender.state == UIGestureRecognizerStateRecognized) {
    if (self.cellContentView.moment && self.cellLikesCommentsView.likeButton) {
      NSDictionary *info = @{kEvstDictionaryMomentKey : self.cellContentView.moment,
                             kEvstDictionaryButtonKey : self.cellLikesCommentsView.likeButton,
                             kEvstDictionaryDoubleTapKey : @YES };
      [[NSNotificationCenter defaultCenter] postNotificationName:kEvstLikeButtonWasPressedNotification object:nil userInfo:info];
    }
  }
}

#pragma mark - Spotlighting

- (void)handleSpotlightGesture:(UITapGestureRecognizer *)sender {
  if (sender.state == UIGestureRecognizerStateRecognized && self.cellContentView.moment) {
    [[NSNotificationCenter defaultCenter] postNotificationName:kEvstMomentSpotlightShouldChangeNotification object:self.cellContentView.moment];
  }
}

#pragma mark - Prepare For Reuse

- (void)prepareForReuse {
  [super prepareForReuse];

  [self.editorsPickView prepareForReuse];
  self.editorsPickView.hidden = YES;
  [self.cellHeaderView prepareForReuse];
  [self.cellTagsView prepareForReuse];
  [self.cellContentView prepareForReuse];
  [self.cellLikesCommentsView prepareForReuse];
  self.deletedCellOverlay.hidden = YES;
}

#pragma mark - Configurations

- (void)configureWithMoment:(EverestMoment *)moment withOptions:(EvstMomentViewOptions)options {
  // Don't set up an editor's pick area for lifecycle cell types
  if (moment.isLifecycleMoment == NO) {
    // Editor's Pick area (if necessary)
    [self.userHeaderYConstraint uninstall];
    BOOL shouldShowEditorsPick = moment.isEditorsPick && (options & EvstMomentCanShowEditorsPickHeader);
    CGFloat offset = shouldShowEditorsPick ? kEvstEditorsPickContentAreaHeight : 0.f;
    [self.cellHeaderView updateConstraints:^(MASConstraintMaker *make) {
      self.userHeaderYConstraint = make.top.equalTo(self.contentView.top).offset(offset);
    }];
    if (shouldShowEditorsPick) {
      [self.editorsPickView configureWithMoment:moment withOptions:options];
      self.editorsPickView.hidden = NO;
    }
  }

  [self.cellHeaderView configureWithMoment:moment withOptions:options];
  [self.cellContentView configureWithMoment:moment withOptions:options];

  // Check if there are tags to show
  if (moment.tags.count > 0) {
    [self.cellTagsView configureWithMoment:moment withOptions:options];
    self.cellTagsView.hidden = NO;
  } else {
    self.cellTagsView.hidden = YES;;
  }

  [self.cellLikesCommentsView configureWithMoment:moment withOptions:options];
  BOOL forCommentsHeader = options & EvstMomentShownInCommentsHeader;
  if (forCommentsHeader) {
    [self setupBottomSeparator];
  }
  // Since it's not very performant to do this in a configure method,
  // only create the overlay if it hasn't already been created
  if (moment.associatedJourneyWasDeleted && !self.deletedCellOverlay) {
    self.deletedCellOverlay = [[EvstMomentCellDeletedOverlayView alloc] init];
    [self.contentView addSubview:self.deletedCellOverlay];
    [self.deletedCellOverlay makeConstraints:^(MASConstraintMaker *make) {
      make.edges.equalTo(self.contentView);
    }];
  }
  self.deletedCellOverlay.hidden = !moment.associatedJourneyWasDeleted;
}

#pragma mark - Cell Calculations

+ (CGFloat)cellHeightForMoment:(EverestMoment *)moment withOptions:(EvstMomentViewOptions)options fromCacheIfAvailable:(BOOL)fromCache {
  BOOL shouldShowEditorsPick = (moment.isEditorsPick && (options & EvstMomentCanShowEditorsPickHeader));
  CGFloat topPadding = shouldShowEditorsPick ? kEvstEditorsPickContentAreaHeight : 0.f;
  return topPadding + kEvstSharedCellUserHeaderViewHeight + [self heightForContentAreaWithMoment:moment withOptions:options fromCacheIfAvailable:fromCache] + kEvstMomentLikesCommentsViewHeight;
}

+ (CGFloat)heightForContentAreaWithMoment:(EverestMoment *)moment withOptions:(EvstMomentViewOptions)options fromCacheIfAvailable:(BOOL)fromCache {
  CGFloat (^calculateHeight)() = ^CGFloat() {
    CGFloat calculatedHeight = [self calculatedContentHeightForMoment:moment withOptions:options];
    // If we wanted a value from cache but there was none, we should cache the new value.  Otherwise,
    // don't cache calculated values since it's most likely for showing the moment in the comments view
    if (fromCache) {
      [[EvstCellCache sharedCache] cacheCellHeight:calculatedHeight forUUID:moment.uuid withMomentOptions:options];
    }
    return calculatedHeight;
  };

  if (fromCache) {
    NSNumber *momentHeight = [[EvstCellCache sharedCache] cachedCellHeightForUUID:moment.uuid withMomentOptions:options];
    if (momentHeight) {
      return [momentHeight floatValue];
    } else {
      return calculateHeight();
    }
  } else {
    return calculateHeight();
  }
}

+ (CGFloat)calculatedContentHeightForMoment:(EverestMoment *)moment withOptions:(EvstMomentViewOptions)options {
  ZAssert(NO, @"Subclasses should override this method and provide their own implementation.");
  return 0.f;
}

#pragma mark - Shared Methods

+ (CGFloat)heightOfTextForMoment:(EverestMoment *)moment withJourneyName:(BOOL)withJourneyName {
  if (!moment.name.length && !withJourneyName) {
    return 0.f;
  }

  CGSize constraintSize = CGSizeMake([self cellContentWidth], CGFLOAT_MAX);
  NSString *text = withJourneyName ? [self momentContentWithJourneyNameForMoment:moment] : moment.name;
  NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
  paragraphStyle.lineHeightMultiple = kEvstMomentPlainTextLineHeightMultiple;
  paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
  NSDictionary *attributes = @{NSFontAttributeName : kFontMomentContent, NSParagraphStyleAttributeName : paragraphStyle};
  NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:text attributes:attributes];
  CGSize size = [EvstAttributedLabel sizeThatFitsAttributedString:attrString withConstraints:constraintSize limitedToNumberOfLines:0];

  return ceil(size.height + kEvstMomentContentBottomMargin);
}

+ (CGFloat)heightOfTagsForMoment:(EverestMoment *)moment shownExpanded:(BOOL)showExpanded {
  if (moment.tags.count == 0) {
    return 0.f;
  } else if (moment.tags.count == 1 || showExpanded == NO) {
    return kEvstMomentTagAreaDefaultHeight;
  } else if (showExpanded) {
    CGSize constraintSize = CGSizeMake([EvstMomentCellTagsView contentWidth], CGFLOAT_MAX);
    NSString *text = [EvstMomentCellTagsView stringByJoiningTags:moment.tags.array];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineHeightMultiple:kEvstMomentTagLineHeightMultiple];
    NSDictionary *attributes = @{NSFontAttributeName : kFontMomentTag, NSParagraphStyleAttributeName : paragraphStyle};
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:text attributes:attributes];
    CGSize size = [EvstAttributedLabel sizeThatFitsAttributedString:attrString withConstraints:constraintSize limitedToNumberOfLines:0];
    return MAX(kEvstMomentTagAreaDefaultHeight, ceil(size.height + kEvstDefaultPadding)); // Set a minimum height
  }
  return 0.f;
}

+ (CGFloat)cellContentWidth {
  return kEvstMainScreenWidth - kEvstMomentContentPadding * 2.f;
}

+ (NSString *)momentContentWithJourneyNameForMoment:(EverestMoment *)moment {
  return [self momentContent:moment.name withJourneyName:[self inJourneyNameForMoment:moment]];
}

+ (NSString *)inJourneyNameForMoment:(EverestMoment *)moment {
  return [NSString stringWithFormat:@"%@ %@", kLocaleIn, moment.journey.name];
}

+ (NSString *)momentContent:(NSString *)momentContent withJourneyName:(NSString *)inJourneyName {
  return (momentContent.length) ? [NSString stringWithFormat:@"%@ %@", momentContent, inJourneyName] : inJourneyName;
}

@end


text:
import { Component } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';
import { AlertController, ToastController, LoadingController } from 'ionic-angular';
import { DomSanitizer } from '@angular/platform-browser';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

import { GlobalVars } from '../providers/globalvars';
import { AuthService} from '../providers/auth-service';

import { SaveDoseLoginPage } from '../save-dose-login/save-dose-login';

@Component({
  selector: 'page-save-dose-register',
  templateUrl: 'save-dose-register.html'
})
export class SaveDoseRegisterPage {

  AbsoluteURL: string;
  html_data: any;
  registerCredentials = {'name': '', 'email': '', 'password': '', 'confirm': '', 'city': '', 'gender': '', 'newsletter': ''};
  constructor(public navCtrl: NavController, public menu: MenuController, private authService: AuthService,
      public alertCtrl: AlertController, public loadingCtrl: LoadingController, public toastCtrl: ToastController,
      public http: Http, private sanitizer: DomSanitizer) {
  	this.menu = menu;
  	this.AbsoluteURL = GlobalVars.getAbsoluteURL();
  }
  getHtmlData(){
    this.html_data = null;
    this.http.get("assets/json/save_dose_register.json").map(response => response.json()).subscribe(data => {
        this.html_data = data;
    });
  }
  showMenu() {
  	this.menu.open();
  }
  registerPage(){
  	this.authService.setMainPage(this);
  	this.authService.setLoginPage(SaveDoseLoginPage);
  	this.authService.register(this.registerCredentials);
  }
  ionViewDidLoad() {
    this.getHtmlData();
  }

}

redpajama_set_name: RedPajamaGithub


text:
import hammerhead from '../../deps/hammerhead';
import testCafeCore from '../../deps/testcafe-core';
import testCafeUI from '../../deps/testcafe-ui';
import MoveAutomation from '../move';
import { MoveOptions } from '../../../../test-run/commands/options';
import { getDefaultAutomationOffsets } from '../../utils/offsets';
import AutomationSettings from '../../settings';

var Promise = hammerhead.Promise;

var browserUtils     = hammerhead.utils.browser;
var eventSimulator   = hammerhead.eventSandbox.eventSimulator;
var focusBlurSandbox = hammerhead.eventSandbox.focusBlur;

var domUtils   = testCafeCore.domUtils;
var styleUtils = testCafeCore.styleUtils;
var delay      = testCafeCore.delay;

var selectElementUI = testCafeUI.selectElement;

const FOCUS_DELAY = browserUtils.isTouchDevice ? 0 : 160;

export default class SelectChildClickAutomation {
    constructor (element, clickOptions) {
        this.element   = element;
        this.modifiers = clickOptions.modifiers;
        this.caretPos  = clickOptions.caretPos;

        this.offsetX = clickOptions.offsetX;
        this.offsetY = clickOptions.offsetY;
        this.speed   = clickOptions.speed;

        this.automationSettings = new AutomationSettings(clickOptions.speed);

        this.parentSelect       = domUtils.getSelectParent(this.element);
        this.optionListExpanded = this.parentSelect ? selectElementUI.isOptionListExpanded(this.parentSelect) : false;
        this.childIndex         = null;
        this.clickCausesChange  = false;

        if (this.parentSelect) {
            var isOption      = domUtils.isOptionElement(this.element);
            var selectedIndex = this.parentSelect.selectedIndex;

            this.childIndex = isOption ? domUtils.getOptionIndex(this.parentSelect, this.element) :
                              domUtils.getOptionGroupIndex(this.parentSelect, this.element);

            var parentOptGroup = domUtils.isOptionGroupElement(this.element.parentNode) ? this.element.parentNode : null;
            var isDisabled     = this.element.disabled || parentOptGroup && parentOptGroup.disabled;

            this.clickCausesChange = isOption && !isDisabled && this.childIndex !== selectedIndex;
        }

        this.eventsArgs = {
            options: this.modifiers,
            element: this.element
        };
    }

    _calculateEventArguments () {
        var childElement     = this.optionListExpanded ? selectElementUI.getEmulatedChildElement(this.element) : this.element;
        var parentSelectSize = styleUtils.getSelectElementSize(this.parentSelect) > 1;

        return {
            options: this.modifiers,
            element: browserUtils.isIE && parentSelectSize ? this.parentSelect : childElement
        };
    }

    _getMoveArguments () {
        var element = null;
        var offsetX = null;
        var offsetY = null;

        if (this.optionListExpanded) {
            element = selectElementUI.getEmulatedChildElement(this.element);

            var moveActionOffsets = getDefaultAutomationOffsets(element);

            offsetX = moveActionOffsets.offsetX;
            offsetY = moveActionOffsets.offsetY;
        }
        else {
            element = document.documentElement;

            var elementCenter = selectElementUI.getSelectChildCenter(this.element);

            offsetX = elementCenter.x;
            offsetY = elementCenter.y;
        }

        return { element, offsetX, offsetY, speed: this.speed };
    }

    _move ({ element, offsetX, offsetY, speed }) {
        var moveOptions = new MoveOptions({
            offsetX,
            offsetY,
            speed,

            modifiers: this.modifiers
        }, false);

        var moveAutomation = new MoveAutomation(element, moveOptions);

        return moveAutomation
            .run()
            .then(() => delay(this.automationSettings.mouseActionStepDelay));
    }

    _mousedown () {
        if (browserUtils.isFirefox) {
            eventSimulator.mousedown(this.eventsArgs.element, this.eventsArgs.options);

            if (this.clickCausesChange)
                this.parentSelect.selectedIndex = this.childIndex;

            return this._focus();
        }

        if (browserUtils.isIE) {
            eventSimulator.mousedown(this.eventsArgs.element, this.eventsArgs.options);

            return this._focus();
        }

        // NOTE: In Chrome, document.activeElement is 'select' after mousedown. But we need to
        // raise blur and change the event for a previously active element during focus raising.
        // That's why we should change the event order and raise focus before mousedown.
        return this
            ._focus()
            .then(() => delay(FOCUS_DELAY))
            .then(() => {
                eventSimulator.mousedown(this.eventsArgs.element, this.eventsArgs.options);

                if (this.clickCausesChange)
                    this.parentSelect.selectedIndex = this.childIndex;
            });
    }

    _focus () {
        return new Promise(resolve => {
            focusBlurSandbox.focus(this.parentSelect, resolve, false, true);
        });
    }

    _mouseup () {
        var elementForMouseupEvent = browserUtils.isIE ? this.parentSelect : this.eventsArgs.element;

        eventSimulator.mouseup(elementForMouseupEvent, this.eventsArgs.options);

        if (browserUtils.isIE && this.clickCausesChange)
            this.parentSelect.selectedIndex = this.childIndex;

        var simulateInputEventOnValueChange = browserUtils.isFirefox || browserUtils.isSafari ||
                                               browserUtils.isChrome && browserUtils.version >= 53;

        var simulateChangeEventOnValueChange = simulateInputEventOnValueChange || browserUtils.isIE;

        if (simulateInputEventOnValueChange && this.clickCausesChange)
            eventSimulator.input(this.parentSelect);

        if (simulateChangeEventOnValueChange && this.clickCausesChange)
            eventSimulator.change(this.parentSelect);

        return Promise.resolve();
    }

    _click () {
        eventSimulator.click(this.eventsArgs.element, this.eventsArgs.options);
    }

    run () {
        if (!this.parentSelect) {
            eventSimulator.click(this.eventsArgs.element, this.eventsArgs.options);

            return Promise.resolve();
        }

        if (!this.optionListExpanded)
            selectElementUI.scrollOptionListByChild(this.element);

        var moveArguments = this._getMoveArguments();

        this.eventsArgs = this._calculateEventArguments();

        if (styleUtils.getSelectElementSize(this.parentSelect) <= 1) {
            return this
                ._move(moveArguments)
                .then(() => this._click());
        }

        return this
            ._move(moveArguments)
            .then(() => this._mousedown())
            .then(() => this._mouseup())
            .then(() => this._click());
    }
}


text:
package org.cidrz.webapp.dynasite.utils;

import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;

/**
 * @author Chris Kelley
 *         Date: Sep 8, 2005
 *         Time: 4:18:44 PM
 * http://javatechniques.com/public/java/docs/basics/faster-deep-copy.html
 */
public class DeepCopy {
    /**
     * Returns a copy of the object, or null if the object cannot
     * be serialized.
     */
    public static Object copy(Object orig) {
        Object obj = null;
        try {
            // Write the object out to a byte array
            FastByteArrayOutputStream fbos =
                    new FastByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(fbos);
            out.writeObject(orig);
            out.flush();
            out.close();

            // Retrieve an input stream from the byte array and read
            // a copy of the object back in.
            ObjectInputStream in =
                new ObjectInputStream(fbos.getInputStream());
            obj = in.readObject();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        catch(ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
        }
        return obj;
    }
}


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

#pragma once

#include "AIController.h"
#include "TankAiController.generated.h"

/**
 *  Tanp Cpp AI Controller
 */
UCLASS()
class ZZBATTLETANK_API ATankAiController : public AAIController
{
	GENERATED_BODY()

private:

	void BeginPlay() override;

	virtual void Tick(float DeltaTime);

	float AcceptanceRadius = 3000;

};


text:
package voyager.nove.model.utente.competenze;

/**
 * @name Login
 *
 * @project Voyager
 *
 * @package voyager.nove.model.utente.competenze
 *
 * @author Giacomo Marciani, Jesus Cevallos, Ilyas Aboki, Ludovic William
 *
 */
public class Login extends AbstractCompetenza {

	private static final long serialVersionUID = 1L;

	private static Login singletonLogin;

	private static int ID = Competenza.LOGIN;
	private static String STRING = "Logout";

	protected Login(int id, String string) {
		super(id, string);
	}

	public static synchronized Login getInstance() {
		if (singletonLogin == null) {
			singletonLogin = new Login(ID, STRING);
			return singletonLogin;
		}

		return singletonLogin;
	}

}


text:
<dom-module id="cs-music-library-action">
	<link rel="import" type="css" href="style.css">
	<template vertical center layout>
		<cs-music-menu-items>
			<cs-music-menu-item on-tap="create_playlist">[[L.create-playlist]]</cs-music-menu-item>
			<cs-music-menu-item on-tap="add_to_playlist">[[L.add-to-playlist]]</cs-music-menu-item>
		</cs-music-menu-items>
		<cs-controls horizontal center layout>
			<cs-control flex icon="chevron-left" on-tap="back"></cs-control>
		</cs-controls>
	</template>
	<script src="script.js"></script>
</dom-module>


text:
rem @echo off
set SELF=%~dp0
if "%1" equ "" (
    echo Usage: build_double.bat {node_version}
    echo e.g. build_double.bat 5.9.1
    exit /b -1
)

mkdir "%SELF%\build\nuget\content\edge" > nul 2>&1
mkdir "%SELF%\build\nuget\lib\net40" > nul 2>&1
mkdir "%SELF%\build\nuget\lib\netstandard1.6" > nul 2>&1
mkdir "%SELF%\build\nuget\tools" > nul 2>&1
mkdir "%SELF%\..\src\double\Edge.js\bin\Release\net40" > nul 2>&1

if not exist "%SELF%\build\download.exe" (
	csc /out:"%SELF%\build\download.exe" "%SELF%\download.cs"
)

if not exist "%SELF%\build\unzip.exe" (
 	csc /out:"%SELF%\build\unzip.exe" /r:System.IO.Compression.FileSystem.dll "%SELF%\unzip.cs"
)

if not exist "%SELF%\build\repl.exe" (
	csc /out:"%SELF%\build\repl.exe" "%SELF%\repl.cs"
)

if not exist "%SELF%\build\nuget.exe" (
	"%SELF%\build\download.exe" http://nuget.org/nuget.exe "%SELF%\build\nuget.exe"
)

if not exist "%SELF%\build\%1.zip" (
	"%SELF%\build\download.exe" https://github.com/nodejs/node/archive/v%1.zip "%SELF%\build\%1.zip"
)

if not exist "%SELF%\build\node-%1" (
	rem "%SELF%\build\unzip.exe" "%SELF%\build\%1.zip" "%SELF%\build"
	pushd "%SELF%\build\"
	cscript //B ..\unzip.vbs %1.zip
	popd
)

call :build_node %1 x86
if %ERRORLEVEL% neq 0 exit /b -1
call :build_node %1 x64
if %ERRORLEVEL% neq 0 exit /b -1

if not exist "%SELF%\build\node-%1-x86\node.exe" (
	"%SELF%\build\download.exe" http://nodejs.org/dist/v%1/win-x86/node.exe "%SELF%\build\node-%1-x86\node.exe"
)

if not exist "%SELF%\build\node-%1-x64\node.exe" (
	"%SELF%\build\download.exe" http://nodejs.org/dist/v%1/win-x64/node.exe "%SELF%\build\node-%1-x64\node.exe"
)

call :build_edge %1 x86 ia32
if %ERRORLEVEL% neq 0 exit /b -1
call :build_edge %1 x64 x64
if %ERRORLEVEL% neq 0 exit /b -1

csc /out:"%SELF%\..\src\double\Edge.js\bin\Release\net40\EdgeJs.dll" /target:library "%SELF%\..\src\double\Edge.js\dotnet\EdgeJs.cs"
if %ERRORLEVEL% neq 0 exit /b -1

cd "%SELF%\..\src\double\Edge.js"
dotnet restore
if %ERRORLEVEL% neq 0 exit /b -1
dotnet build --configuration Release

rem if %ERRORLEVEL% neq 0 exit /b -1
rem dotnet build --configuration Release --framework netstandard1.6
rem if %ERRORLEVEL% neq 0 exit /b -1
rem dotnet build --configuration Release --framework netstandard2.0
rem if %ERRORLEVEL% neq 0 exit /b -1
rem dotnet build --configuration Release --framework net40
rem if %ERRORLEVEL% neq 0 exit /b -1
rem dotnet build --configuration Release --framework net45

if %ERRORLEVEL% neq 0 exit /b -1
dotnet pack --configuration Release --no-build

if %ERRORLEVEL% neq 0 (
	echo Failure building Nuget package
	cd "%SELF%"
	exit /b -1
)

cd "%SELF%"
copy /y "%SELF%\..\src\double\Edge.js\bin\Release\*.nupkg" "%SELF%\build\nuget"
echo SUCCESS. Nuget package at %SELF%\build\nuget

exit /b 0

:build_edge

rem takes 2 parameters: 1 - node version, 2 - x86 or x64

if exist "%SELF%\build\nuget\content\edge\%2\edge_nativeclr.node" exit /b 0

set NODEEXE=%SELF%\build\node-%1-%2\node.exe
set GYP=%APPDATA%\npm\node_modules\node-gyp\bin\node-gyp.js

pushd "%SELF%\.."

"%NODEEXE%" "%GYP%" configure --msvs_version=2019
"%SELF%\build\repl.exe" ./build/edge_nativeclr.vcxproj "%USERPROFILE%\.node-gyp\%1\%3\node.lib" "%SELF%build\node-%1-%2\node.lib"
"%NODEEXE%" "%GYP%" build
mkdir "%SELF%\build\nuget\content\edge\%2" > nul 2>&1
copy /y build\release\edge_nativeclr.node "%SELF%\build\nuget\content\edge\%2"
copy /y "%SELF%\build\node-%1-%2\node.dll" "%SELF%\build\nuget\content\edge\%2"

popd

exit /b 0

:build_node

rem takes 2 parameters: 1 - node version, 2 - x86 or x64

if exist "%SELF%\build\node-%1-%2\node.lib" exit /b 0

pushd "%SELF%\build\node-%1"
rmdir /s /q Release
rmdir /s /q build
rmdir /s /q tools\icu\Release

..\repl.exe node.gyp "'executable'" "'shared_library'"
if %ERRORLEVEL% neq 0 (
    echo Cannot update node.gyp
    popd
    exit /b -1
)

call vcbuild.bat release %2
if not exist .\Release\node.dll (
    echo Cannot build node.dll for %1-%2
    popd
    exit /b -1
)

mkdir "%SELF%\build\node-%1-%2"
copy /y .\Release\node.* "%SELF%\build\node-%1-%2"
echo Finished building Node shared library %1

popd
exit /b 0


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

if (!window.sendPost) {
    window.sendPost = function(url, obj){
        var myForm = document.createElement("form");
        myForm.action = url;
        myForm.method = "post";
        for(var key in obj) {
            var input = document.createElement("input");
            input.type = "text";
            input.value = obj[key];
            input.name = key;
            myForm.appendChild(input);
        }
        document.body.appendChild(myForm);
        myForm.submit();
    };
}

function fazerLogin() {
    sendPost(top.basePath + '/login/logar',{
        login: document.getElementById('login').value,
        senha: top.senha
    });
}

$(function(){
    $('#home').removeClass('active');
    $('#diarios').removeClass('active');
    $('#rotas').removeClass('active');
    $('#anuncie').removeClass('active');
    $('#cadastrese').addClass('active');
    $('#contato').removeClass('active');
    $('#areaRestrita').removeClass('active');
});


text:
class CreatePastes < ActiveRecord::Migration
  def change
    create_table :pastes do |t|
      t.integer :placement_id
      t.integer :snippet_id
      t.text    :options
      t.string  :mercury_id

      t.timestamps
    end

    add_index :pastes, :placement_id
    add_index :pastes, :snippet_id
    add_index :pastes, :mercury_id
  end
end


text:
<?php

namespace app\controllers;

use app\models\Movie;
use Yii;
use yii\data\Pagination;

class MoviesController extends \app\controllers\AppController
{
    public function actionIndex()
    {
        $query = Movie::find()->select('id, title, post_date')->orderBy('post_date DESC');
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $data = $query->offset($pages->offset)
            ->limit($pages->limit)
            ->all();
        return $this->render('index', [
            'data' => $data,
            'pages' => $pages,
        ]);
    }

    public function actionView($id)
    {
        $movies = Movie::find()->where('id = :id', [':id' => $id])->one();
        if (!$movies) {
            $this->redirect('/movies');
        }
        return $this->render('view', ['movies' => $movies]);
    }
}


text:
// FieldArray
// Author: Matthew Raso-Barnett  29/09/2010

#ifndef FIELDARRAY_H
#define FIELDARRAY_H

#include "TNamed.h"
#include <string>
#include <map>
#include <iostream>
#include "TVector3.h"

#include "Field.h"
#include "Observable.h"

////////////////////////////////////////////////////////////////////////////
//                                                                        //
//    FieldArray                                                      //
//                                                                        //
////////////////////////////////////////////////////////////////////////////
using std::string;
using std::map;

class Point;

class FieldArray : public TNamed, public Observable
{
protected:
   typedef map<string, Field*> FieldContainer;
   FieldContainer fFieldList;

   // Don't allow copy construction - otherwise we run into problems with ownership of pointers
   FieldArray(const FieldArray&);

private:
   void PurgeFields();

public:
   // -- constructors
   FieldArray();
   FieldArray(const std::string name);
   // -- destructor
   virtual ~FieldArray();

   // -- methods
   void AddField(Field* field);
   const TVector3 GetField(const Point& point, const string = "") const;
   virtual const TVector3 GetMagField(const Point& point, const TVector3& velocity, const std::string = "") const = 0;

   ClassDef(FieldArray, 1)
};

#endif /* FIELDARRAY_H */


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__) + '..', '..', 'lib'))
require 'lib/ramazon_advertising'

require 'spec/expectations'

configatron.ramazon.configure_from_yaml(File.join(File.dirname(__FILE__), "ramazon_advertising.yml"))


text:
module Seiten
  class Engine < ::Rails::Engine
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

<title>Compiling and Running</title>

Environment, Configuring, Compiling and Running

This page of the tutorial explains how to build the BBFS filesystem
program and use it to mount a directory.

Environment

This tutorial describes the use of FUSE version 2.9.x (API level 26).
Development of FUSE itself has gone beyond this level (the most recent
release is 3.2.1); unfortunately, the developers broke backward
compatibility with version 3.  I'm now looking into what changes I need
to make to bring this tutorial in line with the latest versions.  In
the mean time, if you want to use the code from this tutorial I
strongly recommend you install an older version.

In order to compile against the FUSE libraries, you need to make sure
you have installed the development version of the libraries.  In
Debian and Ubuntu the package name is "libfuse-dev"; in Fedora it's
"fuse-devel".  Note in both cases that the distributions are only
using fuse version 2.9.7, so if you install using the package managers
you'll automatically be using a version that is compatible with this
tutorial.

Configuring and Compiling

This tutorial uses the GNU autotools system for configuration.  As
is the case with all autotools-based projects, you can configure and
compile it by going to the top-level directory and typing

./configure
make

and the code should be compiled and ready to go.

Unlike most software, the code from this tutorial is not intended to
be installed.  Consequently, I've tried to disable all the various
installation targets; if I've missed one please let me know.

Mounting a BBFS Filesystem

You mount a BBFS filesystem by running the command bbfs
(in general, a FUSE filesystem is implemented by a program, and you
mount it by running that program).
bbfs has two required arguments:  the root directory (which
contains the actual directory data) and the mount directory.  The
tutorial tarball includes an example directory, which
contains two subdirectories named rootdir and
mountdir.  You can verify that rootdir
contains a single file named bogus.txt, while
mountdir is empty

Here's what it looks like when you try it:

snowball:655$ pwd
/home/joseph/fuse-tutorial/example
snowball:656$ ls -lR
.:
total 12
-rw-r--r-- 1 joseph users  185 Jun  9 15:56 Makefile
drwxr-xr-x 2 joseph users 4096 Jun 12 17:16 mountdir/
drwxr-xr-x 2 joseph users 4096 Jun 12 17:16 rootdir/

./mountdir:
total 0

./rootdir:
total 4
-rw-r--r-- 1 joseph users 11 Jun 12 17:16 bogus.txt

Now, if you go into the example directory and execute

../src/bbfs rootdir mountdir

all of the files that are really in rootdir appear to also
be in mountdir"

snowball:657$ ../src/bbfs rootdir/ mountdir/
about to call fuse_main
snowball:658$ ls -lR
.:
total 40
-rw-r--r-- 1 joseph users   185 Jun  9 15:56 Makefile
-rw-r--r-- 1 joseph users 25632 Jun 12 17:51 bbfs.log
drwxr-xr-x 2 joseph users  4096 Jun 12 17:16 mountdir/
drwxr-xr-x 2 joseph users  4096 Jun 12 17:16 rootdir/

./mountdir:
total 4
-rw-r--r-- 1 joseph users 11 Jun 12 17:16 bogus.txt

./rootdir:
total 4
-rw-r--r-- 1 joseph users 11 Jun 12 17:16 bogus.txt

But, every time you perform any file
operation in mountdir, the operation (and a whole bunch
of both relevant and irrelevant stuff) gets logged to a new file in the
current working directory called bbfs.log  If you execute

tail -F bbfslog

in another terminal window, you can watch the operations get
logged.

Finally, you can see that the operating system sees
mountdir as a filesystem:

snowball:660$ mount | grep mountdir
bbfs on /home/joseph/fuse-tutorial/example/mountdir type fuse.bbfs (rw,nosuid,nodev,relatime,user_id=1248,group_id=1005)

Unmounting

Finally, you can unmount the filesystem with

snowball:661$ fusermount -u mountdir
snowball:662$ ls -lR
.:
total 40
-rw-r--r-- 1 joseph users   185 Jun  9 15:56 Makefile
-rw-r--r-- 1 joseph users 27520 Jun 12 17:57 bbfs.log
drwxr-xr-x 2 joseph users  4096 Jun 12 17:16 mountdir/
drwxr-xr-x 2 joseph users  4096 Jun 12 17:16 rootdir/

./mountdir:
total 0

./rootdir:
total 4
-rw-r--r-- 1 joseph users 11 Jun 12 17:16 bogus.txt

(note that fusermount isn't part of this tutorial
— it comes along with FUSE).

pkg-config

One thing to mention about configuring the software is the line

PKG_CHECK_MODULES(FUSE, fuse)

in configure.ac

This translates to two invocations of pkg-config to
obtain the C compilation flags and libraries needed to compile and
link the code in the tutorial.

`pkg-config fuse --cflags`

says to use pkg-config to determine what C
compiler flags are necessary to compile a source file that makes use
of FUSE.  The back-quotes around the command are important —
they take the output of the command and insert it into the
command-line as command-line operations (note  — it's important
those are back-quotes aka accent graves.  They can't be forward quotes,
nor double quotes).  The other place it's used,

`pkg-config fuse --libs`

gives the extra command-line arguments to link the program with
libfuse.

An earlier version of this tutorial used these invocations directly in
the Makefile, like this:

bbfs : bbfs.o log.o
        gcc -g -o bbfs bbfs.o log.o `pkg-config fuse --libs`

bbfs.o : bbfs.c log.h params.h
        gcc -g -Wall `pkg-config fuse --cflags` -c bbfs.c

log.o : log.c log.h params.h
        gcc -g -Wall `pkg-config fuse --cflags` -c log.c

Next:  Callbacks and
struct fuse_operations

<address></address>
Last modified: Sun Feb  4 09:16:09 MST 2018


text:
#include "volume_id_internal.h"

/* All these values are taken from ocfs2-tools's ocfs2_fs.h */
#define OCFS2_VOL_UUID_LEN			16
#define OCFS2_MAX_VOL_LABEL_LEN			64
#define OCFS2_SUPERBLOCK_OFFSET			0x2000

/* This is the superblock. The OCFS2 header files have structs in structs.
This is one has been simplified since we only care about the superblock.
*/

struct ocfs2_super_block {
	uint8_t		i_signature[8];			/* Signature for validation */
	uint32_t	i_generation;			/* Generation number */
	int16_t		i_suballoc_slot;			/* Slot suballocator this inode belongs to */
	uint16_t	i_suballoc_bit;			/* Bit offset in suballocator block group */
	uint32_t	i_reserved0;
	uint32_t	i_clusters;			/* Cluster count */
	uint32_t	i_uid;				/* Owner UID */
	uint32_t	i_gid;				/* Owning GID */
	uint64_t	i_size;				/* Size in bytes */
	uint16_t	i_mode;				/* File mode */
	uint16_t	i_links_count;			/* Links count */
	uint32_t	i_flags;				/* File flags */
	uint64_t	i_atime;				/* Access time */
	uint64_t	i_ctime;				/* Creation time */
	uint64_t	i_mtime;				/* Modification time */
	uint64_t	i_dtime;				/* Deletion time */
	uint64_t	i_blkno;				/* Offset on disk, in blocks */
	uint64_t	i_last_eb_blk;			/* Pointer to last extent block */
	uint32_t	i_fs_generation;			/* Generation per fs-instance */
	uint32_t	i_atime_nsec;
	uint32_t	i_ctime_nsec;
	uint32_t	i_mtime_nsec;
	uint64_t	i_reserved1[9];
	uint64_t	i_pad1;				/* Generic way to refer to this 64bit union */
	/* Normally there is a union of the different block types, but we only care about the superblock. */
	uint16_t	s_major_rev_level;
	uint16_t	s_minor_rev_level;
	uint16_t	s_mnt_count;
	int16_t		s_max_mnt_count;
	uint16_t	s_state;				/* File system state */
	uint16_t	s_errors;				/* Behaviour when detecting errors */
	uint32_t	s_checkinterval;			/* Max time between checks */
	uint64_t	s_lastcheck;			/* Time of last check */
	uint32_t	s_creator_os;			/* OS */
	uint32_t	s_feature_compat;			/* Compatible feature set */
	uint32_t	s_feature_incompat;		/* Incompatible feature set */
	uint32_t	s_feature_ro_compat;		/* Readonly-compatible feature set */
	uint64_t	s_root_blkno;			/* Offset, in blocks, of root directory dinode */
	uint64_t	s_system_dir_blkno;		/* Offset, in blocks, of system directory dinode */
	uint32_t	s_blocksize_bits;			/* Blocksize for this fs */
	uint32_t	s_clustersize_bits;		/* Clustersize for this fs */
	uint16_t	s_max_slots;			/* Max number of simultaneous mounts before tunefs required */
	uint16_t	s_reserved1;
	uint32_t	s_reserved2;
	uint64_t	s_first_cluster_group;		/* Block offset of 1st cluster group header */
	uint8_t		s_label[OCFS2_MAX_VOL_LABEL_LEN];	/* Label for mounting, etc. */
	uint8_t		s_uuid[OCFS2_VOL_UUID_LEN];	/* 128-bit uuid */
} PACKED;

int FAST_FUNC volume_id_probe_ocfs2(struct volume_id *id /*,uint64_t off*/)
{
#define off ((uint64_t)0)
	struct ocfs2_super_block *os;

	dbg("probing at offset 0x%llx", (unsigned long long) off);

	os = volume_id_get_buffer(id, off + OCFS2_SUPERBLOCK_OFFSET, 0x200);
	if (os == NULL)
		return -1;

	if (memcmp(os->i_signature, "OCFSV2", 6) != 0) {
		return -1;
	}

//	volume_id_set_usage(id, VOLUME_ID_FILESYSTEM);
//	volume_id_set_label_raw(id, os->s_label, OCFS2_MAX_VOL_LABEL_LEN < VOLUME_ID_LABEL_SIZE ?
//					OCFS2_MAX_VOL_LABEL_LEN : VOLUME_ID_LABEL_SIZE);
	volume_id_set_label_string(id, os->s_label, OCFS2_MAX_VOL_LABEL_LEN < VOLUME_ID_LABEL_SIZE ?
					OCFS2_MAX_VOL_LABEL_LEN : VOLUME_ID_LABEL_SIZE);
	volume_id_set_uuid(id, os->s_uuid, UUID_DCE);
	IF_FEATURE_BLKID_TYPE(id->type = "ocfs2";)
	return 0;
}


text:
> [UI.Next Documentation](UINext.md) ▸ **Leaks**

The [Dataflow](UINext-Dataflow.md) layer avoids most common cases of space leaks,
as well as time leaks, by using a clever coordination protocol.

The protocol is GC-friendly, which is great news for the programmer.
You can generally create consumers without having to "unsubscribe" or otherwise
imperatively mark their irrelevance.  So, for instance:

    let y = View.Map f x

This creates `y` as a consumer (dependent) of `x`.  If your program drops `y`,
it gets collected without any effect on `x`.

The protocol makes one important assumption:

**VARIABLES KEEP CHANGING**

If your program creates [Var](UINext-Var.md) cells, it should either:

* keep updating them

* drop them so they get collected

* explicitly mark them as finalized by `Var.SetFinal` - very rarely needed

If your program violates these rules, and dynamically continues creating new views on
violating variables, and observing these views, you will obtain a memory leak.
This happens when view update processes sit waiting for a `Var` to change,
preventing GC from collecting them.

In practice, it is fairly difficult to accidentally construct a leaking program.

We might improve the protocol and GC properties in the future by employing advanced
implementation techniques with weak pointers.


text:
using Microsoft.Azure.Management.KeyVault;
using System;
using System.Collections;
using System.Management.Automation;
using PSKeyVaultModels = Microsoft.Azure.Commands.KeyVault.Models;
using PSKeyVaultProperties = Microsoft.Azure.Commands.KeyVault.Properties;

namespace Microsoft.Azure.Commands.KeyVault
{
    /// <summary>
    /// Create a new key vault.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "AzureRmKeyVault", HelpUri = Constants.KeyVaultHelpUri)]
    [OutputType(typeof(PSKeyVaultModels.PSVault))]
    public class NewAzureKeyVault : KeyVaultManagementCmdletBase
    {
        #region Input Parameter Definitions

        /// <summary>
        /// Vault name
        /// </summary>
        [Parameter(Mandatory = true,
            Position = 0,
            ValueFromPipelineByPropertyName = true,
            HelpMessage =
                "Specifies a name of the key vault to create. The name can be any combination of letters, digits, or hyphens. The name must start and end with a letter or digit. The name must be universally unique."
            )]
        [ValidatePattern("^[a-zA-Z0-9-]{3,24}$")]
        [ValidateNotNullOrEmpty]
        public string VaultName { get; set; }

        /// <summary>
        /// Resource group name
        /// </summary>
        [Parameter(Mandatory = true,
            Position = 1,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies the name of an existing resource group in which to create the key vault.")]
        [ValidateNotNullOrEmpty()]
        public string ResourceGroupName { get; set; }

        /// <summary>
        /// Location
        /// </summary>
        [Parameter(Mandatory = true,
            Position = 2,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies the Azure region in which to create the key vault. Use the command Get-AzureRmResourceProvider with the ProviderNamespace parameter to see your choices.")]
        [ValidateNotNullOrEmpty()]
        public string Location { get; set; }

        [Parameter(Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "If specified, enables secrets to be retrieved from this key vault by the Microsoft.Compute resource provider when referenced in resource creation.")]
        public SwitchParameter EnabledForDeployment { get; set; }

        [Parameter(Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "If specified, enables secrets to be retrieved from this key vault by Azure Resource Manager when referenced in templates.")]
        public SwitchParameter EnabledForTemplateDeployment { get; set; }

        [Parameter(Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "If specified, enables secrets to be retrieved from this key vault by Azure Disk Encryption.")]
        public SwitchParameter EnabledForDiskEncryption { get; set; }

        [Parameter(Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies the SKU of the key vault instance. For information about which features are available for each SKU, see the Azure Key Vault Pricing website (http://go.microsoft.com/fwlink/?linkid=512521).")]
        [ValidateSet("standard", "premium")]
        public string Sku { get; set; }

        [Alias("Tags")]
        [Parameter(Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "A hash table which represents resource tags.")]
        public Hashtable Tag { get; set; }

        #endregion

        public override void ExecuteCmdlet()
        {
            if (VaultExistsInCurrentSubscription(this.VaultName))
            {
                throw new ArgumentException(PSKeyVaultProperties.Resources.VaultAlreadyExists);
            }

            var userObjectId = Guid.Empty;
            AccessPolicyEntry accessPolicy = null;

            try
            {
                userObjectId = GetCurrentUsersObjectId();
            }
            catch (Exception ex)
            {
                // Show the graph exceptions as a warning, but still proceed to create a vault with no access policy
                // This is to unblock Key Vault in Fairfax as Graph has issues in this environment.
                WriteWarning(ex.Message);
            }
            if (userObjectId != Guid.Empty)
            {
                accessPolicy = new AccessPolicyEntry()
                {
                    TenantId = GetTenantId(),
                    ObjectId = userObjectId,
                    PermissionsToKeys = DefaultPermissionsToKeys,
                    PermissionsToSecrets = DefaultPermissionsToSecrets
                };
            }

            var newVault = KeyVaultManagementClient.CreateNewVault(new PSKeyVaultModels.VaultCreationParameters()
            {
                VaultName = this.VaultName,
                ResourceGroupName = this.ResourceGroupName,
                Location = this.Location,
                EnabledForDeployment = this.EnabledForDeployment.IsPresent,
                EnabledForTemplateDeployment = EnabledForTemplateDeployment.IsPresent,
                EnabledForDiskEncryption = EnabledForDiskEncryption.IsPresent,
                SkuFamilyName = DefaultSkuFamily,
                SkuName = string.IsNullOrWhiteSpace(this.Sku) ? DefaultSkuName : this.Sku,
                TenantId = GetTenantId(),
                AccessPolicy = accessPolicy,
                Tags = this.Tag
            },
            ActiveDirectoryClient
            );

            this.WriteObject(newVault);

            if (accessPolicy == null)
            {
                WriteWarning(PSKeyVaultProperties.Resources.VaultNoAccessPolicyWarning);
            }
        }

    }
}


text:
class AddCorrectAnswersCountToQuestion < ActiveRecord::Migration
  def change
    add_column :questions, :correct_answers_count, :integer, default: 0
  end
end


text:
package org.neo4j.driver.types;

/**
 * The Node interface describes the characteristics of a node from a Neo4j graph.
 * @since 1.0
 */
public interface Node extends Entity {
    /**
     * Return all labels.
     *
     * @return a label Collection
     */
    Iterable<String> labels();

    /**
     * Test if this node has a given label
     *
     * @param label the label
     * @return {@code true} if this node has the label otherwise {@code false}
     */
    boolean hasLabel(String label);
}


text: drutil tray close


text:
cwd=$(pwd)
arch="x64"

# @TODO 0.10.30 must be added to https://github.com/mapbox/node-pre-gyp/blob/master/lib/util/abi_crosswalk.json
# and available in all our node-pre-gyp modules.
node_version="0.10.26"
atom_version="0.15.4"

if [ -z "$1" ]; then
    gitsha="master"
else
    gitsha=$1
fi

if [ -z "$2" ]; then
    platform=$(uname -s | sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/")
else
    platform=$2
fi

if [ "$platform" == "win32" ]; then
    arch="ia32"
fi

set -e -u
set -o pipefail

if ! which git > /dev/null; then echo "git command not found"; exit 1; fi;
if ! which aws > /dev/null; then echo "aws command not found"; exit 1; fi;
if ! which npm > /dev/null; then echo "npm command not found"; exit 1; fi;
if ! which tar > /dev/null; then echo "tar command not found"; exit 1; fi;
if ! which curl > /dev/null; then echo "curl command not found"; exit 1; fi;
if ! which unzip > /dev/null; then echo "unzip command not found"; exit 1; fi;

build_dir="/tmp/mapbox-studio-$platform-$arch-$gitsha"
shell_url="https://github.com/atom/atom-shell/releases/download/v$atom_version/atom-shell-v$atom_version-$platform-$arch.zip"
shell_file="/tmp/atom-shell-v$atom_version-$platform-$arch.zip"

if [ "$platform" == "darwin" ]; then
    app_dir="/tmp/mapbox-studio-$platform-$arch-$gitsha/Atom.app/Contents/Resources/app"
else
    app_dir="/tmp/mapbox-studio-$platform-$arch-$gitsha/resources/app"
fi

echo "Building bundle in $build_dir"

if [ -d $build_dir ]; then
    echo "Build dir $build_dir already exists"
    exit 1
fi

curl -Lsfo $shell_file $shell_url
unzip -qq $shell_file -d $build_dir
rm $shell_file

git clone https://github.com/mapbox/mapbox-studio.git $app_dir
cd $app_dir
git checkout $gitsha
rm -rf $app_dir/.git

# Update LICENSE and version files from atom default.
ver=$(node -e "var fs = require('fs'); console.log(JSON.parse(fs.readFileSync('$app_dir/package.json')).version);")
echo $ver > $build_dir/version
cp $app_dir/LICENSE.md $build_dir/LICENSE

BUILD_PLATFORM=$platform npm install --production

# Remove extra deps dirs to save space
deps="node_modules/mbtiles/node_modules/sqlite3/deps
node_modules/mapnik-omnivore/node_modules/gdal/deps
node_modules/mapnik-omnivore/node_modules/srs/deps"
for depdir in $deps; do
    rm -r $app_dir/$depdir
done

# Go through pre-gyp modules and rebuild for target platform/arch.
modules="node_modules/mapnik
node_modules/mbtiles/node_modules/sqlite3
node_modules/mapnik-omnivore/node_modules/srs
node_modules/mapnik-omnivore/node_modules/gdal"
for module in $modules; do
    rm -r $app_dir/$module/lib/binding
    cd $app_dir/$module
    ./node_modules/.bin/node-pre-gyp install \
        --target_platform=$platform \
        --target=$node_version \
        --target_arch=$arch \
        --fallback-to-build=false
done

cd /tmp

# win32: installer using nsis
if [ $platform == "win32" ]; then
    if ! which makensis > /dev/null; then echo "makensis command not found"; exit 1; fi;
    makensis -V2 $build_dir/resources/app/scripts/mapbox-studio.nsi
    rm -rf $build_dir
    mv /tmp/mapbox-studio.exe $build_dir.exe
    aws s3 cp --acl=public-read $build_dir.exe s3://mapbox/mapbox-studio/
    echo "Build at https://mapbox.s3.amazonaws.com/mapbox-studio/$(basename $build_dir.exe)"
    rm -f $build_dir.exe
# darwin: add app resources, zip up
elif [ $platform == "darwin" ]; then
    # Update Info.plist with correct version number.
    sed -i.bak s/VREPLACE/$ver/ $app_dir/scripts/assets/Info.plist

    rm $build_dir/Atom.app/Contents/Resources/atom.icns
    cp $app_dir/scripts/assets/mapbox-studio.icns $build_dir/Atom.app/Contents/Resources/mapbox-studio.icns
    cp $app_dir/scripts/assets/Info.plist $build_dir/Atom.app/Contents/Info.plist
    mv $build_dir/Atom.app "$build_dir/Mapbox Studio.app"

    # Test getting signing key.
    aws s3 cp "s3://mapbox/mapbox-studio/keys/Developer ID Certification Authority.cer" authority.cer
    aws s3 cp "s3://mapbox/mapbox-studio/keys/Developer ID Application: Mapbox, Inc. (GJZR2MEM28).cer" signing-key.cer
    aws s3 cp "s3://mapbox/mapbox-studio/keys/Mac Developer ID Application: Mapbox, Inc..p12" signing-key.p12
    security create-keychain -p travis signing.keychain \
        && echo "+ signing keychain created"
    security import authority.cer -k ~/Library/Keychains/signing.keychain -T /usr/bin/codesign \
        && echo "+ authority cer added to keychain"
    security import signing-key.cer -k ~/Library/Keychains/signing.keychain -T /usr/bin/codesign \
        && echo "+ signing cer added to keychain"
    security import signing-key.p12 -k ~/Library/Keychains/signing.keychain -P "" -T /usr/bin/codesign \
        && echo "+ signing key added to keychain"
    rm authority.cer
    rm signing-key.cer
    rm signing-key.p12

    # Sign .app file.
    codesign --keychain ~/Library/Keychains/signing.keychain --sign "Developer ID Application: Mapbox, Inc." --deep --verbose --force "$build_dir/Mapbox Studio.app"

    # Nuke signin keychain.
    security delete-keychain signing.keychain

    # Use ditto rather than zip to preserve code signing.
    ditto -c -k --sequesterRsrc --keepParent --zlibCompressionLevel 9 $(basename $build_dir) $build_dir.zip

    rm -rf $build_dir
    aws s3 cp --acl=public-read $build_dir.zip s3://mapbox/mapbox-studio/
    echo "Build at https://mapbox.s3.amazonaws.com/mapbox-studio/$(basename $build_dir.zip)"
    rm -f $build_dir.zip
# linux: zip up
else
    zip -qr $build_dir.zip $(basename $build_dir)
    rm -rf $build_dir
    aws s3 cp --acl=public-read $build_dir.zip s3://mapbox/mapbox-studio/
    echo "Build at https://mapbox.s3.amazonaws.com/mapbox-studio/$(basename $build_dir.zip)"
    rm -f $build_dir.zip
fi

cd $cwd


text:
class MyApp < Sinatra::Base
  get '/skeletons' do
    # view that displays data, see: views/skeletons.haml
    # (skeleton in skeletons/skeleton.rb)
    @skeletons = Skeleton.all
    haml :"skeletons/skeletons"
  end

  # Database Interaction CRUD

  # "CREATE", part of the C in CRUD
  get '/new_skeleton_form' do
    env['warden'].authenticate!
    # view containing the form elements, see: views/form.haml)
    haml :"skeletons/new_skeleton_form"
  end

  post '/submit' do
    env['warden'].authenticate!
    # post route that handles the given form data and saves it to the database
    @skeleton = Skeleton.new(params[:skeleton])
    @skeleton.valid?
    if @skeleton.save
      flash[:success] = 'Skeleton successfully saved!'
      redirect '/skeletons'
    else
      @errors = @skeleton.errors
      haml :"skeletons/new_skeleton_form"
    end
  end

  # "EDIT", part of the U in CRUD
  get '/skeletons/:id/edit' do
    env['warden'].authenticate!
    @skeleton = Skeleton.find(params[:id])
    haml :"skeletons/edit_skeleton_form"
  end

  # "UPDATE", part of the U in CRUD
  post '/skeletons/:id' do
    env['warden'].authenticate!
    @skeleton = Skeleton.find(params[:id])
    if @skeleton.update_attributes(params[:skeleton])
      redirect to('/skeletons')
    else
      @errors = @skeleton.errors
      haml :"skeletons/edit_skeleton_form"
    end
  end

  # "DESTROY", the D in CRUD
  post '/skeletons/:id/destroy' do
    env['warden'].authenticate!
    @skeleton = Skeleton.find(params[:id])
    @skeleton.destroy
    flash[:success] = 'Skeleton successfully destroyed'
    redirect to('/skeletons')
  end
end


text:
<link rel="import" href="../forge-shared/polymer.html">

<dom-module id="forge-image-preview">

  <template>

    <style>
      :host {
        display: block;
        padding: 0 2px;
      }
    </style>

    <paper-input value="{{value}}" label="[[label]]" on-input="onInput" on-change="onChange"></paper-input>
    <template is="dom-if" if="[[show]]">
      <iron-image src="{{value}}" fade="true" style="width:100%; height:400px;" sizing="contain" position="top left" on-loaded-changed="_onLoadedChanged"></iron-image>
    </template>

  </template>

  <script>
    Polymer({
      is: 'forge-image-preview',
      behaviors: [ForgeWebComponents.Behaviors.ExtendedFieldStringBehavior],
      properties: {
        show: {
          type: Boolean,
          value: true,
          readOnly: true
        }
      },
      _onLoadedChanged: function (e) {
        this._setShow(e.detail.value);
      },
      onInput: function () {
        this.debounce('triggerOnValueChanged', this.triggerOnValueChanged, 2000);
      },
      onChange: function () {
        this.debounce('triggerOnValueChanged', this.triggerOnValueChanged, 0);
      }
    });
  </script>

</dom-module>


text:
<?php

namespace Nette\Forms;

use Nette,
	Nette\Web\Html;

/**
 * Converts a Form into the HTML output.
 *
 * @copyright  Copyright (c) 2004, 2010 David Grudl
 * @package    Nette\Forms
 */
class ConventionalRenderer extends Nette\Object implements IFormRenderer
{
	/**
	 *  /--- form.container
	 *
	 *    /--- if (form.errors) error.container
	 *      .... error.item [.class]
	 *    \---
	 *
	 *    /--- hidden.container
	 *      .... HIDDEN CONTROLS
	 *    \---
	 *
	 *    /--- group.container
	 *      .... group.label
	 *      .... group.description
	 *
	 *      /--- controls.container
	 *
	 *        /--- pair.container [.required .optional .odd]
	 *
	 *          /--- label.container
	 *            .... LABEL
	 *            .... label.suffix
	 *            .... label.requiredsuffix
	 *          \---
	 *
	 *          /--- control.container [.odd]
	 *            .... CONTROL [.required .text .password .file .submit .button]
	 *            .... control.requiredsuffix
	 *            .... control.description
	 *            .... if (control.errors) error.container
	 *          \---
	 *        \---
	 *      \---
	 *    \---
	 *  \--
	 *
	 * @var array of HTML tags */
	public $wrappers = array(
		'form' => array(
			'container' => NULL,
			'errors' => TRUE,
		),

		'error' => array(
			'container' => 'ul class=error',
			'item' => 'li',
		),

		'group' => array(
			'container' => 'fieldset',
			'label' => 'legend',
			'description' => 'p',
		),

		'controls' => array(
			'container' => 'table',
		),

		'pair' => array(
			'container' => 'tr',
			'.required' => 'required',
			'.optional' => NULL,
			'.odd' => NULL,
		),

		'control' => array(
			'container' => 'td',
			'.odd' => NULL,

			'errors' => FALSE,
			'description' => 'small',
			'requiredsuffix' => '',

			'.required' => 'required',
			'.text' => 'text',
			'.password' => 'text',
			'.file' => 'text',
			'.submit' => 'button',
			'.image' => 'imagebutton',
			'.button' => 'button',
		),

		'label' => array(
			'container' => 'th',
			'suffix' => NULL,
			'requiredsuffix' => '',
		),

		'hidden' => array(
			'container' => 'div',
		),
	);

	/** @var Form */
	protected $form;

	/** @var object */
	protected $clientScript = TRUE; // means autodetect

	/** @var int */
	protected $counter;

	/**
	 * Provides complete form rendering.
	 * @param  Form
	 * @param  string
	 * @return string
	 */
	public function render(Form $form, $mode = NULL)
	{
		if ($this->form !== $form) {
			$this->form = $form;
			$this->init();
		}

		$s = '';
		if (!$mode || $mode === 'begin') {
			$s .= $this->renderBegin();
		}
		if ((!$mode && $this->getValue('form errors')) || $mode === 'errors') {
			$s .= $this->renderErrors();
		}
		if (!$mode || $mode === 'body') {
			$s .= $this->renderBody();
		}
		if (!$mode || $mode === 'end') {
			$s .= $this->renderEnd();
		}
		return $s;
	}

	/**
	 * Sets JavaScript handler.
	 * @param  object
	 * @return ConventionalRenderer  provides a fluent interface
	 */
	public function setClientScript($clientScript = NULL)
	{
		$this->clientScript = $clientScript;
		return $this;
	}

	/**
	 * Returns JavaScript handler.
	 * @return mixed
	 */
	public function getClientScript()
	{
		if ($this->clientScript === TRUE) {
			$this->clientScript = new InstantClientScript($this->form);
		}
		return $this->clientScript;
	}

	/**
	 * Initializes form.
	 * @return void
	 */
	protected function init()
	{
		$clientScript = $this->getClientScript();
		if ($clientScript !== NULL) {
			$clientScript->enable();
		}

		// TODO: only for back compatiblity - remove?
		$wrapper = & $this->wrappers['control'];
		foreach ($this->form->getControls() as $control) {
			if ($control->getOption('required') && isset($wrapper['.required'])) {
				$control->getLabelPrototype()->class($wrapper['.required'], TRUE);
			}

			$el = $control->getControlPrototype();
			if ($el->getName() === 'input' && isset($wrapper['.' . $el->type])) {
				$el->class($wrapper['.' . $el->type], TRUE);
			}
		}
	}

	/**
	 * Renders form begin.
	 * @return string
	 */
	public function renderBegin()
	{
		$this->counter = 0;

		foreach ($this->form->getControls() as $control) {
			$control->setOption('rendered', FALSE);
		}

		if (strcasecmp($this->form->getMethod(), 'get') === 0) {
			$el = clone $this->form->getElementPrototype();
			$uri = explode('?', (string) $el->action, 2);
			$el->action = $uri[0];
			$s = '';
			if (isset($uri[1])) {
				foreach (preg_split('#[;&]#', $uri[1]) as $param) {
					$parts = explode('=', $param, 2);
					$name = urldecode($parts[0]);
					if (!isset($this->form[$name])) {
						$s .= Html::el('input', array('type' => 'hidden', 'name' => $name, 'value' => urldecode($parts[1])));
					}
				}
				$s = "\n\t" . $this->getWrapper('hidden container')->setHtml($s);
			}
			return $el->startTag() . $s;

		} else {
			return $this->form->getElementPrototype()->startTag();
		}
	}

	/**
	 * Renders form end.
	 * @return string
	 */
	public function renderEnd()
	{
		$s = '';
		foreach ($this->form->getControls() as $control) {
			if ($control instanceof HiddenField && !$control->getOption('rendered')) {
				$s .= (string) $control->getControl();
			}
		}
		if ($s) {
			$s = $this->getWrapper('hidden container')->setHtml($s) . "\n";
		}

		$s .= $this->form->getElementPrototype()->endTag() . "\n";

		$clientScript = $this->getClientScript();
		if ($clientScript !== NULL) {
			$s .= $clientScript->renderClientScript() . "\n";
		}

		return $s;
	}

	/**
	 * Renders validation errors (per form or per control).
	 * @param  IFormControl
	 * @return string
	 */
	public function renderErrors(IFormControl $control = NULL)
	{
		$errors = $control === NULL ? $this->form->getErrors() : $control->getErrors();
		if (count($errors)) {
			$ul = $this->getWrapper('error container');
			$li = $this->getWrapper('error item');

			foreach ($errors as $error) {
				$item = clone $li;
				if ($error instanceof Html) {
					$item->add($error);
				} else {
					$item->setText($error);
				}
				$ul->add($item);
			}
			return "\n" . $ul->render(0);
		}
	}

	/**
	 * Renders form body.
	 * @return string
	 */
	public function renderBody()
	{
		$s = $remains = '';

		$defaultContainer = $this->getWrapper('group container');
		$translator = $this->form->getTranslator();

		foreach ($this->form->getGroups() as $group) {
			if (!$group->getControls() || !$group->getOption('visual')) continue;

			$container = $group->getOption('container', $defaultContainer);
			$container = $container instanceof Html ? clone $container : Html::el($container);

			$s .= "\n" . $container->startTag();

			$text = $group->getOption('label');
			if ($text instanceof Html) {
				$s .= $text;

			} elseif (is_string($text)) {
				if ($translator !== NULL) {
					$text = $translator->translate($text);
				}
				$s .= "\n" . $this->getWrapper('group label')->setText($text) . "\n";
			}

			$text = $group->getOption('description');
			if ($text instanceof Html) {
				$s .= $text;

			} elseif (is_string($text)) {
				if ($translator !== NULL) {
					$text = $translator->translate($text);
				}
				$s .= $this->getWrapper('group description')->setText($text) . "\n";
			}

			$s .= $this->renderControls($group);

			$remains = $container->endTag() . "\n" . $remains;
			if (!$group->getOption('embedNext')) {
				$s .= $remains;
				$remains = '';
			}
		}

		$s .= $remains . $this->renderControls($this->form);

		$container = $this->getWrapper('form container');
		$container->setHtml($s);
		return $container->render(0);
	}

	/**
	 * Renders group of controls.
	 * @param  FormContainer|FormGroup
	 * @return string
	 */
	public function renderControls($parent)
	{
		if (!($parent instanceof FormContainer || $parent instanceof FormGroup)) {
			throw new \InvalidArgumentException("Argument must be FormContainer or FormGroup instance.");
		}

		$container = $this->getWrapper('controls container');

		$buttons = NULL;
		foreach ($parent->getControls() as $control) {
			if ($control->getOption('rendered') || $control instanceof HiddenField || $control->getForm(FALSE) !== $this->form) {
				// skip

			} elseif ($control instanceof Button) {
				$buttons[] = $control;

			} else {
				if ($buttons) {
					$container->add($this->renderPairMulti($buttons));
					$buttons = NULL;
				}
				$container->add($this->renderPair($control));
			}
		}

		if ($buttons) {
			$container->add($this->renderPairMulti($buttons));
		}

		$s = '';
		if (count($container)) {
			$s .= "\n" . $container . "\n";
		}

		return $s;
	}

	/**
	 * Renders single visual row.
	 * @param  IFormControl
	 * @return string
	 */
	public function renderPair(IFormControl $control)
	{
		$pair = $this->getWrapper('pair container');
		$pair->add($this->renderLabel($control));
		$pair->add($this->renderControl($control));
		$pair->class($this->getValue($control->getOption('required') ? 'pair .required' : 'pair .optional'), TRUE);
		$pair->class($control->getOption('class'), TRUE);
		if (++$this->counter % 2) $pair->class($this->getValue('pair .odd'), TRUE);
		$pair->id = $control->getOption('id');
		return $pair->render(0);
	}

	/**
	 * Renders single visual row of multiple controls.
	 * @param  array of IFormControl
	 * @return string
	 */
	public function renderPairMulti(array $controls)
	{
		$s = array();
		foreach ($controls as $control) {
			if (!($control instanceof IFormControl)) {
				throw new \InvalidArgumentException("Argument must be array of IFormControl instances.");
			}
			$s[] = (string) $control->getControl();
		}
		$pair = $this->getWrapper('pair container');
		$pair->add($this->renderLabel($control));
		$pair->add($this->getWrapper('control container')->setHtml(implode(" ", $s)));
		return $pair->render(0);
	}

	/**
	 * Renders 'label' part of visual row of controls.
	 * @param  IFormControl
	 * @return string
	 */
	public function renderLabel(IFormControl $control)
	{
		$head = $this->getWrapper('label container');

		if ($control instanceof Checkbox || $control instanceof Button) {
			return $head->setHtml(($head->getName() === 'td' || $head->getName() === 'th') ? ' ' : '');

		} else {
			$label = $control->getLabel();
			$suffix = $this->getValue('label suffix') . ($control->getOption('required') ? $this->getValue('label requiredsuffix') : '');
			if ($label instanceof Html) {
				$label->setHtml($label->getHtml() . $suffix);
				$suffix = '';
			}
			return $head->setHtml((string) $label . $suffix);
		}
	}

	/**
	 * Renders 'control' part of visual row of controls.
	 * @param  IFormControl
	 * @return string
	 */
	public function renderControl(IFormControl $control)
	{
		$body = $this->getWrapper('control container');
		if ($this->counter % 2) $body->class($this->getValue('control .odd'), TRUE);

		$description = $control->getOption('description');
		if ($description instanceof Html) {
			$description = ' ' . $control->getOption('description');

		} elseif (is_string($description)) {
			$description = ' ' . $this->getWrapper('control description')->setText($control->translate($description));

		} else {
			$description = '';
		}

		if ($control->getOption('required')) {
			$description = $this->getValue('control requiredsuffix') . $description;
		}

		if ($this->getValue('control errors')) {
			$description .= $this->renderErrors($control);
		}

		if ($control instanceof Checkbox || $control instanceof Button) {
			return $body->setHtml((string) $control->getControl() . (string) $control->getLabel() . $description);

		} else {
			return $body->setHtml((string) $control->getControl() . $description);
		}
	}

	/**
	 * @param  string
	 * @return Nette\Web\Html
	 */
	protected function getWrapper($name)
	{
		$data = $this->getValue($name);
		return $data instanceof Html ? clone $data : Html::el($data);
	}

	/**
	 * @param  string
	 * @return string
	 */
	protected function getValue($name)
	{
		$name = explode(' ', $name);
		$data = & $this->wrappers[$name[0]][$name[1]];
		return $data;
	}

}


text:
package io.apiman.gateway.api.rest.impl;

import io.apiman.common.util.ServiceRegistryUtil;
import io.apiman.gateway.engine.IEngine;
import io.apiman.gateway.engine.async.IAsyncResultHandler;
import io.apiman.gateway.engine.beans.exceptions.AbstractEngineException;

import java.util.Set;
import java.util.concurrent.CountDownLatch;

import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.core.Response;

/**
 * Base class for all resource implementation classes.
 *
 * @author eric.wittmann@redhat.com
 */
public abstract class AbstractResourceImpl {

    /**
     * Constructor.
     */
    public AbstractResourceImpl() {
    }

    /**
     * @return the api management runtime engine
     */
    protected IEngine getEngine() {
        return ServiceRegistryUtil.getSingleService(IEngineAccessor.class).getEngine();
    }

    /**
     * @return the current platform
     */
    protected IPlatform getPlatform() {
        return ServiceRegistryUtil.getSingleService(IPlatformAccessor.class).getPlatform();
    }

    protected IAsyncResultHandler<Void> latchedResultHandler(CountDownLatch latch, Set<Throwable> errorHolder) {
        return result -> {
            if (result.isError()) {
                errorHolder.add(result.getError());
            }
            latch.countDown();
        };
    }

    protected void awaitOnLatch(CountDownLatch latch, Set<Throwable> errorHolder) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (!errorHolder.isEmpty()) {
            Throwable error = errorHolder.iterator().next();
            if (error instanceof AbstractEngineException) {
                throw (AbstractEngineException) error;
            } else {
                throw new RuntimeException(error);
            }
        }
    }

    protected <T> IAsyncResultHandler<T> handlerWithResult(AsyncResponse response) {
        return result -> {
            if (result.isSuccess()) {
                response.resume(Response.ok(result.getResult()).build());
            } else {
                throwError(result.getError());
            }
        };
    }

    protected <T> IAsyncResultHandler<T> handlerWithEmptyResult(AsyncResponse response) {
        return result -> {
            if (result.isSuccess()) {
                response.resume(Response.ok().build());
            } else {
                throwError(result.getError());
            }
        };
    }

    protected void throwError(Throwable error) {
        if (error instanceof RuntimeException) {
            throw (RuntimeException) error;
        } else {
            throw new RuntimeException(error);
        }
    }
}


text:
<?php

namespace Arthurh\RestProxifier;

use orange\cfhelper\CfHelper;
use orange\cfhelper\services\Service;

class DatabaseConnector
{

    /**
     * @var Config
     */
    private $config;
    /**
     * @var \PDO;
     */
    private $connexion;

    const TABLE_NAME = 'rest_proxify';
    const SENTENCE_PDO = "%s:host=%s;%sdbname=%s";
    const DBTYPE_PG = "(postgres|pgsql)";
    const DBTYPE_MYSQL = "(maria|my)";
    const DBTYPE_ORACLE = "(oracle|oci)";
    const DBTYPE_SQLITE = "sqlite";

    private function loadDatabase()
    {
        if (CfHelper::getInstance()->isInCloudFoundry()) {
            $this->loadDatabaseFromCloudFoundry();
        } else {
            $this->loadDatabaseFromConfig();
        }
    }

    private function loadSchema()
    {
        if (empty($this->connexion)) {
            return;
        }
        $schemaSql = file_get_contents(__DIR__ . '/../../../assets/sql/create_schema.sql');
        $this->connexion->exec(sprintf($schemaSql, self::TABLE_NAME));
    }

    private function parseDbFromService(Service $service)
    {
        $url = $service->getValue('(uri|url)');
        if (!empty($url)) {
            return $this->parseDbUrl($url);
        }
        $host = $service->getValue('.*host.*');
        $port = $service->getValue('.*port.*');
        if (!empty($port)) {
            $port = sprintf("port=%s;", $port);
        } else {
            $port = "";
        }
        $user = $service->getValue('.*(user|login).*');
        $password = $service->getValue('.*pass.*');
        $type = $service->getValue('.*(type).*');
        $database = $service->getValue('.*(name|database|db).*');
        if (empty($type)) {
            $type = $this->getDbTypeFromServiceName($service->getName());
        }
        $toReturn['sentencePdo'] = sprintf(self::SENTENCE_PDO, $type,
            $host, $port, $database);
        $toReturn['user'] = $user;
        $toReturn['pass'] = $password;
        return $toReturn;
    }

    private function getDbTypeFromServiceName($serviceName)
    {
        if (preg_match('#.*' . self::DBTYPE_MYSQL . '.*#i', $serviceName)) {
            return "mysql";
        }
        if (preg_match('#.*' . self::DBTYPE_ORACLE . '.*#i', $serviceName)) {
            return "oci";
        }
        if (preg_match('#.*' . self::DBTYPE_PG . '.*#i', $serviceName)) {
            return "pgsql";
        }
        if (preg_match('#.*' . self::DBTYPE_SQLITE . '.*#i', $serviceName)) {
            return "sqlite";
        }
    }

    private function loadDatabaseFromConfig()
    {
        $db = $this->getConfig()->get('database', false);
        if (empty($db)) {
            return;
        }
        $dbParsed = $this->parseDbUrl($db);
        $this->loadDatabaseFromDbParsed($dbParsed);
    }

    private function parseDbUrl($url)
    {
        if (stristr($url, 'sqlite') !== FALSE) {
            return $url;
        }
        $toReturn = [];
        $port = "";
        $parsedUrl = parse_url($url);

        if (!empty($parsedUrl['port'])) {
            $port = sprintf("port=%s;", $parsedUrl['port']);
        }
        $toReturn['sentencePdo'] = sprintf(self::SENTENCE_PDO, $parsedUrl['scheme'],
            $parsedUrl['host'], $port, str_replace('/', '', $parsedUrl['path']));
        $toReturn['user'] = $parsedUrl['user'];
        $toReturn['pass'] = $parsedUrl['pass'];
        return $toReturn;
    }

    private function loadDatabaseFromCloudFoundry()
    {
        $dbToFind = implode('|', [
            self::DBTYPE_ORACLE,
            self::DBTYPE_MYSQL,
            self::DBTYPE_PG,
            self::DBTYPE_SQLITE
        ]);
        $dbService = CfHelper::getInstance()->getServiceManager()->getService('.*(db|database|(' . $dbToFind . ')).*');
        if ($dbService == null) {
            return;
        }
        $dbParsed = $this->parseDbFromService($dbService);
        $this->loadDatabaseFromDbParsed($dbParsed);
    }

    private function loadDatabaseFromDbParsed($dbParsed)
    {
        if (is_array($dbParsed)) {
            $this->connexion = new \PDO($dbParsed['sentencePdo'], $dbParsed['user'], $dbParsed['pass']);
        } else {
            $this->connexion = new \PDO($dbParsed);
        }
        $this->connexion->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    }

    /**
     * @return Config
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @param Config $config
     * @Required
     */
    public function setConfig($config)
    {
        $this->config = $config;
        $this->loadDatabase();
        $this->loadSchema();
    }

    /**
     * @return \PDO
     */
    public function getConnexion()
    {
        return $this->connexion;
    }

}


text:
package aos.mime4j.parser;

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

import org.apache.james.mime4j.parser.ContentHandler;
import org.apache.james.mime4j.stream.BodyDescriptor;
import org.apache.james.mime4j.stream.Field;
import org.apache.james.mime4j.util.ContentUtil;

/**
 * Helper class to run comparison of parsed results
 */
class Mime4jTestHandler implements ContentHandler {

    StringBuilder sb = new StringBuilder();

    private String escape(char c) {
        if (c == '&') {
            return "&";
        }
        if (c == '>') {
            return ">";
        }
        if (c == '<') {
            return "<";
        }
        return "" + c;
    }

    private String escape(String s) {
        s = s.replaceAll("&", "&");
        s = s.replaceAll(">", ">");
        s = s.replaceAll("<", "<");
        return s;
    }

    public void epilogue(InputStream is) throws IOException {
        sb.append("<epilogue>\r\n");
        int b = 0;
        while ((b = is.read()) != -1) {
            sb.append(escape((char) b));
        }
        sb.append("</epilogue>\r\n");
    }
    public void preamble(InputStream is) throws IOException {
        sb.append("<preamble>\r\n");
        int b = 0;
        while ((b = is.read()) != -1) {
            sb.append(escape((char) b));
        }
        sb.append("</preamble>\r\n");
    }
    public void startMultipart(BodyDescriptor bd) {
        sb.append("<multipart>\r\n");
    }
    public void body(BodyDescriptor bd, InputStream is) throws IOException {
        sb.append("\r\n");
        int b = 0;
        while ((b = is.read()) != -1) {
            sb.append(escape((char) b));
        }
        sb.append("\r\n");
    }
    public void endMultipart() {
        sb.append("</multipart>\r\n");
    }
    public void startBodyPart() {
        sb.append("\r\n");
    }
    public void endBodyPart() {
        sb.append("\r\n");
    }
    public void startHeader() {
        sb.append("\r\n");
    }
    public void field(Field field) {
        sb.append("<field>\r\n"
                + escape(ContentUtil.decode(field.getRaw()))
                + "</field>\r\n");
    }
    public void endHeader() {
        sb.append("\r\n");
    }
    public void startMessage() {
        sb.append("<message>\r\n");
    }
    public void endMessage() {
        sb.append("</message>\r\n");
    }

    public void raw(InputStream is) throws IOException {
        Mime4jStreamParserTest.fail("raw should never be called");
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Oxystelma wallichii Wight

### Remarks
null


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$this->title = 'Filtrado Movimientos';
$this->params['breadcrumbs'][] = ['label' => 'Movimientos', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

?>

Comparadores:

=

<>

<

>

<=

>=

Like

Between

Atributos

        <?php foreach($model->attributeLabels() as $key=>$valor){
            $tipo='';
            $mivalor='';
                if (is_array($tipos[$valor])){
                    $tipo='select';
                    foreach($tipos[$valor] as $clave=>$val){
                        $mivalor.=$clave.':'.$val.'_';
                    }
                    $mivalor=substr($mivalor,0,strlen($mivalor)-1);
                }else{
                    $tipo = $tipos[$valor];
                }
                echo '
'.$valor.'

';
        }?>

                    atributo

                    Comparador

                    Valor

ORDEN

                    atributo

Ascendente

Descendente

Hay errores en las consultas,
 Debe haber campos o atributos incompletos.

            <?php $form = ActiveForm::begin(['options' => ['id' => 'formfiltro']]); ?>
                <input id="consulta" name="consulta" type="hidden"></input>

Imprimir Listado

            </form><?php ActiveForm::end(); ?>


text:
<ui-switch checked="{ true }" sm></ui-switch>
<ui-switch checked="{ true }"></ui-switch>
<ui-switch checked="{ true }" lg></ui-switch>


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

<TITLE>
AdvancedEditText.OnTextChangedListener
</TITLE>

<META NAME="date" CONTENT="2014-01-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      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.hipipal.texteditor.ui.view

Interface AdvancedEditText.OnTextChangedListener

Enclosing class:
AdvancedEditText

public static interface AdvancedEditText.OnTextChangedListener

Method Summary

 void
onTextChanged(java.lang.String text)

Method Detail

onTextChanged

void onTextChanged(java.lang.String text)

      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 com.getfsc.retroserver.annotation;

/**
 * Created by IntelliJ IDEA.
 * User: draco
 * Date: 16/4/11
 * Time: 上午9:51
 */

import com.squareup.javapoet.TypeSpec;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Annotation processor for Complexity annotation type.
 *
 * @author deors
 * @version 1.0
 */
@SupportedAnnotationTypes({"com.getfsc.retroserver.annotation.Controller", "com.getfsc.retroserver.annotation.Bootstrap"})
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class ControllerProcessor
        extends AbstractProcessor {

    public static final String CONTROLLER_INDEX = "META-INF/controllers/index";

    private IndexWriter indexWriter;
    public Set<String> controllers = new HashSet<>();

    private boolean indexWrote = false;
    public Set<? extends Element> bootstrapElems;

    /**
     * Default constructor.
     */
    public ControllerProcessor() {

        super();
    }

    private HashMap<String, ControllerGenerator> generators = new HashMap<>();

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        indexWriter = new IndexWriter(processingEnv.getFiler());
    }

    /**
     * Reads the complexity value contained in the annotation and prints it in the console
     * (NOTE level).
     *
     * @param annotations set of annotations found
     * @param roundEnv    the environment for this processor round
     * @return whether a new processor round would be needed
     */
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        try {
            boolean controllerAdded = false;
            if(bootstrapElems==null)
                bootstrapElems = roundEnv.getElementsAnnotatedWith(Bootstrap.class);
            for (Element elem : roundEnv.getElementsAnnotatedWith(Controller.class)) {

                TypeElement classElement = (TypeElement) elem;
                String qualifiedName = classElement.getQualifiedName().toString();
                if (!controllers.contains(qualifiedName)) {
                    PackageElement packageElement =
                            processingEnv.getElementUtils().getPackageOf(classElement);

                    String pkg = packageElement.getQualifiedName().toString();
                    ControllerGenerator generator = generators.get(pkg);
                    if (generator == null) {
                        generator = new ControllerGenerator(pkg, processingEnv);
                        generators.put(pkg, generator);
                    }
                    TypeSpec clazz = generator.addControllerElem(classElement);
                    generator.build(clazz, pkg, processingEnv);
                    controllers.add(qualifiedName);
                    controllerAdded = true;

                }
            }

            if (controllerAdded) {
                return true;
            } else if (!indexWrote) {
                indexWriter.writeSimpleNameIndexFile(controllers, CONTROLLER_INDEX);
                indexWrote = true;
                return true;
            } else {
                for (Element elem : bootstrapElems) {
                    Bootstrap bootstrap = elem.getAnnotation(Bootstrap.class);
                    List<Pattern> filters = Arrays.asList(bootstrap.value())
                            .stream()
                            .map(Pattern::compile)
                            .collect(Collectors.toList());
                    Set<String> controllers = readIndexFile(this.getClass().getClassLoader(), CONTROLLER_INDEX);
                    controllers.addAll(this.controllers);

                    List<String> filtered = controllers.stream().filter(c ->
                            filters.stream().anyMatch(f -> f.matcher(c).find()))
                            .collect(Collectors.toList());
                    TypeElement classElement = (TypeElement) elem;

                    BootstrapGenerator.build(processingEnv,classElement, filtered);
                }
                return false;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static Set<String> readIndexFile(ClassLoader classLoader, String resourceFile) {
        Set<String> entries = new HashSet<>();

        try {
            Enumeration<URL> resources = classLoader.getResources(resourceFile);

            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream(), "UTF-8"))) {

                    String line = reader.readLine();
                    while (line != null) {
                        entries.add(line);
                        line = reader.readLine();
                    }
                } catch (FileNotFoundException e) {
                    // When executed under Tomcat started from Eclipse with "Serve modules without
                    // publishing" option turned on, getResources() method above returns the same
                    // resource two times: first with incorrect path and second time with correct one.
                    // So ignore the one which does not exist.
                    // See: https://github.com/atteo/classindex/issues/5
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("ClassIndex: Cannot read class index", e);
        }
        return entries;
    }

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>The Performance Test Application</title>
<link rel="stylesheet" href="../math.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="../index.html" title="Math Toolkit 2.2.0">
<link rel="up" href="../perf.html" title="Chapter 15. Performance">
<link rel="prev" href="comparisons.html" title="Comparisons to Other Open Source Libraries">
<link rel="next" href="../backgrounders.html" title="Chapter 16. Backgrounders">

Home
Libraries
People
FAQ
More

The Performance Test Application

      Under boost-path/libs/math/performance you will find a
      (fairly rudimentary) performance test application for this library.

      To run this application yourself, build the all the .cpp files in boost-path/libs/math/performance
      into an application using your usual release-build settings. Run the application
      with --help to see a full list of options, or with --all to test everything
      (which takes quite a while), or with --tune to test the available
      performance tuning options.

      If you want to use this application to test the effect of changing any of the
      Policies, then you will need to build and run
      it twice: once with the default Policies, and
      then a second time with the Policies you want
      to test set as the default.

Copyright © 2006-2010, 2012-2014 Nikhar Agrawal,
      Anton Bikineev, Paul A. Bristow, Marco Guazzone, Christopher Kormanyos, Hubert
      Holin, Bruno Lalande, John Maddock, Johan Råde, Gautam Sewani, Benjamin Sobotta,
      Thijs van den Berg, Daryle Walker and Xiaogang Zhang

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
"""
Logicalfile management functions.
"""

try:
    from lmiwbem import CIMError
except ImportError:
    from pywbem import CIMError

from lmi.scripts.common import get_computer_system
from lmi.scripts.common import get_logger
from lmi.scripts.common.errors import LmiFailed
from lmi.scripts.common.formatter import command as fcmd
LOG = get_logger(__name__)

def get_file_identification(file_instance):
    """
    Retrieve file identification.

    :type file_instance: LMIInstance
    :param file_instance: The file's instance object.
    :rtype: string
    """
    _CLASSES = {'lmi_datafile':'F',
                'lmi_unixdevicefile':'Dev',
                'lmi_unixdirectory':'Dir',
                'lmi_fifopipefile':'P',
                'lmi_symboliclink':'L',
                'lmi_unixsocket':'S'}
    try:
        return _CLASSES[file_instance.classname.lower()]
    except KeyError:
        return 'Unk'

def get_directory_name_properties(ns, directory):
    """
    Retrieve object path of a directory.

    :type directory: string
    :param directory: Full path to the directory.
    :rtype: LMIInstanceName
    """
    system = get_computer_system(ns)
    return {'CSCreationClassName':system.classname,
            'CSName':system.name,
            'CreationClassName':'LMI_UnixDirectory',
            'FSCreationClassName':'LMI_LocalFileSystem',
            'FSName':'',
            'Name':directory}

def get_directory_instance(ns, directory):
    """
    Retrieve LMIInstance of a directory.

    :type directory: string
    :param directory: Full path to the directory.
    :rtype: LMIInstance
    """
    name = ns.LMI_UnixDirectory.new_instance_name(get_directory_name_properties(ns, directory))
    return name.to_instance()

def walk_cim_directory(directory, depth=0):
    """
    Retrieve all files in a directory.

    If depth is positive, directory is walked recursively up to the given depth.
    Files and directories are yielded as they are encountered.
    This function does not return, it is a generator.

    :type directory: string
    :param directory: Full path to the directory.
    :type depth: integer
    :param depth: Maximum depth to be recursed to.
    """
    content = directory.associators(AssocClass='LMI_DirectoryContainsFile', Role='GroupComponent')
    content = sorted(content, key=lambda x: x.Name)
    dirs = filter(lambda f: f.classname == 'LMI_UnixDirectory', content)

    for f in content:
        yield (f, depth)
        if depth > 0 and f in dirs:
            for i in walk_cim_directory(f, depth - 1):
                yield i

def lf_list(ns, directory, depth=None):
    """
    List all files in a directory.

    If depth is positive, directory is walked recursively up to the given depth.

    :type directory: string
    :param directory: Full path to the directory.
    :type depth: integer
    :param depth: Maximum depth to be recursed to.
    """
    if directory != '/':
        directory = directory.rstrip('/')
    try:
        d = get_directory_instance(ns, directory)
    except:
        raise LmiFailed("Can't list directory: %s" % directory)
    if depth:
        try:
            depth = int(depth)
        except ValueError:
            raise LmiFailed("Depth must be integer.")
    else:
        depth = 0

    for (f, lvl) in walk_cim_directory(d, depth):
        rwx = ''
        rwx += 'r' if f.Readable else '-'
        rwx += 'w' if f.Writeable else '-'
        rwx += 'x' if f.Executable else '-'
        prefix = '  ' * (depth-lvl)
        ident = f.associators(AssocClass='LMI_FileIdentity')[0]
        yield(get_file_identification(f), prefix+f.Name, rwx, ident.SELinuxCurrentContext)

def lf_createdir(ns, directory):
    """
    Create a directory.

    The parent directory must exist.

    :type directory: string
    :param directory: Full path to the directory.
    """
    if directory != '/':
        directory = directory.rstrip('/')
    ns.LMI_UnixDirectory.create_instance(get_directory_name_properties(ns, directory))

    LOG().info("Successfully created directory: %s", directory)

def lf_deletedir(ns, directory):
    """
    Delete a directory.

    The directory must be empty.

    :type directory: string
    :param directory: Full path to the directory.
    """
    if directory != '/':
        directory = directory.rstrip('/')
    get_directory_instance(ns, directory).delete()

    LOG().info("Successfully deleted directory: %s", directory)

def lf_show(ns, target):
    """
    Show detailed information about the target.

    Target can be either a file or a directory.

    :type target: string
    :param target: Full path to the target.
    """
    system = get_computer_system(ns)
    uf_name = ns.LMI_UnixFile.new_instance_name(
        {'CSCreationClassName':system.classname,
         'CSName':system.name,
         'LFCreationClassName':'ignored',
         'FSCreationClassName':'ignored',
         'FSName':'ignored',
         'LFName':target})
    try:
        uf = uf_name.to_instance()
    except CIMError as err:
        raise LmiFailed('Could not get target "%s": %s' % (target, err))

    ident = uf.associators(AssocClass='LMI_FileIdentity')[0]

    yield fcmd.NewTableCommand(title=uf.Name)
    yield('Type', get_file_identification(ident))
    yield('Readable', ident.Readable)
    yield('Writeable', ident.Writeable)
    yield('Executable', ident.Executable)
    yield('UserID', uf.UserID)
    yield('GroupID', uf.GroupID)
    yield('SaveText', uf.SaveText)
    yield('SetGid', uf.SetGid)
    yield('SetUid', uf.SetUid)
    yield('FileSize', ident.FileSize)
    yield('LastAccessed', ident.LastAccessed)
    yield('LastModified', ident.LastModified)
    yield('FileInodeNumber', uf.FileInodeNumber)
    yield('SELinuxCurrentContext', uf.SELinuxCurrentContext)
    yield('SELinuxExpectedContext', uf.SELinuxExpectedContext)


text:
package com.hostel.config.dbmigrations;

import com.hostel.domain.Authority;
import com.hostel.domain.User;
import com.hostel.security.AuthoritiesConstants;

import com.github.mongobee.changeset.ChangeLog;
import com.github.mongobee.changeset.ChangeSet;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;

/**
 * Creates the initial database setup
 */
@ChangeLog(order = "001")
public class InitialSetupMigration {

    @ChangeSet(order = "01", author = "initiator", id = "01-addAuthorities")
    public void addAuthorities(MongoTemplate mongoTemplate) {
        Authority adminAuthority = new Authority();
        adminAuthority.setName(AuthoritiesConstants.ADMIN);
        Authority userAuthority = new Authority();
        userAuthority.setName(AuthoritiesConstants.USER);
        mongoTemplate.save(adminAuthority);
        mongoTemplate.save(userAuthority);
    }

    @ChangeSet(order = "02", author = "initiator", id = "02-addUsers")
    public void addUsers(MongoTemplate mongoTemplate) {
        Authority adminAuthority = new Authority();
        adminAuthority.setName(AuthoritiesConstants.ADMIN);
        Authority userAuthority = new Authority();
        userAuthority.setName(AuthoritiesConstants.USER);

        User adminUser = new User();
        adminUser.setId("user-0");
        adminUser.setLogin("admin");
        adminUser.setPassword("$2a$10$gSAhZrxMllrbgj/kkK9UceBPpChGWJA7SYIb1Mqo.n5aNLq1/oRrC");
        adminUser.setFirstName("admin");
        adminUser.setLastName("Administrator");
        adminUser.setEmail("admin@localhost");
        adminUser.setActivated(true);
        adminUser.setLangKey("en");
        adminUser.getAuthorities().add(userAuthority);
        adminUser.setCreatedBy(adminUser.getLogin());
        adminUser.setCreatedDate(ZonedDateTime.now());
        adminUser.setLastModifiedBy(adminUser.getLogin());
        adminUser.setLastModifiedDate(ZonedDateTime.now());
        mongoTemplate.save(adminUser);
    }

}