text:
function ClickHandler(buttonName) {
    msg = "Button " + buttonName + " pressed!"
    console.log(msg)
    var printarea  = $("#print")
    printarea.html(msg)
    var myButton = $("#defaultbutton")
    if (myButton.length) {
        myButton.removeClass('btn-default').addClass('btn-danger')
    } else {
        console.log("Cannot find defaultbutton")
    }

    console.log("Update button class!")
}

function EventHandler(type, name) {
    msg = "Event from " + name + " of type " + type
    console.log(msg)
    if (type == "textarea") {
        console.log("This is a textarea")
        var x = document.getElementById(name).value;
        console.log(x)
        var id = "#" + name
        var myobj = $("#mytextarea")
        var myval = myobj.value
        console.log(myval)
    }

}


text:
namespace workstealing
{
  using funcType = hpx::util::function<void()>;
  funcType workqueue::steal() {
      if (tasks.size() >= 1) {
        auto task = tasks.front();
        tasks.pop();
        return task;
      }
      return nullptr;
    }

    void workqueue::addWork(funcType task) {
      tasks.push(task);
    }
}
HPX_REGISTER_COMPONENT_MODULE();

typedef hpx::components::component<workstealing::workqueue> workqueue_type;

HPX_REGISTER_COMPONENT(workqueue_type, workqueue);

HPX_REGISTER_ACTION(workstealing::workqueue::steal_action, workqueue_steal_action);
HPX_REGISTER_ACTION(workstealing::workqueue::addWork_action, workqueue_addWork_action);

redpajama_set_name: RedPajamaGithub


text:
package co.johnrowley.codecounter;

import java.io.File;

public class FileWalker {
	ICommand command;

	public FileWalker(ICommand command){
		this.command = command;
	}

	public void walk(String path) {

		File root = new File( path );
		File[] list = root.listFiles();

		if (list == null) return;

		for ( File f : list ) {
        if ( f.isDirectory() && !f.getName().startsWith(".")) {
            walk( f.getAbsolutePath() );
				    command.directory(f.getAbsolutePath()); //directory
			  }
			  else {
				    command.file(f.getAbsolutePath()); //file
			  }
		}
	}
}


text:
import iterFloor10 = require( './index' );

/**
* Returns an iterator protocol-compliant object.
*
* @returns iterator protocol-compliant object
*/
function iterator() {
	return {
		'next': next
	};

	/**
	* Implements the iterator protocol `next` method.
	*
	* @returns iterator protocol-compliant object
	*/
	function next() {
		return {
			'value': true,
			'done': false
		};
	}
}

// TESTS //

// The function returns an iterator...
{
	iterFloor10( iterator() ); // $ExpectType Iterator
}

// The compiler throws an error if the function is provided a first argument which is not an iterator protocol-compliant object...
{
	iterFloor10( '5' ); // $ExpectError
	iterFloor10( 5 ); // $ExpectError
	iterFloor10( true ); // $ExpectError
	iterFloor10( false ); // $ExpectError
	iterFloor10( null ); // $ExpectError
	iterFloor10( undefined ); // $ExpectError
	iterFloor10( [] ); // $ExpectError
	iterFloor10( {} ); // $ExpectError
	iterFloor10( ( x: number ): number => x ); // $ExpectError
}

// The compiler throws an error if the function is provided insufficient arguments...
{
	iterFloor10(); // $ExpectError
}


text:
using UnityEngine;
using System.Collections;

public class TimeSpectreComplex : MonoBehaviour {

	public ScoreHandler scoreHandler;
	public int points;
	private int spectreStage;
	private const int stages = 5;
	private bool preparedChange;
	public float force =100f;
	public float distanceStage0=5f;
	public float distanceStage3=4f;
	private GameObject player;
	private Animator anim;

	// Use this for initialization
	void Start () {
		anim = GetComponent<Animator> ();
		spectreStage = 0;
		preparedChange = false;
		player = GameObject.FindGameObjectWithTag ("Player");
		rigidbody2D.MovePosition ( new Vector2((player.transform.position.x + distanceStage0), player.transform.position.y));

	}

	// Update is called once per frame
	void FixedUpdate () {

		switch(spectreStage){
		case 0:
			rigidbody2D.MovePosition ( new Vector2(player.transform.position.x + distanceStage0,
			                                       player.transform.position.y));
			break;
		case 1:
			rigidbody2D.AddForce ( new Vector2 ((-force),0));
			break;
		case 2:
			rigidbody2D.AddForce (new Vector2 (force , 0));
			break;
		case 3:
			rigidbody2D.MovePosition ( new Vector2(player.transform.position.x + distanceStage3, player.transform.position.y));
			rigidbody2D.velocity=(new Vector2 (0,0));
			break;
		case 4:
			rigidbody2D.AddForce ( new Vector2 (force,0));
			break;

		}

	}

	void Update () {

		if (spectreStage == 0 && !preparedChange) {
			preparedChange = !preparedChange;
			Invoke("ChangeOfStage",3f);
		}

		if (spectreStage == 1 && (rigidbody2D.transform.position.x < player.transform.position.x)) {
			rigidbody2D.velocity=(new Vector2 (0,0));
			preparedChange = !preparedChange;
			ChangeOfStage ();
			anim.SetBool("Back",true);

		}

		if (spectreStage == 2 && ((rigidbody2D.transform.position.x - player.transform.position.x) > distanceStage3)) {
			preparedChange = !preparedChange;
			ChangeOfStage ();
			anim.SetBool("Back",false);

		}

		if (spectreStage == 3 && !preparedChange) {
			preparedChange = !preparedChange;
			Invoke("ChangeOfStage",1.5f);
		}

		if (spectreStage == 4 && ((rigidbody2D.transform.position.x ) > (player.transform.position.x + distanceStage0))) {

			preparedChange = !preparedChange;
			rigidbody2D.velocity=(new Vector2 (0,0));
			ChangeOfStage ();

		}

	}

	private void ChangeOfStage(){
		spectreStage = (spectreStage + 1) % stages;
		preparedChange = !preparedChange;

	}

	void EnemyDie(){
		GameObject gc=GameObject.FindWithTag("GameController");
		gc.GetComponent<ScoreHandler>().AddPoints(points);
		Destroy (gameObject);
	}
}


text:
/**
 * Swaggy Jenkins
 * Jenkins API clients generated from Swagger / Open API specification
 *
 * The version of the OpenAPI document: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package org.openapitools.client.model;

import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;

@ApiModel(description = "")
public class User {

  @SerializedName("_class")
  private String _class = null;
  @SerializedName("id")
  private String id = null;
  @SerializedName("fullName")
  private String fullName = null;
  @SerializedName("email")
  private String email = null;
  @SerializedName("name")
  private String name = null;

  /**
   **/
  @ApiModelProperty(value = "")
  public String getClass() {
    return _class;
  }
  public void setClass(String _class) {
    this._class = _class;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  public String getFullName() {
    return fullName;
  }
  public void setFullName(String fullName) {
    this.fullName = fullName;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  public String getEmail() {
    return email;
  }
  public void setEmail(String email) {
    this.email = email;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    User user = (User) o;
    return (this._class == null ? user._class == null : this._class.equals(user._class)) &&
        (this.id == null ? user.id == null : this.id.equals(user.id)) &&
        (this.fullName == null ? user.fullName == null : this.fullName.equals(user.fullName)) &&
        (this.email == null ? user.email == null : this.email.equals(user.email)) &&
        (this.name == null ? user.name == null : this.name.equals(user.name));
  }

  @Override
  public int hashCode() {
    int result = 17;
    result = 31 * result + (this._class == null ? 0: this._class.hashCode());
    result = 31 * result + (this.id == null ? 0: this.id.hashCode());
    result = 31 * result + (this.fullName == null ? 0: this.fullName.hashCode());
    result = 31 * result + (this.email == null ? 0: this.email.hashCode());
    result = 31 * result + (this.name == null ? 0: this.name.hashCode());
    return result;
  }

  @Override
  public String toString()  {
    StringBuilder sb = new StringBuilder();
    sb.append("class User {\n");

    sb.append("  _class: ").append(_class).append("\n");
    sb.append("  id: ").append(id).append("\n");
    sb.append("  fullName: ").append(fullName).append("\n");
    sb.append("  email: ").append(email).append("\n");
    sb.append("  name: ").append(name).append("\n");
    sb.append("}\n");
    return sb.toString();
  }
}


text:
TitleWidget::TitleWidget()
{
    setFocusPolicy( Qt::ClickFocus );

    m_imgBackground = new QPixmap( "images/TitleScreen.jpg" );
    m_imgCross = new QPixmap( "images/Cross.png" );
    m_imgGear = new QPixmap( "images/Gear.png" );
    m_imgPlay = new QPixmap( "images/Play.png" );

    m_lbBackground = new QLabel( this );
    m_lbBackground->setPixmap( *m_imgBackground );
    m_lbBackground->setScaledContents( true );

    QIcon iconPlay = QIcon( *m_imgPlay );
    m_btnPlay = new QPushButton( this );
    m_btnPlay->setIcon( iconPlay );
    m_btnPlay->setStyleSheet("QPushButton{background-color: rgba(0,0,0,0%); outline: none;}");

    QIcon iconCross = QIcon( *m_imgCross );
    m_btnExit = new QPushButton( this );
    m_btnExit->setIcon( iconCross );
    m_btnExit->setStyleSheet("QPushButton{background-color: rgba(0,0,0,0%); outline: none;}");

    QIcon iconGear = QIcon( *m_imgGear );
    m_btnSettings = new QPushButton( this );
    m_btnSettings->setIcon( iconGear );
    m_btnSettings->setStyleSheet("QPushButton{background-color: rgba(0,0,0,0%); outline: none;}");

    resize();

    connect( m_btnPlay, SIGNAL( released() ), this, SIGNAL( clickedPlay() ) );
    connect( m_btnSettings, SIGNAL( released() ), this,
        SIGNAL( clickedSettings () ) );
    connect( m_btnExit, SIGNAL( released() ), this, SIGNAL( clickedExit() ) );
}

TitleWidget::~TitleWidget()
{
    delete m_imgBackground;
    delete m_imgCross;
    delete m_imgGear;
    delete m_imgPlay;
    delete m_lbBackground;
    delete m_btnPlay;
    delete m_btnExit;
    delete m_btnSettings;
}

void TitleWidget::resizeEvent( QResizeEvent* event )
{
    (void)event;
    resize();
}

void TitleWidget::resize()
{
    float percentWidth = QWidget::width() / 1855.0f;
    float percentHeight = QWidget::height() / 1056.0f;

    m_lbBackground->setGeometry( 0, 0, QWidget::width(), QWidget::height() );

    m_btnPlay->setIconSize( QSize( 65 * percentWidth, 70 * percentHeight ) );
    m_btnPlay->setGeometry( QWidget::width() - (450.0f * percentWidth), QWidget::height() - (170 * percentHeight),
        80 * percentWidth, 80 * percentHeight );

    m_btnExit->setIconSize( QSize( 69 * percentWidth, 70 * percentHeight ) );
    m_btnExit->setGeometry( QWidget::width() - (350.0f * percentWidth), QWidget::height() - (170 * percentHeight),
        80 * percentWidth, 80 * percentHeight );

    m_btnSettings->setIconSize( QSize( 80 * percentWidth, 79 * percentHeight ) );
    m_btnSettings->setGeometry( QWidget::width() - (250.0f * percentWidth), QWidget::height() - (170 * percentHeight),
        80 * percentWidth, 80 * percentHeight );
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/security/manager/ssl/public/nsIPK11TokenDB.idl
 */

#ifndef __gen_nsIPK11TokenDB_h__
#define __gen_nsIPK11TokenDB_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIPK11Token; /* forward declaration */

class nsIEnumerator; /* forward declaration */

#define NS_PK11TOKENDB_CONTRACTID "@mozilla.org/security/pk11tokendb;1"

/* starting interface:    nsIPK11TokenDB */
#define NS_IPK11TOKENDB_IID_STR "4ee28c82-1dd2-11b2-aabf-bb4017abe395"

#define NS_IPK11TOKENDB_IID \
  {0x4ee28c82, 0x1dd2, 0x11b2, \
    { 0xaa, 0xbf, 0xbb, 0x40, 0x17, 0xab, 0xe3, 0x95 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIPK11TokenDB : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IPK11TOKENDB_IID)

  /* nsIPK11Token getInternalKeyToken (); */
  NS_SCRIPTABLE NS_IMETHOD GetInternalKeyToken(nsIPK11Token * *_retval NS_OUTPARAM) = 0;

  /* nsIPK11Token findTokenByName (in wstring tokenName); */
  NS_SCRIPTABLE NS_IMETHOD FindTokenByName(const PRUnichar * tokenName, nsIPK11Token * *_retval NS_OUTPARAM) = 0;

  /* nsIEnumerator listTokens (); */
  NS_SCRIPTABLE NS_IMETHOD ListTokens(nsIEnumerator * *_retval NS_OUTPARAM) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIPK11TokenDB, NS_IPK11TOKENDB_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIPK11TOKENDB \
  NS_SCRIPTABLE NS_IMETHOD GetInternalKeyToken(nsIPK11Token * *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD FindTokenByName(const PRUnichar * tokenName, nsIPK11Token * *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD ListTokens(nsIEnumerator * *_retval NS_OUTPARAM);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIPK11TOKENDB(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetInternalKeyToken(nsIPK11Token * *_retval NS_OUTPARAM) { return _to GetInternalKeyToken(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD FindTokenByName(const PRUnichar * tokenName, nsIPK11Token * *_retval NS_OUTPARAM) { return _to FindTokenByName(tokenName, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD ListTokens(nsIEnumerator * *_retval NS_OUTPARAM) { return _to ListTokens(_retval); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIPK11TOKENDB(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetInternalKeyToken(nsIPK11Token * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetInternalKeyToken(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD FindTokenByName(const PRUnichar * tokenName, nsIPK11Token * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->FindTokenByName(tokenName, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD ListTokens(nsIEnumerator * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->ListTokens(_retval); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsPK11TokenDB : public nsIPK11TokenDB
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIPK11TOKENDB

  nsPK11TokenDB();

private:
  ~nsPK11TokenDB();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsPK11TokenDB, nsIPK11TokenDB)

nsPK11TokenDB::nsPK11TokenDB()
{
  /* member initializers and constructor code */
}

nsPK11TokenDB::~nsPK11TokenDB()
{
  /* destructor code */
}

/* nsIPK11Token getInternalKeyToken (); */
NS_IMETHODIMP nsPK11TokenDB::GetInternalKeyToken(nsIPK11Token * *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIPK11Token findTokenByName (in wstring tokenName); */
NS_IMETHODIMP nsPK11TokenDB::FindTokenByName(const PRUnichar * tokenName, nsIPK11Token * *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIEnumerator listTokens (); */
NS_IMETHODIMP nsPK11TokenDB::ListTokens(nsIEnumerator * *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIPK11TokenDB_h__ */


text:
//
//  SunbeamAFServiceContext.h
//  Pods
//
//  Created by sunbeam on 16/6/29.
//
//

#import <Foundation/Foundation.h>
#import "SunbeamAFServiceFactory.h"

// 网络状态
typedef enum : NSUInteger {
    UNKNOWN             = -1,   // 未知
    NOT_REACHABLE       = 0,    // 不可达
    REACHABLE_VIA_WWAN  = 1,    // 蜂窝流量
    REACHABLE_VIA_WIFI  = 2,    // wifi
} SAF_NETWORK_STATUS;

// 网络状态发生变化时发送notification
#define SAF_NETWORK_STATUS_CHANGED_NOTIFICATION_NAME @"saf_network_status_changed_notification"

@interface SunbeamAFServiceContext : NSObject

/**
 *  单例
 */
+ (SunbeamAFServiceContext *) sharedSunbeamAFServiceContext;

/**
 网络请求超时时间设置
 */
@property (nonatomic, assign) NSTimeInterval timeoutInterval;

/**
 网络是否可达
 */
@property (nonatomic, assign, readonly) BOOL networkIsReachable;

/**
 当前网络状态
 */
@property (nonatomic, assign, readonly) SAF_NETWORK_STATUS networkStatus;

/**
 设置service factory代理

 @param SAFServiceFactoryDelegate 代理
 */
- (void) setSAFServiceFactoryDelegate:(id<SAFServiceFactoryProtocol>) SAFServiceFactoryDelegate;

/**
 监听网络状态改变

 @param networkStatusChangeBlock 网络状态改变回调
 */
- (void) startListenNetworkStatusChange:(void(^)(SAF_NETWORK_STATUS networkStatus)) networkStatusChangeBlock;

@end


text:
package org.killbill.billing.plugin.meter.timeline;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.killbill.billing.plugin.meter.timeline.persistent.FileBackedBuffer;
import org.killbill.billing.plugin.meter.timeline.sources.SourceSamplesForTimestamp;

public class MockFileBackedBuffer extends FileBackedBuffer {

    private final List<SourceSamplesForTimestamp> hostSamplesForTimestamps = new ArrayList<SourceSamplesForTimestamp>();

    public MockFileBackedBuffer() throws IOException {
        // Kepp it small - 50 bytes. Will be allocated but not used
        super(String.valueOf(System.nanoTime()), "test", 50, 1);
    }

    @Override
    public boolean append(final SourceSamplesForTimestamp hostSamplesForTimestamp) {
        hostSamplesForTimestamps.add(hostSamplesForTimestamp);
        return true;
    }

    /**
     * Discard in-memory and on-disk data
     */
    @Override
    public void discard() {
        hostSamplesForTimestamps.clear();
    }

    @Override
    public long getBytesInMemory() {
        return -1;
    }

    @Override
    public long getBytesOnDisk() {
        return 0;
    }

    @Override
    public long getFilesCreated() {
        return 0;
    }

    @Override
    public long getInMemoryAvailableSpace() {
        return -1;
    }

    public List<SourceSamplesForTimestamp> getSourceSamplesForTimestamps() {
        return hostSamplesForTimestamps;
    }
}


text:
<?php

declare(strict_types=1);

namespace Zhiyi\Component\ZhiyiPlus\PlusComponentFeed\API2;

use Illuminate\Contracts\Routing\ResponseFactory as ResponseContract;
use Illuminate\Http\Request;
use Zhiyi\Component\ZhiyiPlus\PlusComponentFeed\Models\Feed as FeedModel;
use Zhiyi\Plus\Http\Controllers\Controller;
use Zhiyi\Plus\Notifications\Like as LikeNotification;

class LikeController extends Controller
{
    /**
     * Get feed likes.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Contracts\Routing\ResponseFactory $response
     * @param \Zhiyi\Component\ZhiyiPlus\PlusComponentFeed\Models\Feed $feed
     * @return mixed
     * @author Seven Du <shiweidu@outlook.com>
     */
    public function index(Request $request, ResponseContract $response, FeedModel $feed)
    {
        $limit = $request->query('limit', 15);
        $after = $request->query('after', false);
        $userID = $request->user('api')->id ?? 0;
        $likes = $feed->likes()
            ->whereHas('user')
            ->with(['user' => function ($query) {
                return $query->withTrashed();
            }])
            ->when($after, function ($query) use ($after) {
                return $query->where('id', '<', $after);
            })
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        return $response->json(
            $feed->getConnection()->transaction(function () use ($likes, $userID) {
                return $likes->map(function ($like) use ($userID) {
                    if (! $like->relationLoaded('user')) {
                        return $like;
                    }

                    $like->user->following = false;
                    $like->user->follower = false;

                    if ($userID && $like->user_id !== $userID) {
                        $like->user->following = $like->user->hasFollwing($userID);
                        $like->user->follower = $like->user->hasFollower($userID);
                    }

                    return $like;
                });
            })
        )->setStatusCode(200);
    }

    /**
     * 用户点赞接口.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Contracts\Routing\ResponseFactory $response
     * @param \Zhiyi\Component\ZhiyiPlus\PlusComponentFeed\Models\Feed $feed
     * @return mixed
     * @author Seven Du <shiweidu@outlook.com>
     */
    public function store(Request $request, ResponseContract $response, FeedModel $feed)
    {
        $user = $request->user();
        if ($feed->liked($user)) {
            return $response->json(['message' => '操作成功'])->setStatusCode(201);
        }

        $like = $feed->like($user);
        if ($feed->user_id !== $user->id && $feed->user) {
            $feed->user->notify(new LikeNotification('动态', $like, $user));
        }

        return $response->json(['message' => '操作成功'])->setStatusCode(201);
    }

    /**
     * 取消动态赞.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Contracts\Routing\ResponseFactory $response
     * @param \Zhiyi\Component\ZhiyiPlus\PlusComponentFeed\Models\Feed $feed
     * @return mixed
     * @author Seven Du <shiweidu@outlook.com>
     */
    public function destroy(Request $request, ResponseContract $response, FeedModel $feed)
    {
        $user = $request->user();

        if (! $feed->liked($user)) {
            return $response->json(['message' => '操作成功'])->setStatusCode(204);
        }

        $feed->unlike($user);

        return $response->json(['message' => '操作成功'])->setStatusCode(204);
    }
}


text:
/**
 * @author Dmitry A. Durnev
 */
package org.apache.harmony.awt.wtk;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;

/**
 * A cross-platform interface for java.awt.Robot implementation
 */
public interface NativeRobot {

    /**
     * @see java.awt.Robot#createScreenCapture(Rectangle)
     * @param screenRect rectangle to capture in screen coordinates
     * @return the captured image or null if
     * capture failed.
     */
    BufferedImage createScreenCapture(Rectangle screenRect);

    /**
     * @see java.awt.Robot#getPixelColor(int, int)
     */
    Color getPixel(int x, int y);

    /**
     * Generate a native system keyboard input event.
     * @param keycode A Java virtual key code
     * @param press A key is pressed if true, released otherwise
     * @see java.awt.Robot#keyPress(int)
     * @throws IllegalArgumentException if keycode is invalid in the native system
     */
    void keyEvent(int keycode, boolean press);

    /**
     * Generate a native system mouse button(s) press or release event.
     * @param buttons A mask of Java mouse button flags
     * @param press buttons are pressed if true, released otherwise
     * @see java.awt.Robot#mousePress(int)
     */
    void mouseButton(int buttons, boolean press);

    /**
     * Generate a native system mouse motion event.
     *
     * @see java.awt.Robot#mouseMove(int, int)
     */
    void mouseMove(int x, int y);

    /**
     * Generate a native system mouse wheel event.
     *
     * @see java.awt.Robot#mouseWheel(int)
     */
    void mouseWheel(int wheelAmt);
}


text:
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.zone_hvac_controls_and_thermostats import ThermostatSetpointThermalComfortFangerSingleHeatingOrCooling

log = logging.getLogger(__name__)

class TestThermostatSetpointThermalComfortFangerSingleHeatingOrCooling(unittest.TestCase):

    def setUp(self):
        self.fd, self.path = tempfile.mkstemp()

    def tearDown(self):
        os.remove(self.path)

    def test_create_thermostatsetpointthermalcomfortfangersingleheatingorcooling(self):

        pyidf.validation_level = ValidationLevel.error

        obj = ThermostatSetpointThermalComfortFangerSingleHeatingOrCooling()
        # alpha
        var_name = "Name"
        obj.name = var_name
        # object-list
        var_fanger_thermal_comfort_schedule_name = "object-list|Fanger Thermal Comfort Schedule Name"
        obj.fanger_thermal_comfort_schedule_name = var_fanger_thermal_comfort_schedule_name

        idf = IDF()
        idf.add(obj)
        idf.save(self.path, check=False)

        with open(self.path, mode='r') as f:
            for line in f:
                log.debug(line.strip())

        idf2 = IDF(self.path)
        self.assertEqual(idf2.thermostatsetpointthermalcomfortfangersingleheatingorcoolings[0].name, var_name)
        self.assertEqual(idf2.thermostatsetpointthermalcomfortfangersingleheatingorcoolings[0].fanger_thermal_comfort_schedule_name, var_fanger_thermal_comfort_schedule_name)


text:
layout: docs
title: Customization options
description: Customize Bootstrap 4 with our new built-in Sass variables for global style preferences for easy theming and component changes.
group: getting-started
toc: true
---

## Customizing variables

Every Sass variable in Bootstrap 4 includes the `!default` flag, meaning you can override that default value in your own Sass even after that original variable's been defined. Copy and paste variables as needed, modify the values, remove the `!default` flag, and recompile.

For example, to change out the `background-color` and `color` for the `<body>`, you'd do the following:

{% highlight scss %}
$body-bg:    $gray-900;
$body-color: $gray-600;
{% endhighlight %}

Do the same for any variable you need to override, including the global options listed below.

## Global options

Customize Bootstrap 4 with our built-in custom variables file and easily toggle global CSS preferences with new `$enable-*` Sass variables. Override a variable's value and recompile with `npm run test` as needed.

You can find and customize these variables for key global options in our `_variables.scss` file.

| Variable                    | Values                             | Description                                                                            |
| --------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------- |
| `$spacer`                   | `1rem` (default), or any value > 0 | Specifies the default spacer value to programmatically generate our [spacer utilities]({{ site.baseurl }}/docs/{{ site.docs_version }}/utilities/spacing/). |
| `$enable-rounded`           | `true` (default) or `false`        | Enables predefined `border-radius` styles on various components.                       |
| `$enable-shadows`           | `true` or `false` (default)        | Enables predefined `box-shadow` styles on various components.                          |
| `$enable-gradients`         | `true` or `false` (default)        | Enables predefined gradients via `background-image` styles on various components.      |
| `$enable-transitions`       | `true` (default) or `false`        | Enables predefined `transition`s on various components.                                |
| `$enable-hover-media-query` | `true` or `false` (default)        | ...                                                                                |
| `$enable-grid-classes`      | `true` (default) or `false`        | Enables the generation of CSS classes for the grid system (e.g., `.container`, `.row`, `.col-md-1`, etc.).     |
| `$enable-print-styles`      | `true` (default) or `false`        | Enables styles for optimizing printing.                                |

## Color

Many of Bootstrap's various components and utilities are built through a series of colors defined in a Sass map. This map can be looped over in Sass to quickly generate a series of rulesets.

### All colors

All colors available in Bootstrap 4, available as Sass variables and a Sass map in our `scss/_variables.scss` file. This will be expanded upon in subsequent minor releases to add additional shades, much like the [grayscale palette](#grays) we already include.

  {% for color in site.data.colors %}

      {% unless color.name == "white" or color.name == "gray" or color.name == "gray-dark" %}

{{ color.name | capitalize }}

      {% endunless %}

  {% endfor %}

Here's how you can use these in your Sass:

{% highlight scss %}
// With variable
.alpha { color: $purple; }

// From the Sass map with our `color()` function
.beta { color: color("purple"); }
{% endhighlight %}

[Color utility classes]({{ site.baseurl }}/docs/{{ site.docs_version }}/utilities/colors/) are also available for setting `color` and `background-color`.

{% callout info %}
In the future, we'll aim to provide Sass maps and variables for shades of each color as we've done with the grayscale colors below.
{% endcallout %}

### Theme colors

We use a subset of all colors to create a smaller color palette for generating color schemes, also available as Sass variables and a Sass map in our `scss/_variables.scss` file.

  {% for color in site.data.theme-colors %}

{{ color.name | capitalize }}

  {% endfor %}

### Grays

An expansive set of gray variables and a Sass map in `scss/_variables.scss` for consistent shades of gray across your project.

    {% for color in site.data.grays %}

{{ color.name | capitalize }}

    {% endfor %}

Within `_variables.scss`, you'll find our color variables and Sass map. Here's an example of the `$colors` Sass map:

{% highlight scss %}
$colors: (
  red: $red,
  orange: $orange,
  yellow: $yellow,
  green: $green,
  teal: $teal,
  blue: $blue,
  pink: $pink,
  purple: $purple,
  white: $white,
  gray: $gray-600,
  gray-dark: $gray-900
) !default;
{% endhighlight %}

Add, remove, or modify values within the map to update how they're used in many other components. Unfortunately at this time, not _every_ component utilizes this Sass map. Future updates will strive to improve upon this. Until then, plan on making use of the `${color}` variables and this Sass map.


text:
package net.wizardsoflua.file;

import java.nio.ByteBuffer;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.UUID;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Crypto {

  private static final String ALGORITHM = "AES";
  private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

  public String createRandomPassword() {
    SecureRandom random = new SecureRandom();
    byte[] bytes = new byte[16];
    random.nextBytes(bytes);
    return encodeBase64(bytes);
  }

  public String encrypt(UUID salt, String password, String input) throws BadPaddingException {
    try {
      IvParameterSpec iv = toInitializationVector(salt);
      SecretKeySpec keySpec = toKey(password);

      Cipher cipher = Cipher.getInstance(TRANSFORMATION);
      cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

      byte[] encrypted = cipher.doFinal(input.getBytes());

      String result = encodeBase64(encrypted);
      return result;
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
        | InvalidAlgorithmParameterException | IllegalBlockSizeException e) {
      throw new RuntimeException(e);
    }
  }

  public String decrypt(UUID salt, String password, String input) throws BadPaddingException {
    try {
      IvParameterSpec iv = toInitializationVector(salt);
      SecretKeySpec keySpec = toKey(password);

      Cipher cipher = Cipher.getInstance(TRANSFORMATION);
      cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);

      byte[] decodedInput = decodeBase64(input);
      byte[] decrypted = cipher.doFinal(decodedInput);

      String result = new String(decrypted);
      return result;
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
        | InvalidAlgorithmParameterException | IllegalBlockSizeException e) {
      throw new RuntimeException(e);
    }
  }

  private static SecretKeySpec toKey(String password) {
    byte[] passwordBytes = decodeBase64(password);
    return new SecretKeySpec(passwordBytes, ALGORITHM);
  }

  private static IvParameterSpec toInitializationVector(UUID salt) {
    byte[] saltBytes = toBytes(salt);
    return new IvParameterSpec(saltBytes);
  }

  private static byte[] toBytes(UUID uuid) {
    ByteBuffer buffer = ByteBuffer.allocate(2 * Long.BYTES);
    buffer.putLong(uuid.getMostSignificantBits());
    buffer.putLong(uuid.getLeastSignificantBits());
    return buffer.array();
  }

  private static String encodeBase64(byte[] input) {
    return new String(Base64.getUrlEncoder().encode(input)).replace("=", "");
  }

  private static byte[] decodeBase64(String input) {
    int len = input.length();
    for (int i = 0; i < 4 - (len % 4); ++i) {
      input += "=";
    }
    return Base64.getUrlDecoder().decode(input.getBytes());
  }

}


text:
\subsection[Esercizi]{Esercizi}

\begin{frame}[fragile]\frametitle{Esercizi (I)}

  \begin{itemize}
    \item inizializzare un array  di 10 interi e inserire in ciascun elemento
	  il valore 5 (utilizzare un ciclo for)
    \item inizializzare un  array  di  interi e assegnare a ciascun elemento
	  un valore uguale alla sua posizione
    \item Dopo aver inizializzato l'array precedente, copiare il suo  contenuto
	  in ordine nverso in un altro array della stessa dimensione.
    \begin{itemize}
      \item $(1, 2, 3) \rightarrow (3, 2, 1)$
    \end{itemize}
  \end{itemize}

  Suggerimento, con \texttt{arr.\Blue{length}} si può ottenere la lunghezza dell'array:
  \begin{JavaCodePlain}[commandchars=\\!|]
    \Jint arr[]
    arr = \Word!new| \Jint[10];

    \Jfor (\Jint i = 0; i < arr.length; i++) {
      \dots
    }
  \end{JavaCodePlain}

\end{frame}

\begin{frame}{Esercizi (I)}

  \begin{itemize}
  \item Implementare una funzione che dato in ingresso un vettore di numeri interi
	restituisca quel vettore ordinato in ordine crescente.
  \end{itemize}

  Esistono tantissimi algoritmi di ordinamento, ecco l'idea di base per uno di essi:
  \begin{itemize}
   \item array $v$ di lunghezza $N$, si fa scorrere l'indice $i$ da  $0$ a $N-1$ ripetendo i seguenti passi:
   \begin{enumerate}
    \item si cerca il più piccolo elemento della sottosequenza $v[i..N]$
    \item si scambia questo elemento con l'elemento $i$-esimo
   \end{enumerate}
  \end{itemize}

  Un'animazione descrittiva è disponibile a questo indirizzo:
  {\scriptsize \url{https://upload.wikimedia.org/wikipedia/commons/9/94/Selection-Sort-Animation.gif}}

\end{frame}

\begin{frame}{Esercizi (II)}

  \begin{itemize}
   \item Scrivere una funzione che calcoli il prodotto scalare (\texttt{\Word{double}}) di due vettori
   (di \texttt{\Word{double}}) :
  \end{itemize}

  \begin{equation}
    \langle  v, w \rangle = \sum_{i=1}^{N} v_i \cdot w_i
  \end{equation}

\end{frame}

\begin{frame}{Esercizi (III)}

  \begin{itemize}
    \item Scrivere un programma che data in ingresso una matrice di numeri casuali ne calcoli la matrice trasposta.
    \begin{itemize}
      \item Scrivere una funzione che stampi una matrice
      \item Scrivere una funzione che calcoli la matrice trasposta data una matrice
    \end{itemize}
  \end{itemize}

  Data la matrice $A$, la matrice trasposta - indicata con $A^T$ - si ottiene scambiando le righe con le colonne:
  \begin{columns}[T]
    \begin{column}[T]{5cm}
      \begin{equation*}
	A = \left(
	\begin{array}{ccc}
	  1 & 9 & 3 \\
	  0 & 4 & 5 \\
	  2 & 7 & 0 \\
	\end{array} \right)
      \end{equation*}
    \end{column}
    \begin{column}[T]{5cm}
      \begin{equation*}
	  A^T = \left(
	  \begin{array}{ccc}
	    1 & 0 & 2 \\
	    9 & 4 & 7 \\
	    3 & 5 & 0 \\
	  \end{array} \right)
      \end{equation*}
    \end{column}
  \end{columns}

\end{frame}

\begin{frame}{Esercizi (IV)}
  \begin{itemize}
    \item Scrivere un programma che dati in ingresso i tre coefficienti
	  $a$, $b$ e $c$ risolva le equazioni di secondo grado usando la formula.
    \begin{itemize}
      \item il programma deve gestire i casi in cui non esistano soluzioni reali
      (discriminante $\Delta = (b^2 - 4ac)$ negativo),
    \end{itemize}

  \end{itemize}

  \begin{equation*}
    x_{1,2} = \dfrac{-b \pm \sqrt{b^2 - 4ac}}{2a}
  \end{equation*}

\end{frame}


text:
package com.yidejia.app.mall.view;

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

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yidejia.app.mall.BaseActivity;
import com.yidejia.app.mall.MyApplication;
import com.yidejia.app.mall.R;
import com.yidejia.app.mall.adapter.IntegeralFragmentAdapter;
import com.yidejia.app.mall.datamanage.VoucherDataManage;
import com.yidejia.app.mall.fragment.ExchangeAdapter;
import com.yidejia.app.mall.fragment.ExchangeFragment;
import com.yidejia.app.mall.fragment.FreeGivingAdapter;
import com.yidejia.app.mall.fragment.FreeGivingFragment;
import com.yidejia.app.mall.model.Cart;
import com.yidejia.app.mall.model.Specials;
import com.yidejia.app.mall.pay.CstmPayActivity;
import com.yidejia.app.mall.util.Consts;

/**
 * 免费送和积分换购
 *
 * @author LiuYong
 *
 */
public class ExchangeFreeActivity extends BaseActivity {

	private ViewPager mPager;
	private ArrayList<Fragment> fragmentsList;

	private TextView mCoupons, mIntegeral;
	private ImageView ivBottomLine;
	private int currIndex = 0;
	private int bottomLineWidth;
	private int offset = 0;
	private int position_one;
	// private int position_two;
	// private int position_three;
	// private String sumprice;
	private List<HashMap<String, Float>> exchange;// 换购商品
	private List<HashMap<String, Object>> cart;// 换购商品
	private VoucherDataManage dataManage;// 用户积分
	// private float voucher;// 用户积分
	private MyApplication myApplication;
	private ArrayList<Cart> mArrayList;
	// private String isString;
	private AlertDialog dialog;
	private float voucher = 0.0f; // 用户总积分
	// private float needJifen = 0.0f; //用户本次购买消耗积分
	private float goodsPrice;

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
		goodsPrice = intent.getFloatExtra("price", 0.0f);
		voucher = intent.getFloatExtra("voucher", -1);
		// isString = intent.getStringExtra("cartActivity");
		try {
			mArrayList = (ArrayList<Cart>) intent.getSerializableExtra("carts");
		} catch (Exception e) {
		}
		setContentView(R.layout.pay_free);
		dialog = new Builder(this)
				.setIcon(R.drawable.ic_launcher)
				.setTitle(getResources().getString(R.string.tips))
				.setMessage(getResources().getString(R.string.sure_commit))
				.setPositiveButton(getResources().getString(R.string.sure),
						new android.content.DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								Intent intent = new Intent(
										ExchangeFreeActivity.this,
										CstmPayActivity.class);
								exchange = ExchangeAdapter.mlist1;
								cart = ExchangeAdapter.mlist2;

								float sum = 0;

								float sum1 = 0;
								for (int i = 0; i < exchange.size(); i++) {
									HashMap<String, Float> map = exchange
											.get(i);

									Float isSelelct = map.get("isCheck");
									Float price = map.get("price");
									Float count = map.get("count");
									if (isSelelct == 0.0) {
										sum = price * count;

										sum1 += sum;
									}

								}
								if (sum1 > voucher) {
									Toast.makeText(
											ExchangeFreeActivity.this,
											getResources().getString(
													R.string.my_voucher),
											Toast.LENGTH_SHORT).show();
									Intent intent1 = new Intent(
											Consts.EXCHANG_FREE);
									sendBroadcast(intent1);
									return;
									// }
								} else if (sum1 <= voucher) {// && isSelelct1 ==
																// 0.0
									for (int i = 0; i < cart.size(); i++) {
										HashMap<String, Object> map1 = cart
												.get(i);
										Float isSelelct1 = Float
												.parseFloat(map1
														.get("isCheck1")
														.toString());

										Float count1 = Float.parseFloat(map1
												.get("count1").toString());

										Specials specials = (Specials) map1
												.get("cart");
										Cart cart = new Cart();

										cart.setImgUrl(specials.getImgUrl());
										cart.setPrice(0);
										cart.setScort(specials.getScores());
										cart.setProductText(specials.getBrief());
										cart.setUId(specials.getUId());
										cart.setSalledAmmount(count1.intValue());
										if (isSelelct1 == 0.0 && count1 > 0) {
											mArrayList.add(cart);
											voucher = (int) (voucher - sum1);
										}
									}
								}
								Cart cart1 = FreeGivingAdapter.carts;
								Log.i("voucher", cart1 + "   cart1");
								if (null != cart1 && cart1.getUId() != null) {
									mArrayList.add(cart1);
								}
								intent.putExtra("price", goodsPrice);
								intent.putExtra("voucher", voucher);
								intent.putExtra("needJifen", sum1);

								intent.putExtra("carts", mArrayList);
								intent.putExtra("cartActivity", "E");
								setResult(Consts.CstmPayActivity_Response,
										intent);
								ExchangeFreeActivity.this.finish();

							}
						})
				.setNegativeButton(getResources().getString(R.string.cancel),
						null).create();
		if (null == mArrayList) {
			Toast.makeText(ExchangeFreeActivity.this,
					getResources().getString(R.string.no_network),
					Toast.LENGTH_SHORT).show();
		}
		dataManage = new VoucherDataManage(ExchangeFreeActivity.this);
		myApplication = (MyApplication) getApplication();
		if (voucher == -1) {
			voucher = Float.parseFloat(dataManage.getUserVoucher(
					myApplication.getUserId(), myApplication.getToken()));
		} else {
			// voucher = jifen;
		}

		InitWidth();
		InitTextView();
		InitViewPager();
		// setActionBar();
		setActionbarConfig();
		setTitle(getResources().getString(R.string.produce_exchange));

		TextView tvComplete = (TextView) findViewById(R.id.ab_common_tv_right);
		tvComplete.setVisibility(View.VISIBLE);
		tvComplete.setText(R.string.complete);
		tvComplete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.show();
			}
		});
	}

	private void InitTextView() {
		mIntegeral = (TextView) findViewById(R.id.pay_free_voucher_Coupons);// 赠送
		mCoupons = (TextView) findViewById(R.id.pay_free_voucher_mIntegeral);// 换购
		// mIntegeral.setSelected(true);
		mCoupons.setOnClickListener(new MyOnClickListener(1));
		mIntegeral.setOnClickListener(new MyOnClickListener(0));
	}

	private void InitViewPager() {
		mPager = (ViewPager) findViewById(R.id.avPager);
		fragmentsList = new ArrayList<Fragment>();
		// LayoutInflater mInflater = getLayoutInflater();

		Fragment freeGivingFragment = FreeGivingFragment
				.newInstance("zengsong");
		Fragment exchangeFragment = ExchangeFragment.newInstance("huangou");

		fragmentsList.add(freeGivingFragment);
		fragmentsList.add(exchangeFragment);

		mPager.setAdapter(new IntegeralFragmentAdapter(this
				.getSupportFragmentManager(), fragmentsList));
		if (CstmPayActivity.arrayListFree.isEmpty()) {
			mPager.setCurrentItem(1);
			mCoupons.setSelected(true);
			currIndex = 1;
		} else {
			mPager.setCurrentItem(0);
			mIntegeral.setSelected(true);
		}
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());

	}

	private void InitWidth() {
		ivBottomLine = (ImageView) findViewById(R.id.iv_bottom_line);// 滑动
		bottomLineWidth = ivBottomLine.getLayoutParams().width;
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);// 获取当前屏幕的属性
		int screenW = dm.widthPixels;// 屏幕的宽
		offset = (int) ((screenW / 3 - bottomLineWidth) / 2);// 起始位置

		position_one = (int) (screenW / 3);
		// position_two = position_one * 2;

	}

	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			mPager.setCurrentItem(index);
		}
	};

	public class MyOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:// 假如是第一个被选中,添加事件
				if (currIndex == 1) {// 当前是第二个
					mCoupons.setSelected(false);
					animation = new TranslateAnimation(position_one, 0, 0, 0);
				}
				mIntegeral.setSelected(true);
				break;
			case 1:
				if (currIndex == 0) {
					mIntegeral.setSelected(false);
					animation = new TranslateAnimation(offset, position_one, 0,
							0);
				}
				mCoupons.setSelected(true);
				break;

			}
			currIndex = arg0;
			animation.setFillAfter(true);
			animation.setDuration(300);
			ivBottomLine.startAnimation(animation);
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (!mArrayList.isEmpty())
			mArrayList.clear();
	}
}


text:
/* -*- mode: C; mode: folding; fill-column: 70; -*- */
/* Copyright 2010,  Georgia Institute of Technology, USA. */
/* See COPYING for license. */
#if !defined(RMAT_HEADER_)
#define RMAT_HEADER_

/** Fill IJ with a randomly permuted R-MAT generated edge list. */
void rmat_edgelist (int64_t *IJ, int64_t nedge, int SCALE,
		    double A, double B, double C);
void permute_vertex_labels (int64_t * IJ, int64_t nedge, int64_t max_nvtx,
			    void * st, int64_t * newlabel);
void permute_edgelist (int64_t * IJ, int64_t nedge, void *st);

#endif /* RMAT_HEADER_ */


text:
package com.microsoft.windowsazure.mobileservices;

/**
 * Callback to invoke after unregister the registration
 */
interface UnregisterInternalCallback {
	/**
	 * Method to execute when the unregister is finished
	 *
	 * @param registrationId
	 *            The registration Id used for unregister
	 *
	 * @param exception
	 *            An exception representing the error, in case there was one
	 */
	public void onUnregister(String registrationId, Exception exception);
}


text:
<?php
namespace Idio\MonologHandlers;

use Monolog\Logger;

/**
* Monolog Airbrake Handler
*
* @author Oliver Byford <oliver.byford@idioplatform.com>
* @package Idio::MonologHandlers
*/
class AirbrakeHandler extends \Monolog\Handler\AbstractProcessingHandler
{

    /**
     * @var string Airbrake Token
     */
    protected $strAirbrakeApiToken = false;

    /**
     * @var array Airbrake Configuration
     */
    protected $arrAirbrakeConfig;

    /**
     * @var object Airbrake Client
     */
    protected $objAirbrakeClient = false;

    /**
     * Constructor
     *
     * Stores the Airbrake API token before handing off to the parent constructor
     * to deal with levels and bubbling
     *
     * @param string  $strAirbrakeApiToken Airbrake Project API Token
     * @param integer $level Level above which entries should be logged
     * @param boolean $bubble Whether to bubble to the next handler or not
     */
    public function __construct($token, $config = array(), $level = Logger::ERROR, $bubble = true)
    {
        $this->strAirbrakeApiToken = $token;
        $this->arrAirbrakeConfig = $config;
        parent::__construct($level, $bubble);
    }

    /**
     * @inheritdoc
     */
    protected function write(array $record)
    {
        $this->initialize();

        $this->objAirbrakeClient->notify(
            $this->createAirbrakeNotice(
                array(
                    'errorClass'   => $record['level_name'],
                    'errorMessage' => $this->makeXmlSafe($record['message']),
                    'extraParameters' => array_merge(
                        $record['extra'],
                        array(
                            'context' => $record['context'],
                            'channel' => $record['channel']
                        )
                    ),
                )
            )
        );
    }

    /**
     * Make XML Safe
     *
     * @param string $strMessage Message
     * @return string Message with & replaced with &
     */
    protected function makeXmlSafe($strMessage)
    {
        return str_replace('&', '&', $strMessage);
    }

    /**
     * Initialize
     *
     * Create a Airbrake client object if it doesn't exist already
     */
    protected function initialize()
    {
        if ($this->objAirbrakeClient) {
            return;
        } else {
            $this->objAirbrakeClient = $this->getAirbrakeClient();
        }
    }

    /**
     * Get Airbrake Client
     *
     * @return object Airbrake Client
     */
    protected function getAirbrakeClient()
    {
        return new \Airbrake\Client(
            new \Airbrake\Configuration($this->strAirbrakeApiToken, $this->arrAirbrakeConfig)
        );
    }

    /**
     * Create Airbrake Notice
     *
     * @param array Airbrake notice details (errorClass, errorMessage, extraParameters)
     * @return object Airbrake Notice
     */
    protected function createAirbrakeNotice($arrDetails)
    {
        return new \Airbrake\Notice($arrDetails);
    }
}


text:
package frontendhost

import dconfig "github.com/uber/cherami-server/common/dconfigclient"

func (h *Frontend) registerInt() {
	// Add handler function for the dynamic config value
	handlerMap := make(map[string]dconfig.Handler)

	// nothing to be dynamically configured right now

	h.dClient.AddHandlers(handlerMap)
	// Add verify function for the dynamic config value
	verifierMap := make(map[string]dconfig.Verifier)
	h.dClient.AddVerifiers(verifierMap)
}

// LoadUconfig load the dynamic config values for key
func (h *Frontend) LoadUconfig() {
	// nothing to be loaded dynamically right now
}

// Manage do the work for uconfig
func (h *Frontend) dynamicConfigManage() {
	h.dClient.Refresh()
	h.LoadUconfig()
	h.registerInt()
	h.dClient.StartBackGroundRefresh()
}


text:
// <auto-generated />
using System;
using ArragroCMS.BusinessLayer.Data.EFCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

namespace ArragroCMS.BusinessLayer.Data.EFCore.Migrations.ArragroCms.SQL
{
    [DbContext(typeof(ArragroCmsContext))]
    [Migration("20181005032002_Add-UserAttributes")]
    partial class AddUserAttributes
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "2.1.2-rtm-30932")
                .HasAnnotation("Relational:MaxIdentifierLength", 128)
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.Alias", b =>
                {
                    b.Property<Guid>("AliasId")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid>("CreatedBy");

                    b.Property<DateTime>("CreatedDate");

                    b.Property<string>("Host")
                        .IsRequired()
                        .HasMaxLength(2000);

                    b.Property<Guid>("ModifiedBy");

                    b.Property<DateTime>("ModifiedDate");

                    b.Property<int>("Port");

                    b.Property<Guid>("SiteId");

                    b.HasKey("AliasId");

                    b.HasIndex("SiteId");

                    b.HasIndex("Host", "Port")
                        .IsUnique();

                    b.ToTable("Aliases");
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.Asset", b =>
                {
                    b.Property<Guid>("AssetId")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Alt")
                        .HasMaxLength(128);

                    b.Property<Guid>("ContentUrlRouteId");

                    b.Property<Guid>("CreatedBy");

                    b.Property<DateTime>("CreatedDate");

                    b.Property<string>("FileName")
                        .IsRequired()
                        .HasMaxLength(128);

                    b.Property<int?>("Height");

                    b.Property<bool>("IsFolder");

                    b.Property<bool>("IsImage");

                    b.Property<string>("MimeType")
                        .IsRequired()
                        .HasMaxLength(255);

                    b.Property<Guid>("ModifiedBy");

                    b.Property<DateTime>("ModifiedDate");

                    b.Property<DateTime?>("OriginSyncDate");

                    b.Property<string>("OriginUrl")
                        .HasMaxLength(2000);

                    b.Property<Guid?>("ParentAssetId");

                    b.Property<string>("PhysicalLocationThumbnailUrl")
                        .HasMaxLength(2500);

                    b.Property<string>("PhysicalLocationUrl")
                        .HasMaxLength(2500);

                    b.Property<long>("Size");

                    b.Property<Guid>("UrlRouteId");

                    b.Property<int?>("Width");

                    b.HasKey("AssetId");

                    b.HasIndex("ContentUrlRouteId");

                    b.HasIndex("ParentAssetId");

                    b.HasIndex("UrlRouteId")
                        .IsUnique();

                    b.ToTable("Assets");
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.Content", b =>
                {
                    b.Property<Guid>("ContentId");

                    b.Property<int>("Status");

                    b.Property<string>("Action")
                        .IsRequired()
                        .HasMaxLength(255);

                    b.Property<string>("ConfigurationJson");

                    b.Property<string>("ConfigurationTypeAssemblyQualifiedName")
                        .HasMaxLength(1000);

                    b.Property<string>("ConfigurationTypeTypeFullName")
                        .HasMaxLength(255);

                    b.Property<string>("ContentJson");

                    b.Property<string>("ContentTypeAssemblyQualifiedName")
                        .IsRequired()
                        .HasMaxLength(1000);

                    b.Property<string>("ContentTypeFullName")
                        .IsRequired()
                        .HasMaxLength(255);

                    b.Property<string>("ControllerName")
                        .IsRequired()
                        .HasMaxLength(255);

                    b.Property<Guid>("CreatedBy");

                    b.Property<DateTime>("CreatedDate");

                    b.Property<string>("Description")
                        .HasMaxLength(255);

                    b.Property<string>("Keywords")
                        .HasMaxLength(255);

                    b.Property<string>("Layout")
                        .IsRequired()
                        .HasMaxLength(255);

                    b.Property<Guid>("ModifiedBy");

                    b.Property<DateTime>("ModifiedDate");

                    b.Property<string>("NavigationTitle")
                        .HasMaxLength(128);

                    b.Property<int>("Orientation");

                    b.Property<string>("RedirectUrl")
                        .HasMaxLength(2000);

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasMaxLength(128);

                    b.Property<Guid>("UrlRouteId");

                    b.HasKey("ContentId", "Status");

                    b.HasIndex("UrlRouteId");

                    b.ToTable("Contents");
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.Setting", b =>
                {
                    b.Property<int>("SettingId")
                        .ValueGeneratedOnAdd()
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<Guid>("CreatedBy");

                    b.Property<DateTime>("CreatedDate");

                    b.Property<Guid>("ModifiedBy");

                    b.Property<DateTime>("ModifiedDate");

                    b.Property<string>("Name");

                    b.Property<string>("Value");

                    b.HasKey("SettingId");

                    b.HasIndex("Name")
                        .IsUnique()
                        .HasFilter("[Name] IS NOT NULL");

                    b.ToTable("Settings");
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.Site", b =>
                {
                    b.Property<Guid>("SiteId")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("CdnUrl")
                        .HasMaxLength(2000);

                    b.Property<Guid>("CreatedBy");

                    b.Property<DateTime>("CreatedDate");

                    b.Property<bool>("Enabled");

                    b.Property<string>("Layout")
                        .IsRequired()
                        .HasMaxLength(255);

                    b.Property<Guid>("ModifiedBy");

                    b.Property<DateTime>("ModifiedDate");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasMaxLength(255);

                    b.Property<string>("Url")
                        .HasMaxLength(2000);

                    b.HasKey("SiteId");

                    b.HasIndex("Name")
                        .IsUnique();

                    b.ToTable("Sites");
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.SupportedCulture", b =>
                {
                    b.Property<int>("SupportedCultureId")
                        .ValueGeneratedOnAdd()
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<Guid>("CreatedBy");

                    b.Property<DateTime>("CreatedDate");

                    b.Property<string>("CultureName");

                    b.Property<bool>("Default");

                    b.Property<Guid>("ModifiedBy");

                    b.Property<DateTime>("ModifiedDate");

                    b.HasKey("SupportedCultureId");

                    b.ToTable("SupportedCultures");
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.Tag", b =>
                {
                    b.Property<Guid>("TagId")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasMaxLength(255);

                    b.Property<Guid>("SiteId");

                    b.HasKey("TagId");

                    b.HasIndex("SiteId", "Name")
                        .IsUnique();

                    b.ToTable("Tags");
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.TagUrlRoute", b =>
                {
                    b.Property<Guid>("TagId");

                    b.Property<Guid>("UrlRouteId");

                    b.HasKey("TagId", "UrlRouteId");

                    b.HasIndex("UrlRouteId");

                    b.ToTable("TagUrlRoute");
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.UrlRoute", b =>
                {
                    b.Property<Guid>("UrlRouteId")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid>("CreatedBy");

                    b.Property<DateTime>("CreatedDate");

                    b.Property<string>("DraftUrl")
                        .IsRequired()
                        .HasMaxLength(2000);

                    b.Property<Guid>("ModifiedBy");

                    b.Property<DateTime>("ModifiedDate");

                    b.Property<Guid>("SiteId");

                    b.Property<string>("Url")
                        .IsRequired()
                        .HasMaxLength(2000);

                    b.Property<int>("UrlRouteTypeId");

                    b.HasKey("UrlRouteId");

                    b.HasIndex("UrlRouteTypeId");

                    b.HasIndex("SiteId", "Url")
                        .IsUnique();

                    b.HasIndex("Url", "UrlRouteTypeId");

                    b.ToTable("UrlRoutes");
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.UrlRouteType", b =>
                {
                    b.Property<int>("UrlRouteTypeId")
                        .ValueGeneratedOnAdd()
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasMaxLength(100);

                    b.Property<int>("UrlRouteTypes");

                    b.HasKey("UrlRouteTypeId");

                    b.HasIndex("Name")
                        .IsUnique();

                    b.ToTable("UrlRouteTypes");

                    b.HasData(
                        new { UrlRouteTypeId = 1, Name = "Asset", UrlRouteTypes = 0 },
                        new { UrlRouteTypeId = 2, Name = "Content", UrlRouteTypes = 1 }
                    );
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.UserAttribute", b =>
                {
                    b.Property<Guid>("UserId")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid?>("WorkingSiteId");

                    b.HasKey("UserId");

                    b.ToTable("UserAttributes");
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.Alias", b =>
                {
                    b.HasOne("ArragroCMS.BusinessLayer.Data.Entities.Site", "Site")
                        .WithMany("Aliases")
                        .HasForeignKey("SiteId")
                        .OnDelete(DeleteBehavior.Restrict);
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.Asset", b =>
                {
                    b.HasOne("ArragroCMS.BusinessLayer.Data.Entities.UrlRoute", "ContentUrlRoute")
                        .WithMany("Assets")
                        .HasForeignKey("ContentUrlRouteId")
                        .OnDelete(DeleteBehavior.Restrict);

                    b.HasOne("ArragroCMS.BusinessLayer.Data.Entities.UrlRoute", "UrlRoute")
                        .WithOne("Asset")
                        .HasForeignKey("ArragroCMS.BusinessLayer.Data.Entities.Asset", "UrlRouteId")
                        .OnDelete(DeleteBehavior.Restrict);
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.Content", b =>
                {
                    b.HasOne("ArragroCMS.BusinessLayer.Data.Entities.UrlRoute", "UrlRoute")
                        .WithMany("Contents")
                        .HasForeignKey("UrlRouteId")
                        .OnDelete(DeleteBehavior.Restrict);
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.TagUrlRoute", b =>
                {
                    b.HasOne("ArragroCMS.BusinessLayer.Data.Entities.Tag", "Tag")
                        .WithMany("TagUrlRoutes")
                        .HasForeignKey("TagId")
                        .OnDelete(DeleteBehavior.Restrict);

                    b.HasOne("ArragroCMS.BusinessLayer.Data.Entities.UrlRoute", "UrlRoute")
                        .WithMany("TagUrlRoutes")
                        .HasForeignKey("UrlRouteId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("ArragroCMS.BusinessLayer.Data.Entities.UrlRoute", b =>
                {
                    b.HasOne("ArragroCMS.BusinessLayer.Data.Entities.Site", "Site")
                        .WithMany("UrlRoutes")
                        .HasForeignKey("SiteId")
                        .OnDelete(DeleteBehavior.Restrict);

                    b.HasOne("ArragroCMS.BusinessLayer.Data.Entities.UrlRouteType", "UrlRouteType")
                        .WithMany()
                        .HasForeignKey("UrlRouteTypeId")
                        .OnDelete(DeleteBehavior.Restrict);
                });
#pragma warning restore 612, 618
        }
    }
}


text:
#ifndef SHOWRUNNER_H
#define SHOWRUNNER_H

#include <QObject>
#include <QMutex>
#include <QMap>

class Function;
class Track;
class Show;
class Doc;

/** @addtogroup engine Engine
 * @{
 */

class ShowRunner : public QObject
{
    Q_OBJECT

public:
    ShowRunner(const Doc* doc, quint32 showID, quint32 startTime = 0);
    ~ShowRunner();

    /** Start the runner */
    void start();

    /** Stop the runner */
    void stop();

    void write();

private:
    const Doc* m_doc;

    /** The reference of the show to play */
    Show* m_show;

    /** The list of Functions of the show to play */
    QList <Function *> m_functions;

    /** List of duration of each function */
    QList <quint32> m_durations;

    /** Elapsed time since runner start. Used also to move the cursor in MultiTrackView */
    quint32 m_elapsedTime;

    /** Total time the runner has to run */
    quint32 m_totalRunTime;

    /** List of running Functions and its mutex */
    QList <Function *> m_runningQueue;
    QMutex m_runningQueueMutex;

    /** Current step being played */
    int m_currentFunctionIndex;

private slots:
    void slotSequenceStopped(quint32);

signals:
    void timeChanged(quint32 time);
    void showFinished();

    /************************************************************************
     * Intensity
     ************************************************************************/
public:
    /**
     * Adjust the intensity of show track
     */
    void adjustIntensity(qreal fraction, Track *track);

private:
    QMap<quint32, qreal> m_intensityMap;

};

/** @} */

#endif


text:
class Rafters::Component
  attr_accessor :identifier, :local_options, :local_settings
  attr_writer :controller

  def initialize(identifier, options = {})
    settings = options.delete(:settings) || {}

    @identifier = identifier
    @local_options = options
    @local_settings = settings
  end

  def options
    @options ||= objectify_with_merge_chain(klass_options, local_options, param_options)
  end

  def settings
    @settings ||= objectify_with_merge_chain(klass_settings, local_settings, param_settings).tap do |_settings|
      klass_setting_options.each do |setting, options|
        raise SettingRequired, "#{setting} is required" if options[:required] && _settings[setting].nil?
      end
    end
  end

  def unsuppressed_settings
    settings_to_suppress = klass_setting_options.select { |setting, options| !!options[:suppress] }.keys
    settings.except(*settings_to_suppress)
  end

  def attributes
    @attributes ||= objectify.tap do |_attributes|
      klass_attributes.each do |attribute|
        _attributes[attribute] = send(attribute)
      end
    end
  end

  def source
    @source ||= if options.source_name
      source_klass = sources[options.source_name.to_s]
      raise UnknownSource, "#{options.source_name} has not be registered" if source_klass.nil?
      source_klass.is_a?(String) ? source_klass.constantize.new(self) : source_klass.new(self)
    end
  end

  def view
    @view ||= objectify((views[options.view_name] || {}).reverse_merge({ name: options.view_name }))
  end

  def locals
    attributes.merge(settings: settings, component: self)
  end

  def rescue_from_options
    self.class._rescue_from_options
  end

  def as_json(*args)
    { identifier: identifier, options: options.as_json(*args), settings: unsuppressed_settings.as_json(*args) }.as_json
  end

  def controller(variable_or_method_name, *args)
    if @controller.instance_variable_defined?("@#{variable_or_method_name}")
      @controller.instance_variable_get("@#{variable_or_method_name}")
    elsif @controller.respond_to?(variable_or_method_name, true)
      @controller.send(variable_or_method_name, *args)
    else
      nil
    end
  end

  def params
    controller(:params) || {}
  end

  def execute_callbacks!(type)
    send(type).each do |callback|
      send(callback)
    end
  end

  class << self
    attr_accessor :_attributes, :_settings, :_setting_options, :_options, :_before_render_callbacks, :_after_render_callbacks, :_sources, :_views, :_rescue_from_options

    def inherited(base)
      base.option(:wrapper, true)
      base.option(:view_name, base.name.underscore)
      base.option(:source_name, nil)
    end

    def before_render(method_name)
      (self._before_render_callbacks ||= []) << method_name
    end

    def after_render(method_name)
      (self._after_render_callbacks ||= []) << method_name
    end

    def setting(name, options = {})
      options = options || {}

      (self._settings ||= {})[name] = options.delete(:default)
      (self._setting_options ||= {})[name] = options
    end

    def attribute(name)
      (self._attributes ||= []) << name
    end

    def option(name, value)
      (self._options ||= {})[name] = value
    end

    def settings(settings = {})
      settings.each { |name, options| setting(name, options) }
    end

    def attributes(*names)
      names.each { |name| attribute(name) }
    end

    def options(options = {})
      options.each { |name, value| option(name, value) }
    end

    def register_source(name, klass)
      (self._sources ||= {})[name.to_s] = klass
    end

    def register_view(name, options = {})
      (self._views ||= {})[name.to_s] = options
    end

    def rescue_from(exception, &block)
      self._rescue_from_options = { exception: exception, block: block }
    end
  end

  private

  def before_render_callbacks
    self.class._before_render_callbacks || []
  end

  def after_render_callbacks
    self.class._after_render_callbacks || []
  end

  def klass_attributes
    self.class._attributes || []
  end

  def klass_options
    self.class._options || {}
  end

  def klass_settings
    self.class._settings || {}
  end

  def klass_setting_options
    self.class._setting_options || {}
  end

  def param_options
    params[identifier] || {}
  end

  def param_settings
    param_options[:settings] || {}
  end

  def sources
    self.class._sources || {}
  end

  def views
    self.class._views || {}
  end

  def merge_chain(*links)
    {}.tap do |chain|
      links.each do |link|
        chain.merge!(link)
      end
    end
  end

  def objectify(hash = {})
    Hashie::Mash.new(hash)
  end

  def objectify_with_merge_chain(*links)
    objectify.tap do |object|
      merge_chain(*links).each do |option, value|
        object[option] = coerce_value(value)
      end
    end
  end

  def coerce_value(value)
    if value == "true"
      return true
    elsif value == "false"
      return false
    elsif value == "nil"
      return nil
    elsif value.is_a?(Proc)
      value.call(self)
    else
      return value
    end
  end

  class SettingRequired < StandardError; end
  class UnknownSource < StandardError; end
end


text:
`<router-link>` ist eine Komponente zum Aktivieren von Nutzernavigationen in Router-aktivierten Apps. Der Zielort ist mit dem `to`-Prop angegeben. Es wird als `<a>` und standardmäßig mit korrektem `href` gerendert, kann jedoch mit dem `tag`-Prop konfiguriert werden. Darüberhinaus erhält der Link automatisch die aktive CSS-Klasse, wenn die Ziel-Route aktiv ist.

`<router-link>` wird gegenüber fest eingebautem `<a href="">` aus folgenden Gründen bevorzugt:

- Es funktioniert im HTML5-Verlaufsmodus wie auch im Hash-Modus. Demnach ändert sich nichts, wenn der Modus jemals gewechselt wird oder in den Hash-Modus für IE9 zurückfällt.

- Im HTML5-Verlaufsmodus fängt `router-link` das Klick-Event ab, sodass der Browser nicht versucht das Fenster neuzuladen.

- Wenn die `base`-Option im HTML5-Verlaufsmodus genutzt wird, ist keine Angabe der URL des Props in `to` nötig.

### Props

- **to**

  - Typ: `string | Location`

  - notwendig

  Kennzeichnet die Ziel-Route des Links. Wenn geklickt, wird der Wert von `to` und `router.push()` intern übergeben, sodass der Wert entweder ein String oder ein Objekt der Ortsbeschreibung sein kann.

  ``` html
  <!-- literaler String -->
  <router-link to="home">Home</router-link>
  <!-- gerendert zu -->
  <a href="home">Home</a>

  <!-- JavaScript-Expression mit v-bind -->
  <router-link v-bind:to="'home'">Home</router-link>

  <!-- Auslassen von v-bind ist okay wie bei jedem anderen Prop -->
  <router-link :to="'home'">Home</router-link>

  <!-- gleich wie oben -->
  <router-link :to="{ path: 'home' }">Home</router-link>

  <!-- benannte Route -->
  <router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

  <!-- mit Abfrage, resultiert in /register?plan=private -->
  <router-link :to="{ path: 'register', query: { plan: 'private' }}">Register</router-link>
  ```

- **replace**

  - Typ: `boolean`

  - Default: `false`

  Die Nutzung vom `replace`-Prop aktiviert `router.replace()` anstelle von `router.push()`, wenn geklickt. Die Navigation hinterlässt einen Verlaufseintrag.

  ``` html
  <router-link :to="{ path: '/abc'}" replace></router-link>
  ```

- **append**

  - Typ: `boolean`

  - Default: `false`

  Die Nutzung vom `append`-Prop hängt immer den relativen Pfad an den aktuellen an. Angenommen man navigiert von `/a` zu einem relativen Pfad `b` - ohne `append` ended man bei `/b`, mit `append` jedoch wird daraus `/a/b`.

  ``` html
  <router-link :to="{ path: 'relative/path'}" append></router-link>
  ```

- **tag**

  - Typ: `string`

  - Default: `"a"`

  Manchmal ist gewollt, dass `<router-link>` einen anderen Tag rendert, zB. `<li>`. Durch Nutzung des `tag`-Props kann man einen speziellen Tag zum Rendern definieren, welcher nach wie vor auf Klick-Events für die Navigation reagiert.

  ``` html
  <router-link to="/foo" tag="li">foo</router-link>
  <!-- gerendert als -->
  <li>foo</li>
  ```

- **active-class**

  - Typ: `string`

  - Default: `"router-link-active"`

  Konfiguration der aktiven CSS-Klasse für den aktiven Link.
  Der Standardwert kann ebenfalls mit der `linkActiveClass`-Option des Router-Konstruktors global konfiguriert werden.

- **exact**

  - Typ: `boolean`

  - Default: `false`

  Das standardmäßige Abstimmungsverfahren der aktiven Klasse ist **eingeschlossene Abstimmung**. Zum Beispiel erhält `<router-link to="/a">` die Klasse, solange der aktuelle Pfad mit `/a` beginnt.

  Die Konsequenz davon ist, dass `<router-link to=/>` für jede Route aktiv ist. Um den Link in exakten Abstimmungsmodus zu zwingen, wird der `exact`-Prop genutzt:

  ``` html
  <!-- dieser Link wird nur bei '/' aktiv -->
  <router-link to="/" exact>
  ```

  Siehe weitere Beispiele zur aktiven Linkklasse [hier](http://jsfiddle.net/fnlCtrl/dokbyypq/).

- **events**

  > 2.1.0+

  - Typ: `string | Array<string>`

  - Default: `'click'`

  Lege das Evens fest, welche die Linknavigation auslöst.

### Angabe der aktiven Klasse bei äußeren Elementen

Manchmal ist gewollt, dass die aktive Klasse an ein äußeres Element anstatt an das `<a>` gesetzt wird. In diesem Fall kann man das äußere Element als `<router-link>` rendern und damit den rohen `<a>`-Tag umschließen:

``` html
<router-link tag="li" to="/foo">
  <a>/foo</a>
</router-link>
```

In diesem Fall ist `<a>` der eigentliche Link und erhält den korrekten `href`, aber die aktive Klasse wird auf das äußere `li` gesetzt.


text:
#!/usr/bin/env node

const chalk = require('chalk');
const fs = require('fs');
const glob = require('glob');
const path = require('path');
const metadataUtils = require('./server/metadataUtils.js');

const CWD = process.cwd();

// escape appropriate characters in a string to be used in a regex
RegExp.escape = function(s) {
  return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

// generate a doc header from metadata
function makeHeader(metadata) {
  let header = '---\n';
  Object.keys(metadata).forEach(key => {
    header += key + ': ' + metadata[key] + '\n';
  });
  header += '---\n';
  return header;
}

let currentVersion, newVersion;

const program = require('commander');

program
  .arguments('<version_name> <new_version_name>')
  .action((ver1, ver2) => {
    currentVersion = ver1;
    newVersion = ver2;
  })
  .parse(process.argv);

// require user to input two command line arguments, current version to be
// renamed, and new version name
if (
  typeof currentVersion === 'undefined' ||
  typeof newVersion === 'undefined'
) {
  console.error(
    `${chalk.yellow(
      'Version numbers are not properly specified!'
    )}\nSpecify as command line arguments: the current version you wish to rename, then the version number you want to rename it to. `
  );
  process.exit(1);
}

// error if no versions currently exist
if (!fs.existsSync(CWD + '/versions.json')) {
  console.error(
    `${chalk.yellow(
      'No versions found!'
    )}\nNo versions.json file currently exists. Use the \`versions\` script if you wish to create new versions.`
  );
  process.exit(1);
}

const versions = JSON.parse(fs.readFileSync(CWD + '/versions.json', 'utf8'));

const versionIndex = versions.indexOf(currentVersion);
// error if current specified version does not exist
if (versionIndex < 0) {
  console.error(
    `${chalk.yellow(
      'Version ' + currentVersion + ' does not currently exist!'
    )}\n Version ${currentVersion} is not in the versions.json file. You can only rename existing versions.`
  );
  process.exit(1);
}
// replace old version with new version in versions.json file
versions[versionIndex] = newVersion;
fs.writeFileSync(
  CWD + '/versions.json',
  JSON.stringify(versions, null, 2) + '\n'
);

// if folder of docs for this version exists, rename folder and rewrite doc
// headers to use new version
if (fs.existsSync(CWD + '/versioned_docs/version-' + currentVersion)) {
  fs.renameSync(
    CWD + '/versioned_docs/version-' + currentVersion,
    CWD + '/versioned_docs/version-' + newVersion
  );

  const files = glob.sync(CWD + '/versioned_docs/version-' + newVersion + '/*');
  files.forEach(file => {
    const extension = path.extname(file);
    if (extension !== '.md' && extension !== '.markdown') {
      return;
    }
    const res = metadataUtils.extractMetadata(fs.readFileSync(file, 'utf8'));
    const metadata = res.metadata;
    const rawContent = res.rawContent;
    if (!metadata.id) {
      return;
    }
    metadata.id = metadata.id.replace(
      `version-${currentVersion}-`,
      `version-${newVersion}-`
    );
    fs.writeFileSync(file, makeHeader(metadata) + rawContent);
  });
}

// if sidebar file exists for this version, rename sidebar file and rewrite
// doc ids in the file
let currentSidebarFile =
  CWD + '/versioned_sidebars/version-' + currentVersion + '-sidebars.json';
let newSidebarFile =
  CWD + '/versioned_sidebars/version-' + newVersion + '-sidebars.json';
if (fs.existsSync(currentSidebarFile)) {
  fs.renameSync(currentSidebarFile, newSidebarFile);
  let sidebarContent = fs.readFileSync(newSidebarFile, 'utf8');
  sidebarContent = sidebarContent.replace(
    new RegExp(`version-${RegExp.escape(currentVersion)}-`, 'g'),
    `version-${newVersion}-`
  );
  fs.writeFileSync(newSidebarFile, sidebarContent);
}

console.log(
  `${chalk.green('Successfully renamed version ')}${chalk.yellow(
    currentVersion
  )}${chalk.green(' to version ')}${chalk.yellow(newVersion)}\n`
);


text:
package v1beta1

import (
	"testing"

	"knative.dev/operator/pkg/apis/operator"

	"k8s.io/apimachinery/pkg/runtime/schema"
	"knative.dev/operator/pkg/apis/operator/base"
	apistest "knative.dev/pkg/apis/testing"
)

func TestKnativeServingGroupVersionKind(t *testing.T) {
	r := &KnativeServing{}
	want := schema.GroupVersionKind{
		Group:   operator.GroupName,
		Version: SchemaVersion,
		Kind:    operator.KindKnativeServing,
	}
	if got := r.GroupVersionKind(); got != want {
		t.Errorf("got: %v, want: %v", got, want)
	}
}

func TestKnativeServingHappyPath(t *testing.T) {
	ks := &KnativeServingStatus{}
	ks.InitializeConditions()

	apistest.CheckConditionOngoing(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionOngoing(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionOngoing(ks, base.InstallSucceeded, t)

	ks.MarkVersionMigrationEligible()

	// Install succeeds.
	ks.MarkInstallSucceeded()
	// Dependencies are assumed successful too.
	apistest.CheckConditionSucceeded(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionOngoing(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionSucceeded(ks, base.InstallSucceeded, t)

	// Deployments are not available at first.
	ks.MarkDeploymentsNotReady([]string{"test"})
	apistest.CheckConditionSucceeded(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionFailed(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionSucceeded(ks, base.InstallSucceeded, t)
	if ready := ks.IsReady(); ready {
		t.Errorf("ks.IsReady() = %v, want false", ready)
	}

	// Deployments become ready and we're good.
	ks.MarkDeploymentsAvailable()
	apistest.CheckConditionSucceeded(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionSucceeded(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionSucceeded(ks, base.InstallSucceeded, t)
	if ready := ks.IsReady(); !ready {
		t.Errorf("ks.IsReady() = %v, want true", ready)
	}
}

func TestKnativeServingErrorPath(t *testing.T) {
	ks := &KnativeServingStatus{}
	ks.InitializeConditions()

	apistest.CheckConditionOngoing(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionOngoing(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionOngoing(ks, base.InstallSucceeded, t)

	ks.MarkVersionMigrationEligible()

	// Install fails.
	ks.MarkInstallFailed("test")
	apistest.CheckConditionOngoing(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionOngoing(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionFailed(ks, base.InstallSucceeded, t)

	// Dependencies are installing.
	ks.MarkDependencyInstalling("testing")
	apistest.CheckConditionFailed(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionOngoing(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionFailed(ks, base.InstallSucceeded, t)

	// Install now succeeds.
	ks.MarkInstallSucceeded()
	apistest.CheckConditionFailed(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionOngoing(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionSucceeded(ks, base.InstallSucceeded, t)
	if ready := ks.IsReady(); ready {
		t.Errorf("ks.IsReady() = %v, want false", ready)
	}

	// Deployments become ready
	ks.MarkDeploymentsAvailable()
	apistest.CheckConditionFailed(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionSucceeded(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionSucceeded(ks, base.InstallSucceeded, t)
	if ready := ks.IsReady(); ready {
		t.Errorf("ks.IsReady() = %v, want false", ready)
	}

	// Finally, dependencies become available.
	ks.MarkDependenciesInstalled()
	apistest.CheckConditionSucceeded(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionSucceeded(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionSucceeded(ks, base.InstallSucceeded, t)
	if ready := ks.IsReady(); !ready {
		t.Errorf("ks.IsReady() = %v, want true", ready)
	}
}

func TestKnativeServingExternalDependency(t *testing.T) {
	ks := &KnativeServingStatus{}
	ks.InitializeConditions()

	// External marks dependency as failed.
	ks.MarkDependencyMissing("test")

	// Install succeeds.
	ks.MarkInstallSucceeded()
	apistest.CheckConditionFailed(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionOngoing(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionSucceeded(ks, base.InstallSucceeded, t)

	// Dependencies are now ready.
	ks.MarkDependenciesInstalled()
	apistest.CheckConditionSucceeded(ks, base.DependenciesInstalled, t)
	apistest.CheckConditionOngoing(ks, base.DeploymentsAvailable, t)
	apistest.CheckConditionSucceeded(ks, base.InstallSucceeded, t)
}

func TestKnativeServingVersionMigrationNotEligible(t *testing.T) {
	ks := &KnativeServingStatus{}
	ks.InitializeConditions()

	ks.MarkVersionMigrationNotEligible("Version migration not eligible.")
	apistest.CheckConditionFailed(ks, base.VersionMigrationEligible, t)
}


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Duracellko.PlanningPoker.Data;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace Duracellko.PlanningPoker.Health
{
    /// <summary>
    /// The object provides health status of <see cref="Data.IScrumTeamRepository"/> object.
    /// </summary>
    public class ScrumTeamRepositoryHealthCheck : IHealthCheck
    {
        private readonly IScrumTeamRepository _scrumTeamRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="ScrumTeamRepositoryHealthCheck"/> class.
        /// </summary>
        /// <param name="scrumTeamRepository">The Scrum Team repository to provide health check for.</param>
        public ScrumTeamRepositoryHealthCheck(IScrumTeamRepository scrumTeamRepository)
        {
            _scrumTeamRepository = scrumTeamRepository ?? throw new ArgumentNullException(nameof(scrumTeamRepository));
        }

        /// <summary>
        /// Runs the health check, returning the status of the Scrum Team repository.
        /// </summary>
        /// <param name="context">A context object associated with the current execution.</param>
        /// <param name="cancellationToken">A <see cref="System.Threading.CancellationToken"/> that can be used to cancel the health check.</param>
        /// <returns>The health status of the Scrum Team repository.</returns>
        [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "All errors are reported as unhealthy status.")]
        public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                var count = _scrumTeamRepository.ScrumTeamNames.Count();
                return Task.FromResult(HealthCheckResult.Healthy($"Repository has {count} teams."));
            }
            catch (Exception ex)
            {
                return Task.FromResult(HealthCheckResult.Unhealthy("Repository is unhealthy.", ex));
            }
        }
    }
}


text:
package ro.pub.cs.systems.pdsd.practicaltest01var04;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class PracticalTest01Var04SecondaryActivity extends Activity {

	private static final String NOTES = "Do, Mi, Sol, Do\'";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_practical_test01_var04_secondary);

		Intent intent = getIntent();
		String notes = intent.getStringExtra("notes");
		if (notes.equals(NOTES)) {
		     setResult(0, new Intent());
		     finish();
		} else  {
		     setResult(-1, new Intent());
	         finish();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater()
				.inflate(R.menu.practical_test01_var04_secondary, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}


text:
namespace Online_Radio_Database
{
    public class InvalidArtistNameException:InvalidSongException
    {
        public override string Message => "Artist name should be between 3 and 20 symbols.";
    }
}


text:
var v1: (i: number, ...arguments) => void; // no error - no code gen
var v12: (arguments: number, ...restParameters) => void; // no error - no code gen
var v2: {
    (arguments: number, ...restParameters); // no error - no code gen
    new (arguments: number, ...restParameters); // no error - no code gen
    foo(arguments: number, ...restParameters); // no error - no code gen
    prop: (arguments: number, ...restParameters) => void; // no error - no code gen
}
var v21: {
    (i: number, ...arguments); // no error - no code gen
    new (i: number, ...arguments); // no error - no code gen
    foo(i: number, ...arguments); // no error - no code gen
    prop: (i: number, ...arguments) => void; // no error - no code gen
}