text:
#pragma once
#include <aws/wafv2/WAFV2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace WAFV2
{
namespace Model
{

  /**
   *
High level information for an SDK release.

See Also:
   AWS
   * API Reference

   */
  class AWS_WAFV2_API ReleaseSummary
  {
  public:
    ReleaseSummary();
    ReleaseSummary(Aws::Utils::Json::JsonView jsonValue);
    ReleaseSummary& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The release version.

     */
    inline const Aws::String& GetReleaseVersion() const{ return m_releaseVersion; }

    /**
     *
The release version.

     */
    inline bool ReleaseVersionHasBeenSet() const { return m_releaseVersionHasBeenSet; }

    /**
     *
The release version.

     */
    inline void SetReleaseVersion(const Aws::String& value) { m_releaseVersionHasBeenSet = true; m_releaseVersion = value; }

    /**
     *
The release version.

     */
    inline void SetReleaseVersion(Aws::String&& value) { m_releaseVersionHasBeenSet = true; m_releaseVersion = std::move(value); }

    /**
     *
The release version.

     */
    inline void SetReleaseVersion(const char* value) { m_releaseVersionHasBeenSet = true; m_releaseVersion.assign(value); }

    /**
     *
The release version.

     */
    inline ReleaseSummary& WithReleaseVersion(const Aws::String& value) { SetReleaseVersion(value); return *this;}

    /**
     *
The release version.

     */
    inline ReleaseSummary& WithReleaseVersion(Aws::String&& value) { SetReleaseVersion(std::move(value)); return *this;}

    /**
     *
The release version.

     */
    inline ReleaseSummary& WithReleaseVersion(const char* value) { SetReleaseVersion(value); return *this;}

    /**
     *
The timestamp of the release.

     */
    inline const Aws::Utils::DateTime& GetTimestamp() const{ return m_timestamp; }

    /**
     *
The timestamp of the release.

     */
    inline bool TimestampHasBeenSet() const { return m_timestampHasBeenSet; }

    /**
     *
The timestamp of the release.

     */
    inline void SetTimestamp(const Aws::Utils::DateTime& value) { m_timestampHasBeenSet = true; m_timestamp = value; }

    /**
     *
The timestamp of the release.

     */
    inline void SetTimestamp(Aws::Utils::DateTime&& value) { m_timestampHasBeenSet = true; m_timestamp = std::move(value); }

    /**
     *
The timestamp of the release.

     */
    inline ReleaseSummary& WithTimestamp(const Aws::Utils::DateTime& value) { SetTimestamp(value); return *this;}

    /**
     *
The timestamp of the release.

     */
    inline ReleaseSummary& WithTimestamp(Aws::Utils::DateTime&& value) { SetTimestamp(std::move(value)); return *this;}

  private:

    Aws::String m_releaseVersion;
    bool m_releaseVersionHasBeenSet;

    Aws::Utils::DateTime m_timestamp;
    bool m_timestampHasBeenSet;
  };

} // namespace Model
} // namespace WAFV2
} // namespace Aws


text:
/**
 */
package pcmarchoptions;

import archoptions.BanComponent;
import org.eclipse.emf.common.util.EList;

/**
 *
 * A representation of the model object 'PCM Ban Component'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link pcmarchoptions.PCM_BanComponent#getBannedContextNames Banned Context Names}

 *

 *
 * @see pcmarchoptions.PcmarchoptionsPackage#getPCM_BanComponent()
 * @model
 * @generated
 */
public interface PCM_BanComponent extends BanComponent {
	/**
	 * Returns the value of the 'Banned Context Names' attribute list.
	 * The list contents are of type {@link java.lang.String}.
	 *
	 *

	 * If the meaning of the 'Banned Context Names' attribute list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Banned Context Names' attribute list.
	 * @see pcmarchoptions.PcmarchoptionsPackage#getPCM_BanComponent_BannedContextNames()
	 * @model required="true"
	 * @generated
	 */
	EList<String> getBannedContextNames();

} // PCM_BanComponent

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">

    <title>My Style Guide Base CSS</title>

    <link rel="stylesheet" href="static/css/doc.css">
    <link rel="stylesheet" href="static/css/github.css">

    <link rel="stylesheet" href="extra/css/screen.css">

My Style Guide

Intro

Base CSS

Background Colors

Buttons

Button Styles

Background Colors

We have a few background colors that can be used in various contexts.
These are not for use as the entire page background but instead for
specific components and modules on the page.

      backgroundLowlight

      backgroundHighlight

      backgroundBasic

      backgroundInverse

Buttons

Button styles can be applied to any element. Typically you'll want to
use either a <button> or an <a> element:

<button class="btn btnDefault">Click</button>
Don't click

<button class="btn btnDefault">Click</button>
<a class="btn btnDefault" href="http://trulia.com">Don't click</a>

If your button is actually a link to another page, please use the
<a> element, while if your button performs an action, such as submitting
a form or triggering some javascript event, then use a <button> element.

Button Sizes

There are three 3 sizes for buttons: Large, medium (default)
and small. Simply apply the size modifier class for the desired size.
There is also an additional modifier that will make the button take the
full width of the container. It may be used with the any of the button
size and style modifiers.

Button
Modifier Class

<button class="btn btnDefault btnLrg">Large</button>
btn btnDefault btnLrg

<button class="btn btnDefault">Default</button>
btn btnDefault

<button class="btn btnDefault btnSml">Small</button>
btn btnDefault btnSml

<button class="btn btnDefault btnFullWidth">Full width</button>
btn btnDefault btnFullWidth

Button Styles

Button
Class
Description

<button class="btn btnDefault">Default</button>
btn btnDefault
This is what buttons look like, this is the go to button style.

<button class="btn btnPrimary">Primary</button>
btn btnPrimary
Use this button as the primary call to action

<button class="btn btnDanger">Delete</button>
btn btnDanger
This button is for delete actions, these actions should also have a confirmation dialog

<button class="btn btnDisabled">Disabled</button>
btn btnDisabled
I'm afraid I can't let you do that, yet.

    The source code for this style guide is licensed under the MIT license.


text:
//
//  UIBezierPath+Annex.h
//  Annex
//
//  Created by Wesley Cope on 4/28/15.
//  Copyright (c) 2015 Wess Cope. All rights reserved.
//

#import <UIKit/UIKit.h>

typedef NS_OPTIONS(NSUInteger, AnnexBezierPathArrowDirection) {
    AnnexBezierPathArrowDirectionNone   = 0,
    AnnexBezierPathArrowDirectionUp     = 1 << 0,
    AnnexBezierPathArrowDirectionRight  = 1 << 1,
    AnnexBezierPathArrowDirectionDown   = 1 << 2,
    AnnexBezierPathArrowDirectionLeft   = 1 << 3
};

@interface UIBezierPath (Annex)
/**
 Creates a BezierPath in the shap of an arrow in the provided direction.

 @param rect        Frame to draw arrow in.
 @param scale       Arrow scaling size.
 @param direction   Direction to draw the arrow in.
 @return            UIBezierPath for created arrow.
 */
+ (UIBezierPath *)pathForArrowSymbolInRect:(CGRect)rect scale:(CGFloat)scale direction:(AnnexBezierPathArrowDirection)direction;
@end


text:
#include <string>

#include "gmock/gmock.h"

#include "smart_objects/smart_object.h"
#include "smart_objects/always_true_schema_item.h"

namespace test {
namespace components {
namespace smart_object_test {

using namespace NsSmartDeviceLink::NsSmartObjects;

/**
 * Test AlwaysTrueSchemaItem
 **/
TEST(test_AlwaysTrueSchemaItemTest, simple_test) {
  SmartObject obj;

  ISchemaItemPtr item = CAlwaysTrueSchemaItem::create();

  obj = 5;
  rpc::ValidationReport report("RPC");
  int resultType = item->validate(obj, &report);
  EXPECT_EQ(Errors::OK, resultType);
  EXPECT_EQ(5, obj.asInt());

  obj = true;
  resultType = item->validate(obj, &report);
  EXPECT_EQ(Errors::OK, resultType);
  EXPECT_TRUE(obj.asBool());

  obj = "Test";
  resultType = item->validate(obj, &report);
  EXPECT_EQ(Errors::OK, resultType);
  EXPECT_EQ(std::string("Test"), obj.asString());

  obj["First"] = "Some string";
  obj["Second"] = 555;
  resultType = item->validate(obj["First"], &report);
  EXPECT_EQ(Errors::OK, resultType);
  resultType = item->validate(obj["Second"], &report);
  EXPECT_EQ(Errors::OK, resultType);
  resultType = item->validate(obj, &report);
  EXPECT_EQ(Errors::OK, resultType);
  EXPECT_EQ(std::string("Some string"), obj["First"].asString());
  EXPECT_EQ(555, obj["Second"].asInt());

  obj[0] = true;
  obj[1] = false;
  resultType = item->validate(obj[0], &report);
  EXPECT_EQ(Errors::OK, resultType);
  resultType = item->validate(obj[1], &report);
  EXPECT_EQ(Errors::OK, resultType);
  resultType = item->validate(obj, &report);
  EXPECT_EQ(Errors::OK, resultType);
  EXPECT_TRUE(obj[0].asBool());
  EXPECT_FALSE(obj[1].asBool());
}

}  // namespace smart_object_test
}  // namespace components
}  // namespace test


text:
/*common look and feel for all user controls that
have a table with 2 colums, left col is the label,
right col is the value*/
.uce
{
    table-layout:auto;
	border-width:1px;
	border-style:solid;
}

.uce_leftcol
{
    font-weight:normal;
	font-size:12px;
	font-family:verdana,arial;
	text-align:right;
    background-color:white;
    color:Black;
}

.uce_rightcol
{
    font-weight:normal;
	font-size:12px;
	font-family:verdana,arial;
	text-align:left;
    background-color:white;
    color:Black;
}

.uce_col_noalg
{
    font-weight:normal;
	font-size:12px;
	font-family:verdana,arial;
    background-color:white;
    color:Black;
}


text:
/* -*- mode: c++; c-basic-offset: 4 indent-tabs-mode: nil -*- */
/*
 * Copyright 2012 Teclo Networks AG
 */

#ifndef _PACKET_H_
#define _PACKET_H_

#include <stdbool.h>
#include <stdint.h>

#include "iface.h"
#include "pkt_in.h"
#include "PacketHeader.pb.h"

enum buffer_owner {
    BUFFER_OWNER_UNKNOWN,
    BUFFER_OWNER_BACKEND,
    BUFFER_OWNER_APPLICATION,
};

// Collection of pointers that make up a TCP packet
class Packet : public PacketHeader {
public:
    Packet() : ethh_(NULL) {
    }

    Packet(const Packet& other);

    ~Packet();

    bool init(uint8_t* frame, size_t length, IoInterface* from_iface);
    void release();

    // Size of packet buffer.
    size_t length_;

    // Interface this packet was received from.
    IoInterface* from_iface_;

    // Ethernet header (coincides with start of packet buffer).
    pkt_eth_t* ethh_;

private:
    bool parse_ipv4(uint8_t* frame, size_t length);
    bool parse_ipv6(uint8_t* frame, size_t length);
    bool parse_tcp(pkt_tcp_t* tcp, size_t length);
};

#endif // PACKET_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LibMinecraft.Model.Blocks
{
    /// <summary>
    /// Leaf Block ID=18
    /// </summary>
    public class LeafBlockBlock:Block
    {
        /// <summary>
        /// The Block ID for this block (18)
        /// </summary>
        /// <remarks></remarks>
        public override byte BlockID
        {
            get { return 18; }
        }
        internal Tree LeafType { get; set; }

        /// <summary>
        /// Leaves are cube solids.
        /// NOTE: Only true if on fancy graphics.
        /// </summary>
        public override BlockOpacity Transparent
        {
            get
            {
                return BlockOpacity.CubeSolid;
            }
        }
    }
}


text:
<?php

namespace Webmozart\Assert\Tests\StaticAnalysis;

use Webmozart\Assert\Assert;

/**
 * @param mixed $value
 * @param mixed $expect
 *
 * @return mixed
 */
function eq($value, $expect)
{
    Assert::eq($value, $expect);

    return $value;
}

/**
 * @param mixed $value
 * @param mixed $expect
 *
 * @return mixed
 */
function nullOrEq($value, $expect)
{
    Assert::nullOrEq($value, $expect);

    return $value;
}

/**
 * @param mixed $value
 * @param mixed $expect
 *
 * @return mixed
 */
function allEq($value, $expect)
{
    Assert::allEq($value, $expect);

    return $value;
}


text:
package in.srain.cube.views.mix;

import android.os.Handler;
import android.os.Looper;

/**
 * A player who can play a @Playable object. It can play next till end and play previous till head.
 *

 * Once it go to the last element, it can play by the reverse order or jump to the first and play again.
 *

 * Between each frame, there is a pause, you can call `setTimeInterval()` to set the time interval you want.
 *
 * @author huqiu.lhq
 */
public class AutoPlayer {

    /**
     * Define how an object can be auto-playable.
     */
    public interface Playable {

        public void playTo(int to);

        public void playNext();

        public void playPrevious();

        public int getTotal();

        public int getCurrent();
    }

    public enum PlayDirection {
        to_left, to_right
    }

    public enum PlayRecycleMode {
        repeat_from_start, play_back
    }

    private PlayDirection mDirection = PlayDirection.to_right;
    private PlayRecycleMode mPlayRecycleMode = PlayRecycleMode.repeat_from_start;
    private int mTimeInterval = 5000;
    private Playable mPlayable;

    private Runnable mTimerTask;

    private boolean mSkipNext = false;
    private int mTotal;
    private boolean mPlaying = false;

    public AutoPlayer(Playable playable) {
        mPlayable = playable;
    }

    public void play() {
        play(0, PlayDirection.to_right);
    }

    public void skipNext() {
        mSkipNext = true;
    }

    public void play(int start, PlayDirection direction) {
        if (mPlaying)
            return;
        mTotal = mPlayable.getTotal();
        if (mTotal <= 1) {
            return;
        }
        mPlaying = true;
        playTo(start);

        final Handler handler = new Handler(Looper.myLooper());
        mTimerTask = new Runnable() {
            @Override
            public void run() {
                playNextFrame();
                if (mPlaying) {
                    handler.postDelayed(mTimerTask, mTimeInterval);
                }
            }
        };
        handler.postDelayed(mTimerTask, mTimeInterval);
    }

    public void play(int start) {
        play(start, PlayDirection.to_right);
    }

    public void stop() {
        if (!mPlaying) {
            return;
        }

        mPlaying = false;
    }

    public AutoPlayer setTimeInterval(int timeInterval) {
        mTimeInterval = timeInterval;
        return this;
    }

    public AutoPlayer setPlayRecycleMode(PlayRecycleMode playRecycleMode) {
        mPlayRecycleMode = playRecycleMode;
        return this;
    }

    private void playNextFrame() {
        if (mSkipNext) {
            mSkipNext = false;
            return;
        }
        int current = mPlayable.getCurrent();
        if (mDirection == PlayDirection.to_right) {
            if (current == mTotal - 1) {
                if (mPlayRecycleMode == PlayRecycleMode.play_back) {
                    mDirection = PlayDirection.to_left;
                    playNextFrame();
                } else {
                    playTo(0);
                }
            } else {
                playNext();
            }
        } else {
            if (current == 0) {
                if (mPlayRecycleMode == PlayRecycleMode.play_back) {
                    mDirection = PlayDirection.to_right;
                    playNextFrame();
                } else {
                    playTo(mTotal - 1);
                }
            } else {
                playPrevious();
            }
        }
    }

    private void playTo(int to) {
        mPlayable.playTo(to);
    }

    private void playNext() {
        mPlayable.playNext();
    }

    private void playPrevious() {
        mPlayable.playPrevious();
    }
}


text:
#include <device.h>
#include <drivers/hwinfo.h>
#include <init.h>
#include <soc.h>
#include <string.h>

static uint8_t sam_uid[16];

ssize_t z_impl_hwinfo_get_device_id(uint8_t *buffer, size_t length)
{
	if (length > sizeof(sam_uid)) {
		length = sizeof(sam_uid);
	}

	memcpy(buffer, sam_uid, length);

	return length;
}

/* On the Atmel SAM SoC series, the device id is located in the flash
 * controller. The controller can either present the flash area containing
 * the code, the unique identifier or the user signature area at the flash
 * location. Therefore the function reading the device id must be executed
 * from RAM with the interrupts disabled. To avoid executing this complex
 * code each time the device id is requested, we do this at boot time at save
 * the 128-bit value into RAM.
 */
__ramfunc static void hwinfo_sam_read_device_id(void)
{
	Efc *efc = (Efc *)DT_REG_ADDR(DT_INST(0, atmel_sam_flash_controller));
	uint8_t *flash = (uint8_t *)CONFIG_FLASH_BASE_ADDRESS;
	int i;

	/* Switch the flash controller to the unique identifier area. The flash
	 * is not available anymore, hence we have to wait for it to be *NOT*
	 * ready.
	 */
	efc->EEFC_FCR = EEFC_FCR_FKEY_PASSWD | EEFC_FCR_FCMD_STUI;
	while ((efc->EEFC_FSR & EEFC_FSR_FRDY) == EEFC_FSR_FRDY) {
		/* Wait */
	}

	/* Copy the 128-bit unique ID. We cannot use memcpy as it would
	 * execute code from flash.
	 */
	for (i = 0; i < sizeof(sam_uid); i++) {
		sam_uid[i] = flash[i];
	}

	/* Switch back the controller to the flash area and wait for it to
	 * be ready.
	 */
	efc->EEFC_FCR = EEFC_FCR_FKEY_PASSWD | EEFC_FCR_FCMD_SPUI;
	while ((efc->EEFC_FSR & EEFC_FSR_FRDY) != EEFC_FSR_FRDY) {
		/* Wait */
	}
}

static int hwinfo_sam_init(const struct device *arg)
{
	Efc *efc = (Efc *)DT_REG_ADDR(DT_INST(0, atmel_sam_flash_controller));
	uint32_t fmr;
	int key;

	/* Disable interrupts. */
	key = irq_lock();

	/* Disable code loop optimization and sequential code optimization. */
	fmr = efc->EEFC_FMR;

#ifndef CONFIG_SOC_SERIES_SAM3X
	efc->EEFC_FMR = (fmr & (~EEFC_FMR_CLOE)) | EEFC_FMR_SCOD;
#else
	/* SAM3x does not have loop optimization (EEFC_FMR_CLOE) */
	efc->EEFC_FMR |= EEFC_FMR_SCOD;
#endif

	/* Read the device ID using code in RAM */
	hwinfo_sam_read_device_id();

	/* Restore code optimization settings. */
	efc->EEFC_FMR = fmr;

	/* Re-enable interrupts */
	irq_unlock(key);

	return 0;
}

SYS_INIT(hwinfo_sam_init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);


text:
title: Workshop Title
layout: workshop
---

# Introduction to REDCap

--------

---------

Please have a REDCap account if you want to follow along.

- **REDCap**: [login here](https://edc.camhx.ca/redcap/)

---------

***Demographics Form***

  -   Record ID
  -   Date of assessment
  -   Initials
  -   DOB
  -   Handedness
  -   Sex
  -   Race
      - White.
      - Black or African American.
      - American Indian or Alaska Native.
      - Asian.
      - Native Hawaiian or Other Pacific Islander.
      - Other, not specified above.
      - Mixed, more than 1 Race.
      - Unknown or Not Reported (participants always have the right to not identify with any category)
  -   Ethnicity
      - Not Hispanic or Latino
      - Hispanic, of Spanish Origin or Latino (e.g. Cuban, Mexican, Puerto Rican, South American)
      - Unknown or Not Reported (participants always have the right to not identify with any category)
  -   Comments

---------

***Example instrument for us to program***

1. On most days, I feel happy
2. My temperament is similar to that of my peers
3. I usually find it hard to get out of bed
4. I often cry for no reason
5. Overall, I lead a good life

---------


text:
package seedu.whatnow.storage;

//@@author A0141021H-reused
import java.io.IOException;
import java.util.Optional;
import seedu.whatnow.commons.core.Config;
import seedu.whatnow.commons.events.model.ConfigChangedEvent;
import seedu.whatnow.commons.events.model.PinnedItemChangedEvent;
import seedu.whatnow.commons.events.model.WhatNowChangedEvent;
import seedu.whatnow.commons.events.storage.DataSavingExceptionEvent;
import seedu.whatnow.commons.exceptions.DataConversionException;
import seedu.whatnow.model.ReadOnlyWhatNow;
import seedu.whatnow.model.UserPrefs;

/**
 * API of the Storage component
 */
public interface Storage extends WhatNowStorage, UserPrefsStorage {

    @Override
    Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOException;

    @Override
    void saveUserPrefs(UserPrefs userPrefs) throws IOException;

    @Override
    String getWhatNowFilePath();

    @Override
    Optional<ReadOnlyWhatNow> readWhatNow() throws DataConversionException, IOException;

    @Override
    void saveWhatNow(ReadOnlyWhatNow whatNow) throws IOException;

    /**
     * Saves the current version of the WhatNow to the hard disk. Creates the
     * data file if it is missing. Raises {@link DataSavingExceptionEvent} if
     * there was an error during saving.
     */
    void handleWhatNowChangedEvent(WhatNowChangedEvent abce);

    void handleFileLocationChangedEvent(ConfigChangedEvent dfgh);

    void saveConfig(Config config) throws IOException;

    void saveConfig(Config config, String filePath) throws IOException;

    void handlePinnedItemChangedEvent(PinnedItemChangedEvent pice);
}


text:
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace hypanel
{
    class HyEngine
    {
        // Hayatで使用するメモリサイズを指定する
        // 指定しなければ、4MiBのメモリを確保する
        [DllImport("hydll.dll")]
        public extern static void  setMemSize(uint memSize);

        // デバッグ用情報をロードするかどうかを設定
        // falseだと、setDebugMemSize()を呼んでもデバッグ用メモリは確保しない。
        // trueだと、シンボル情報、デバッグ情報、SJISエラーメッセージ を読む。
        //     setDebugMemSize()を呼んでいない場合はメインのメモリに読む。
        [DllImport("hydll.dll")]
        public extern static void  setFlagReadDebugInfos(bool flag);

        // Hayatで使用するデバッグ用メモリサイズを指定する
        // 指定しなければ、デバッグ用メモリは確保しない
        [DllImport("hydll.dll")]
        public extern static void  setDebugMemSize(uint MemSize);

        // メモリ初期化
        [DllImport("hydll.dll")]
        public extern static void  init_memory();

        // ロードパスを追加する
        [DllImport("hydll.dll")]
        public extern static void addLoadPath([MarshalAs(UnmanagedType.LPStr)] string path);

        // 基本初期化
        [DllImport("hydll.dll")]
        public extern static void  init_main();

        // 指定バイトコードファイルを読み込んで頭から新規スレッドで実行
        [DllImport("hydll.dll")]
        public extern static bool start_main([MarshalAs(UnmanagedType.LPStr)] string hybFilename);

        // スクリプトを 1tick 実行
        [DllImport("hydll.dll")]
        public extern static bool  tick_main();

        // 終了処理
        [DllImport("hydll.dll")]
        public extern static void  term_main();

        // バイトコードリロード
        [DllImport("hydll.dll")]
        public extern static bool  reload_bytecode([MarshalAs(UnmanagedType.LPStr)] string path, bool bInit);
    }
}


text:
package org.apache.ignite.internal.processors.cache;

import javax.cache.Cache;
import javax.cache.configuration.Factory;
import javax.cache.integration.CacheWriterException;
import javax.cache.processor.MutableEntry;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheEntryProcessor;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.CachePeekMode;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.cache.store.CacheStore;
import org.apache.ignite.cache.store.CacheStoreAdapter;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.lang.IgniteBiInClosure;
import org.apache.ignite.resources.IgniteInstanceResource;
import org.apache.ignite.testframework.MvccFeatureChecker;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Before;
import org.junit.Test;

import static org.apache.ignite.IgniteSystemProperties.IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK;

/**
 * Tests for cache client with and without store.
 */
public class CacheClientStoreSelfTest extends GridCommonAbstractTest {
    /** */
    private static final String CACHE_NAME = "test-cache";

    /** */
    private volatile boolean nearEnabled;

    /** */
    private volatile Factory<CacheStore> factory;

    /** */
    private volatile CacheMode cacheMode;

    /** */
    private static volatile boolean loadedFromClient;

    /** */
    @Before
    public void beforeCacheClientStoreSelfTest() {
        MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.CACHE_STORE);
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        boolean client = igniteInstanceName != null && igniteInstanceName.startsWith("client");
        if (client)
            cfg.setDataStorageConfiguration(new DataStorageConfiguration());

        CacheConfiguration cc = new CacheConfiguration(DEFAULT_CACHE_NAME);

        cc.setName(CACHE_NAME);
        cc.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
        cc.setCacheMode(cacheMode);
        cc.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
        cc.setBackups(1);

        cc.setCacheStoreFactory(factory);

        if (factory instanceof Factory3)
            cc.setReadThrough(true);

        if (client && nearEnabled)
            cc.setNearConfiguration(new NearCacheConfiguration());

        cfg.setCacheConfiguration(cc);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        stopAllGrids();

        loadedFromClient = false;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testCorrectStore() throws Exception {
        nearEnabled = false;
        cacheMode = CacheMode.PARTITIONED;
        factory = new Factory1();

        startGrids(2);

        Ignite ignite = startClientGrid("client-1");

        IgniteCache<Object, Object> cache = ignite.cache(CACHE_NAME);

        cache.get(0);
        cache.getAll(F.asSet(0, 1));
        cache.getAndPut(0, 0);
        cache.getAndPutIfAbsent(0, 0);
        cache.getAndRemove(0);
        cache.getAndReplace(0, 0);
        cache.put(0, 0);
        cache.putAll(F.asMap(0, 0, 1, 1));
        cache.putIfAbsent(0, 0);
        cache.remove(0);
        cache.remove(0, 0);
        cache.removeAll(F.asSet(0, 1));
        cache.removeAll();
        cache.invoke(0, new EP());
        cache.invokeAll(F.asSet(0, 1), new EP());
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testInvalidStore() throws Exception {
        nearEnabled = false;
        cacheMode = CacheMode.PARTITIONED;
        factory = new Factory1();

        startGrids(2);

        factory = new Factory2();

        startClientGrid("client-1");
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testDisabledConsistencyCheck() throws Exception {
        nearEnabled = false;
        cacheMode = CacheMode.PARTITIONED;
        factory = new Factory1();

        startGrids(2);

        factory = new Factory2();

        System.setProperty(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK, "true");

        startClientGrid("client-1");

        factory = new Factory1();

        System.clearProperty(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK);

        startClientGrid("client-2");
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testNoStoreNearDisabled() throws Exception {
        nearEnabled = false;
        cacheMode = CacheMode.PARTITIONED;
        factory = new Factory1();

        startGrids(2);

        doTestNoStore();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testNoStoreNearEnabled() throws Exception {
        nearEnabled = true;
        cacheMode = CacheMode.PARTITIONED;
        factory = new Factory1();

        startGrids(2);

        doTestNoStore();
    }

    /**
     * @throws Exception If failed.
     */
    private void doTestNoStore() throws Exception {
        factory = null;

        Ignite ignite = startClientGrid("client-1");

        IgniteCache<Object, Object> cache = ignite.cache(CACHE_NAME);

        cache.get(0);
        cache.getAll(F.asSet(0, 1));
        cache.getAndPut(0, 0);
        cache.getAndPutIfAbsent(0, 0);
        cache.getAndRemove(0);
        cache.getAndReplace(0, 0);
        cache.put(0, 0);
        cache.putAll(F.asMap(0, 0, 1, 1));
        cache.putIfAbsent(0, 0);
        cache.remove(0);
        cache.remove(0, 0);
        cache.removeAll(F.asSet(0, 1));
        cache.removeAll();
        cache.invoke(0, new EP());
        cache.invokeAll(F.asSet(0, 1), new EP());
    }

    /**
     * Load cache created on client as REPLICATED and see if it only loaded on servers
     */
    @Test
    public void testReplicatedLoadFromClient() throws Exception {
        cacheMode = CacheMode.REPLICATED;
        factory = new Factory3();

        startGrids(2);

        Ignite client = startClientGrid("client-1");

        IgniteCache cache = client.cache(CACHE_NAME);

        cache.loadCache(null);

        assertEquals(0, cache.localSize(CachePeekMode.ALL));

        assertEquals(10, grid(0).cache(CACHE_NAME).localSize(CachePeekMode.ALL));
        assertEquals(10, grid(1).cache(CACHE_NAME).localSize(CachePeekMode.ALL));

        assert !loadedFromClient : "Loaded data from client!";
    }

    /**
     * Load cache created on client as REPLICATED and see if it only loaded on servers
     */
    @Test
    public void testPartitionedLoadFromClient() throws Exception {
        cacheMode = CacheMode.PARTITIONED;
        factory = new Factory3();

        startGrids(2);

        Ignite client = startClientGrid("client-1");

        IgniteCache cache = client.cache(CACHE_NAME);

        cache.loadCache(null);

        assertEquals(0, cache.localSize(CachePeekMode.ALL));

        assertEquals(10, grid(0).cache(CACHE_NAME).localSize(CachePeekMode.ALL));
        assertEquals(10, grid(1).cache(CACHE_NAME).localSize(CachePeekMode.ALL));

        assert !loadedFromClient : "Loaded data from client!";
    }

    /**
     */
    private static class Factory1 implements Factory<CacheStore> {
        /** {@inheritDoc} */
        @Override public CacheStore create() {
            return null;
        }
    }

    /**
     */
    private static class Factory2 implements Factory<CacheStore> {
        /** {@inheritDoc} */
        @Override public CacheStore create() {
            return null;
        }
    }

    /**
     */
    private static class Factory3 implements Factory<CacheStore> {
        /** {@inheritDoc} */
        @Override public CacheStore create() {
            return new TestStore();
        }
    }

    /**
     */
    private static class EP implements CacheEntryProcessor {
        /** {@inheritDoc} */
        @Override public Object process(MutableEntry entry, Object... arguments) {
            return null;
        }
    }

    /**
     * Test store that loads 10 item
     */
    public static class TestStore extends CacheStoreAdapter<Object, Object> {
        /** */
        @IgniteInstanceResource
        private Ignite ignite;

        /** {@inheritDoc} */
        @Override public Integer load(Object key) {
            return null;
        }

        /** {@inheritDoc} */
        @Override public void write(Cache.Entry<?, ?> entry) {
            // No-op.
        }

        /** {@inheritDoc} */
        @Override public void delete(Object key) throws CacheWriterException {
            // No-op.
        }

        /** {@inheritDoc} */
        @Override public void loadCache(IgniteBiInClosure<Object, Object> clo, Object... args) {
            if (ignite.cluster().localNode().isClient())
                loadedFromClient = true;

            for (int i = 0; i < 10; i++)
                clo.apply(i, i);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.wearable.quiz" >

    <uses-sdk
        android:minSdkVersion="20"
        android:targetSdkVersion="20" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.DeviceDefault" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <service android:name=".QuizListenerService" >
            <intent-filter>
                <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
            </intent-filter>
        </service>
        <service android:name=".UpdateQuestionService" />
        <service android:name=".DeleteQuestionService" />
        <service android:name=".QuizReportActionService" />

    </application>

</manifest>


text:
<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
             xmlns:widget='urn:import:org.kie.workbench.common.widgets.metadata.client.widget'
             xmlns:gwt='urn:import:com.google.gwt.user.client.ui'>

  <ui:with field="i18n" type="org.kie.workbench.common.widgets.metadata.client.resources.i18n.MetadataConstants"/>

  <ui:style>

    .firstColumn {
      float: left;
      width: 120px;
    }

	.forceUnlock {
	  display:inline-block;
	}
  </ui:style>

  <gwt:HTMLPanel>

          <gwt:Label text='{i18n.CategoriesMetaData}'/>

          <widget:CategorySelectorWidget ui:field="categories"/>

          <gwt:Label text='{i18n.NoteMetaData}'/>

          <gwt:Label ui:field="note"/>

          <gwt:Label text='{i18n.URI}'/>

          <gwt:Label ui:field="uri"/>

          <gwt:Label text='{i18n.SubjectMetaData}'/>

          <gwt:TextBox ui:field="subject" title='{i18n.AShortDescriptionOfTheSubjectMatter}'/>

          <gwt:Label text='{i18n.TypeMetaData}'/>

          <gwt:TextBox ui:field="type" title='{i18n.TypeTip}'/>

          <gwt:Label text='{i18n.ExternalLinkMetaData}'/>

          <gwt:TextBox ui:field="external" title='{i18n.ExternalLinkTip}'/>

          <gwt:Label text='{i18n.SourceMetaData}'/>

          <gwt:TextBox ui:field="source" title='{i18n.SourceMetaDataTip}'/>

          <gwt:Label text='{i18n.LockMetaData}'/>

          <gwt:InlineLabel ui:field="lockedBy" text='{i18n.LockedByHint}'/>
          <gwt:PushButton addStyleNames="{style.forceUnlock}" ui:field="unlock" text='{i18n.ForceUnlockCaption}'/>

  </gwt:HTMLPanel>

</ui:UiBinder>


text:
package com.emc.ecs.nfsclient.rpc;

import java.io.IOException;

/**
 * This class allows users to specify how new response instances are created
 * during repeated RPC calls, and how responses are validated before their data
 * is used.
 *
 * @author seibed
 */
public abstract class RpcResponseHandler<T> {

    /**
     * The current response.
     */
    private T _response;

    /**
     * Get the current response.
     *
     * @return the current response
     */
    public T getResponse() {
        return _response;
    }

    /**
     * Create a new response and return it.
     *
     * @return the new response
     */
    public T getNewResponse() {
        _response = makeNewResponse();
        return _response;
    }

    /**
     * This is implemented in all concrete subclasses, so that the new response
     * can be created using any available parameters.
     *
     * @return the new response.
     */
    protected abstract T makeNewResponse();

    /**
     * This is implemented in all concrete subclasses to check responses for
     * validity, and throws an IOException if the response indicates that the
     * request failed.
     *
     * @param request
     *            This is used for error messages, to aid debugging, since the
     *            response will likely not have enough data to determine the
     *            request that caused it.
     * @throws IOException
     */
    public abstract void checkResponse(RpcRequest request) throws IOException;

}


text:
Version 0.1.2

* compatibility with configuration via chef-client cookbook
* why-run reports resources as pending
* Chef 13 compatibility

Version 0.1.1

* node name is always reported downcased

Version 0.1.0

* add support for chef-clients running on Windows

Version 0.0.9
* add more configuration options - whitelisting and blacklisting attributes
* support for attributes caching

Version 0.0.1 - 0.0.8
* handlers for uploading facts and reports


text:
#ifndef HGINPUTLISTENER_H_
#define HGINPUTLISTENER_H_

#include "HGSystem.h"
#include "HGIComponent.h"

HGNAMESPACE_START

class InputListener : public IComponent
{
public:
    InputListener();
    ~InputListener();

    // Composite
    static void             RegisterComponentType(void);
    virtual void            deInitialize();
    virtual EventResult     handleEvent(const Event& event);
};

HGNAMESPACE_END

#endif // HGINPUTLISTENER_H_


text:
using System.Diagnostics.Contracts;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace Thinktecture.IdentityModel.Extensions
{
    internal class XmlConverter
    {
        private readonly StringBuilder _xmlTextBuilder;
        private readonly XmlWriter _writer;

        private XmlConverter()
        {
            _xmlTextBuilder = new StringBuilder();

            _writer = new XmlTextWriter(new StringWriter(_xmlTextBuilder))
            {
                Formatting = Formatting.Indented,
                Indentation = 2
            };
        }

        public XmlConverter(XNode e)
            : this()
        {
            Contract.Requires(e != null);

            e.WriteTo(_writer);
        }

        public XmlConverter(XmlNode e)
            : this()
        {
            Contract.Requires(e != null);

            e.WriteTo(_writer);
        }

        public XElement CreateXElement()
        {
            return XElement.Load(new StringReader(_xmlTextBuilder.ToString()));
        }

        public XDocument CreateXDocument()
        {
            return XDocument.Load(new StringReader(_xmlTextBuilder.ToString()));
        }

        public XmlElement CreateXmlElement()
        {
            return CreateXmlDocument().DocumentElement;
        }

        public XmlDocument CreateXmlDocument()
        {
            var doc = new XmlDocument();
            doc.Load(new XmlTextReader(new StringReader(_xmlTextBuilder.ToString())));
            return doc;
        }
    }
}


text:
package cmd

import (
	"fmt"
	"io"
	"strings"
	"time"

	kapi "k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/fields"
	kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/watch"

	"github.com/openshift/origin/pkg/client"
	"github.com/openshift/origin/pkg/cmd/cli/describe"
	imageapi "github.com/openshift/origin/pkg/image/api"
	"github.com/spf13/cobra"

	"github.com/openshift/origin/pkg/cmd/util/clientcmd"
)

const (
	importImageLong = `
Import tag and image information from an external Docker image repository

Only image streams that have a value set for spec.dockerImageRepository and/or
spec.Tags may have tag and image information imported.`

	importImageExample = `  $ %[1]s import-image mystream`
)

// NewCmdImportImage implements the OpenShift cli import-image command.
func NewCmdImportImage(fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:        "import-image IMAGESTREAM[:TAG]",
		Short:      "Imports images from a Docker registry",
		Long:       importImageLong,
		Example:    fmt.Sprintf(importImageExample, fullName),
		SuggestFor: []string{"image"},
		Run: func(cmd *cobra.Command, args []string) {
			err := RunImportImage(f, out, cmd, args)
			kcmdutil.CheckErr(err)
		},
	}
	cmd.Flags().String("from", "", "A Docker image repository or tag to import images from")
	cmd.Flags().Bool("confirm", false, "If true, allow the image stream import location to be set or changed")
	cmd.Flags().Bool("all", false, "If true, import all tags from the provided source on creation or if --from is specified")
	cmd.Flags().Bool("insecure", false, "If true, allow importing from registries that have invalid HTTPS certificates or are hosted via HTTP")

	return cmd
}

// RunImportImage contains all the necessary functionality for the OpenShift cli import-image command.
func RunImportImage(f *clientcmd.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
	if len(args) == 0 || len(args[0]) == 0 {
		return kcmdutil.UsageError(cmd, "you must specify the name of an image stream")
	}

	target := args[0]
	namespace, _, err := f.DefaultNamespace()
	if err != nil {
		return err
	}

	osClient, _, err := f.Clients()
	if err != nil {
		return err
	}

	insecure := kcmdutil.GetFlagBool(cmd, "insecure")
	from := kcmdutil.GetFlagString(cmd, "from")
	confirm := kcmdutil.GetFlagBool(cmd, "confirm")
	all := kcmdutil.GetFlagBool(cmd, "all")

	targetRef, err := imageapi.ParseDockerImageReference(target)
	switch {
	case err != nil:
		return fmt.Errorf("the image name must be a valid Docker image pull spec or reference to an image stream (e.g. myregistry/myteam/image:tag)")
	case len(targetRef.ID) > 0:
		return fmt.Errorf("to import images by ID, use the 'tag' command")
	case len(targetRef.Tag) != 0 && all:
		// error out
		return fmt.Errorf("cannot specify a tag %q as well as --all", target)
	case len(targetRef.Tag) == 0 && !all:
		// apply the default tag
		targetRef.Tag = imageapi.DefaultImageTag
	}
	name := targetRef.Name
	tag := targetRef.Tag

	imageStreamClient := osClient.ImageStreams(namespace)
	stream, err := imageStreamClient.Get(name)
	if err != nil {
		if !errors.IsNotFound(err) {
			return err
		}

		// the stream is new
		if !confirm {
			return fmt.Errorf("no image stream named %q exists, pass --confirm to create and import", name)
		}
		if len(from) == 0 {
			from = target
		}
		if all {
			stream = &imageapi.ImageStream{
				ObjectMeta: kapi.ObjectMeta{Name: name},
				Spec:       imageapi.ImageStreamSpec{DockerImageRepository: from},
			}
		} else {
			stream = &imageapi.ImageStream{
				ObjectMeta: kapi.ObjectMeta{Name: name},
				Spec: imageapi.ImageStreamSpec{
					Tags: map[string]imageapi.TagReference{
						tag: {
							From: &kapi.ObjectReference{
								Kind: "DockerImage",
								Name: from,
							},
						},
					},
				},
			}
		}

	} else {
		// the stream already exists
		if len(stream.Spec.DockerImageRepository) == 0 && len(stream.Spec.Tags) == 0 {
			return fmt.Errorf("image stream has not defined anything to import")
		}

		if all {
			// importing a whole repository
			if len(from) == 0 {
				from = target
			}
			if from != stream.Spec.DockerImageRepository {
				if !confirm {
					if len(stream.Spec.DockerImageRepository) == 0 {
						return fmt.Errorf("the image stream does not currently import an entire Docker repository, pass --confirm to update")
					}
					return fmt.Errorf("the image stream has a different import spec %q, pass --confirm to update", stream.Spec.DockerImageRepository)
				}
				stream.Spec.DockerImageRepository = from
			}

		} else {
			// importing a single tag

			// follow any referential tags to the destination
			finalTag, existing, ok, multiple := imageapi.FollowTagReference(stream, tag)
			if !ok && multiple {
				return fmt.Errorf("tag %q on the image stream is a reference to %q, which does not exist", tag, finalTag)
			}

			if ok {
				// disallow changing an existing tag
				if existing.From == nil || existing.From.Kind != "DockerImage" {
					return fmt.Errorf("tag %q already exists - you must use the 'tag' command if you want to change the source to %q", tag, from)
				}
				if len(from) != 0 && from != existing.From.Name {
					if multiple {
						return fmt.Errorf("the tag %q points to the tag %q which points to %q - use the 'tag' command if you want to change the source to %q", tag, finalTag, existing.From.Name, from)
					}
					return fmt.Errorf("the tag %q points to %q - use the 'tag' command if you want to change the source to %q", tag, existing.From.Name, from)
				}

				// set the target item to import
				from = existing.From.Name
				if multiple {
					tag = finalTag
				}

				// clear the legacy annotation
				delete(existing.Annotations, imageapi.DockerImageRepositoryCheckAnnotation)
				// reset the generation
				zero := int64(0)
				existing.Generation = &zero

			} else {
				// create a new tag
				if len(from) == 0 {
					from = target
				}
				existing = &imageapi.TagReference{
					From: &kapi.ObjectReference{
						Kind: "DockerImage",
						Name: from,
					},
				}
			}
			stream.Spec.Tags[tag] = *existing
		}
	}

	if len(from) == 0 {
		// catch programmer error
		return fmt.Errorf("unexpected error, from is empty")
	}

	// Attempt the new, direct import path
	isi := &imageapi.ImageStreamImport{
		ObjectMeta: kapi.ObjectMeta{
			Name:            stream.Name,
			Namespace:       namespace,
			ResourceVersion: stream.ResourceVersion,
		},
		Spec: imageapi.ImageStreamImportSpec{Import: true},
	}
	if all {
		isi.Spec.Repository = &imageapi.RepositoryImportSpec{
			From: kapi.ObjectReference{
				Kind: "DockerImage",
				Name: from,
			},
			ImportPolicy: imageapi.TagImportPolicy{Insecure: insecure},
		}
	} else {
		isi.Spec.Images = append(isi.Spec.Images, imageapi.ImageImportSpec{
			From: kapi.ObjectReference{
				Kind: "DockerImage",
				Name: from,
			},
			To:           &kapi.LocalObjectReference{Name: tag},
			ImportPolicy: imageapi.TagImportPolicy{Insecure: insecure},
		})
	}

	// TODO: add dry-run
	result, err := imageStreamClient.Import(isi)
	switch {
	case err == client.ErrImageStreamImportUnsupported:
	case err != nil:
		return err
	default:
		fmt.Fprint(cmd.Out(), "The import completed successfully.\n\n")

		// optimization, use the image stream returned by the call
		d := describe.ImageStreamDescriber{Interface: osClient}
		info, err := d.Describe(namespace, stream.Name)
		if err != nil {
			return err
		}

		fmt.Fprintln(out, info)

		if r := result.Status.Repository; r != nil && len(r.AdditionalTags) > 0 {
			fmt.Fprintf(out, "\ninfo: The remote repository contained %d additional tags which were not imported: %s\n", len(r.AdditionalTags), strings.Join(r.AdditionalTags, ", "))
		}
		return nil
	}

	// Legacy path, remove when support for older importers is removed
	delete(stream.Annotations, imageapi.DockerImageRepositoryCheckAnnotation)
	if insecure {
		if stream.Annotations == nil {
			stream.Annotations = make(map[string]string)
		}
		stream.Annotations[imageapi.InsecureRepositoryAnnotation] = "true"
	}

	if stream.CreationTimestamp.IsZero() {
		stream, err = imageStreamClient.Create(stream)
	} else {
		stream, err = imageStreamClient.Update(stream)
	}
	if err != nil {
		return err
	}

	resourceVersion := stream.ResourceVersion

	fmt.Fprintln(cmd.Out(), "Importing (ctrl+c to stop waiting) ...")

	updatedStream, err := waitForImport(imageStreamClient, stream.Name, resourceVersion)
	if err != nil {
		if _, ok := err.(importError); ok {
			return err
		}
		return fmt.Errorf("unable to determine if the import completed successfully - please run 'oc describe -n %s imagestream/%s' to see if the tags were updated as expected: %v", stream.Namespace, stream.Name, err)
	}

	fmt.Fprint(cmd.Out(), "The import completed successfully.\n\n")

	d := describe.ImageStreamDescriber{Interface: osClient}
	info, err := d.Describe(updatedStream.Namespace, updatedStream.Name)
	if err != nil {
		return err
	}

	fmt.Fprintln(out, info)
	return nil
}

// TODO: move to image/api as a helper
type importError struct {
	annotation string
}

func (e importError) Error() string {
	return fmt.Sprintf("unable to import image: %s", e.annotation)
}

func waitForImport(imageStreamClient client.ImageStreamInterface, name, resourceVersion string) (*imageapi.ImageStream, error) {
	streamWatch, err := imageStreamClient.Watch(kapi.ListOptions{FieldSelector: fields.OneTermEqualSelector("metadata.name", name), ResourceVersion: resourceVersion})
	if err != nil {
		return nil, err
	}
	defer streamWatch.Stop()

	for {
		select {
		case event, ok := <-streamWatch.ResultChan():
			if !ok {
				return nil, fmt.Errorf("image stream watch ended prematurely")
			}

			switch event.Type {
			case watch.Modified:
				s, ok := event.Object.(*imageapi.ImageStream)
				if !ok {
					continue
				}
				annotation, ok := s.Annotations[imageapi.DockerImageRepositoryCheckAnnotation]
				if !ok {
					continue
				}

				if _, err := time.Parse(time.RFC3339, annotation); err == nil {
					return s, nil
				}
				return nil, importError{annotation}

			case watch.Deleted:
				return nil, fmt.Errorf("the image stream was deleted")
			case watch.Error:
				return nil, fmt.Errorf("error watching image stream")
			}
		}
	}
}


text:
<?php

namespace Matthias\SymfonyConsoleForm\Tests\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\Length;

class NameType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'name',
            TextType::class,
            [
                'label' => 'Your name',
                'data' => 'Matthias',
                'constraints' => [
                    new Length(['min' => 4]),
                ],
            ]
        )->add(
            'submit',
            SubmitType::class,
            [
                'label' => 'Submit',
            ]
        );
    }
}


text:
namespace eprosima {
namespace fastdds {
namespace dds {

class DomainParticipant;
class DomainParticipantQos;
class TopicDataType;
class DataReaderQos;
class DataWriterQos;

}  // namespace dds
}  // namespace fastdds
}  // namespace eprosima

namespace chrono {
namespace synchrono {

class SynDDSParticipantListener;

/// @addtogroup synchrono_communication_dds
/// @{

const std::string default_prefix = std::string("/syn/node/");

/// Derived communicator used to establish and facilitate communication between nodes.
/// Uses the Data Distribution Service (DDS) standard
class SYN_API SynDDSCommunicator : public SynCommunicator {
  public:
    SynDDSCommunicator(int node_id, const std::string& prefix = default_prefix);

    ///@brief Default constructor
    ///
    ///@param name The name to set to the qos
    SynDDSCommunicator(const std::string& name, const std::string& prefix = default_prefix);

    ///@brief Set the QoS directly from the constructor
    ///
    ///@param qos the Quality of Service to set for the participant
    SynDDSCommunicator(eprosima::fastdds::dds::DomainParticipantQos& qos, const std::string& prefix = default_prefix);

    ///@brief Destructor
    ///
    virtual ~SynDDSCommunicator();

    ///@brief Initialization function typically responsible for establishing a connection.
    /// Although not mandatory, this function should handle initial peer-to-peer communication.
    /// This could mean a simple handshake or an actual exchange of information used during the simulation.
    ///
    virtual void Initialize() override;

    ///@brief This function is responsible for continuous synchronization steps
    /// This function, depending on it's implementation, could be blocking or non-blocking.
    /// As in, depending on the derived class implementation, this function could use synchronous
    /// or asynchronous function calls to implement a communication interface.
    ///
    /// Synchronize will serialize the underlying message buffer if it hasn't yet
    ///
    virtual void Synchronize() override;

    ///@brief This function is responsible for blocking until an action is received or done.
    /// For example, a process may call Barrier to wait until another process has established
    /// certain classes and initialized certain quantities. This functionality should be implemented
    /// in this function.
    ///
    virtual void Barrier() override;

    // -----------------------------------------------------------------------------------------------

    ///@brief This function is responsible for blocking until the passed number of participants
    /// has been matched.
    ///
    ///@param num_participants number of participants to block until matched
    void Barrier(unsigned int num_participants);

    ///@brief Get the matched participant's names
    /// A matched participant is defined as a DDSParticipant Entity that has matched
    /// with the participant created on this node
    ///
    std::vector<std::string> GetMatchedParticipantNames();

    // -----------------------------------------------------------------------------------------------

    ///@brief Create a topic
    /// The topic will be registered with the participant, if desired
    ///
    /// The SynDDSCommunicator maintains a list of topics instantiated in the simulation.
    /// A topic can only by constructed through this function or indirectly through the
    /// CreateSubscriber/CreatePublisher functions
    ///
    ///@param topic_name The name associated with the topic
    ///@param data_type The topic data type
    ///@param topic_prefix The prefix to use
    std::shared_ptr<SynDDSTopic> CreateTopic(const std::string& topic_name,
                                             eprosima::fastdds::dds::TopicDataType* data_type,
                                             const std::string& topic_prefix);

	///@brief Create a topic using the communicator's prefix
    /// The topic will be registered with the participant, if desired
    ///
    ///@param topic_name The name associated with the topic
    ///@param data_type The topic data type
    std::shared_ptr<SynDDSTopic> CreateTopic(const std::string& topic_name,
                                             eprosima::fastdds::dds::TopicDataType* data_type);

    ///@brief Create a subscription to the specified topic
    /// Will call the callback when a subscription is received
    /// Takes a SynDDSTopic object (see CreateTopic)
    ///
    ///@param topic Topic object describing the DDS topic
    ///@param callback The callback called when data is received
    ///@param message The message that is used to parse the returned message
    ///@param is_synchronous Whether the subscriber synchronously receives data (default: true)
    ///@param is_managed Whether the SynDDSCommunicator is responsible for using the sending/receiving function calls
    ///@param read_qos Data Reader Quality of Service. Falls back to default if nullptr
    std::shared_ptr<SynDDSSubscriber> CreateSubscriber(std::shared_ptr<SynDDSTopic> topic,
                                                       std::function<void(void*)> callback,
                                                       void* message,
                                                       bool is_synchronous = true,
                                                       bool is_managed = false,
                                                       eprosima::fastdds::dds::DataReaderQos* read_qos = nullptr);

    ///@brief Create a subscription to the specified topic
    /// Will call the callback when a subscription is received
    /// Takes a string and TopicDataType and creates a topic (see CreateTopic)
    ///
    ///@param topic_name The name associated with the topic
    ///@param data_type The topic data type
    ///@param callback The callback called when data is received
    ///@param message The message that is used to parse the returned message
    ///@param is_synchronous Whether the subscriber synchronously receives data (default: true)
    ///@param is_managed Whether the SynDDSCommunicator is responsible for using the sending/receiving function calls
    std::shared_ptr<SynDDSSubscriber> CreateSubscriber(const std::string& topic_name,
                                                       eprosima::fastdds::dds::TopicDataType* data_type,
                                                       std::function<void(void*)> callback,
                                                       void* message,
                                                       bool is_synchronous = true,
                                                       bool is_managed = false);

    ///@brief Create a Publisher
    /// Returns a publisher handle to be used to publish information
    /// Takes a SynDDSTopic object (see CreateTopic)
    ///
    ///@param topic Topic object describing the DDS topic
    ///@param is_managed Whether the SynDDSCommunicator is responsible for using the sending/receiving function calls
    ///@param read_qos Data Writer Quality of Service. Falls back to default if nullptr
    std::shared_ptr<SynDDSPublisher> CreatePublisher(std::shared_ptr<SynDDSTopic> topic,
                                                     bool is_managed = false,
                                                     eprosima::fastdds::dds::DataWriterQos* write_qos = nullptr);

    ///@brief Create a Publisher
    /// Returns a publisher handle to be used to publish information
    /// Takes a string and TopicDataType and creates a topic (see CreateTopic)
    ///
    ///@param topic_name The name associated with the topic
    ///@param data_type The topic data type
    ///@param is_managed Whether the SynDDSCommunicator is responsible for using the sending/receiving function calls
    std::shared_ptr<SynDDSPublisher> CreatePublisher(const std::string& topic_name,
                                                     eprosima::fastdds::dds::TopicDataType* data_type,
                                                     bool is_managed = false);

    // -----------------------------------------------------------------------------------------------

    std::string m_prefix;

  private:
    void InitQoS(const std::string& name);

    ///@brief Creates the underyling participant
    ///
    ///@param qos the Quality of Service to set to the participant
    void CreateParticipant(eprosima::fastdds::dds::DomainParticipantQos& qos);

    ///@brief Publish the outgoing messagse
    ///
    void Publish();

    ///@brief Listen for incoming messages
    /// Will only block if the underlying subscribers are synchronous
    ///
    void Listen();

    // -----------------------------------------------------------------------------------------------

    eprosima::fastdds::dds::DomainParticipant* m_participant;  ///< Domain Participant which maintains the pubs/subs

    TopicMap m_topics;
    PublisherList m_publishers;
    SubscriberList m_subscribers;

    SynDDSParticipantListener* m_listener;
};

/// @} synchrono_communication

}  // namespace synchrono
}  // namespace chrono

#endif


text:
import glslify from 'glslify'

Object.assign(exports, {
  [__dirname + '/variables']: glslify(__dirname + '/variables.glsl'),
  [__dirname + '/uniforms']: glslify(__dirname + '/uniforms.glsl'),
  [__dirname + '/camera']: glslify(__dirname + '/camera.glsl'),
})


text:
const char *message[ MAX ] = {
    "Correct!",
    "Affirmative!",
    "Right!",
    "That's it!",
    "Absolutely!",
    "Way to go!",
    "Good!",
    "Precisely!"
};

// For the purpose of progress report
const char *modeTypes[ MAX_MODES ] = {
    "Image Naming with Prompt",
    "Image Naming without Prompt",
    "Image Comparison",
    "Image Verification"
};

#ifdef APP_AMINO
// For the purpose of progress report
const char *propertyTypes[ MAX_PROPERTY_TYPES ] = {
    "Acidic / Basic / Amide / Neutral",
    "Charged / Uncharged",
    "Polar / Non-polar",
    "Hydrophobic / Hydrophilic",
    "Aromatic / Hydroxyl / Thiol / Aliphatic",
    "No Properties"
};

// For the purpose of progress report
const char *nameTypes[ MAX_NAME_TYPES ] = {
    "Full Name",
    "Single Letter Name",
    "Three Letter Name",
    "No Name"
};
#endif

QuizDialog * QuizDialog::s_instance = nullptr;

QuizDialog::QuizDialog(QWidget * parent)
    : QDialog(parent)
{
    initialPalette = palette();
    setWindowFlags(Qt::CustomizeWindowHint | Qt::Dialog | Qt::WindowTitleHint);
    setWindowTitle("Quiz Session");
    font.setPixelSize(ppp(25));

    imageLabel1 = new QLabel(this); // Label to hold image or left comparison image
    imageLabel1->setBackgroundRole(QPalette::Base);
    imageLabel1->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    imageLabel1->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    imageLabel1->setFont(font);

    imageLabel2 = new QLabel(this); // Label to hold right comparison image
    imageLabel2->setBackgroundRole(QPalette::Base);
    imageLabel2->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    imageLabel2->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    imageLabel2->setFont(font);
    imageLabel2->setVisible(false);

    // Label to hold answer when Quiz/Test mode is
    // Image Naming with Option
    answerLabel = new QLabel(this);
    answerLabel->setBackgroundRole(QPalette::Base);
    answerLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    answerLabel->setFont(font);
    answerLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    answerLabel->setVisible(true);

    incorrectAnswerLabel = new QLabel(this);
    incorrectAnswerLabel->setBackgroundRole(QPalette::Base);
    incorrectAnswerLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    incorrectAnswerLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    incorrectAnswerLabel->setVisible(false);

    font.setPixelSize(ppp(15));

    // Label to hold "Answer :" or "Same (y/n)" to the left of the textbox
    enterAnswerHereLabel = new QLabel(this);
    enterAnswerHereLabel->setBackgroundRole(QPalette::Base);
    enterAnswerHereLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    enterAnswerHereLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    enterAnswerHereLabel->setFont(font);
    enterAnswerHereLabel->setVisible(false);

    // Textbox to enter the answer
    answerLineEdit = new QLineEdit(this);
    answerLineEdit->setFont(font);
    answerLineEdit->setVisible(false);

    QObject::connect(answerLineEdit, SIGNAL(returnPressed()), this, SLOT(answerEntered()));

    okButton = new QPushButton("Ok", this);
    okButton->setFont(font);
    okButton->setVisible(false);

    QObject::connect(okButton, SIGNAL(clicked()), this, SLOT(answerEntered()));

    cancelButton = new QPushButton("Cancel", this);
    cancelButton->setFont(font);
    cancelButton->setVisible(false);

    QObject::connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancelClicked()));

    setFocusPolicy(Qt::StrongFocus);  // Keyboard focus to get keystrokes

    interval = 1000;
    fixationInterval = 500;
    numberOfImages = INT_MAX;
    quizOption = 0;
    viewProgressAfterQuiz = false;
    viewProgressAfterTest = false;
    firstAttempt = true;
    quizInProgress = false;
    spellingSensitivity = 1.0;
    messageIndex = 0;

#ifndef APP_AMINO
    backgroundColor = Qt::white;
#endif
}

// Initialize progress report variables
void QuizDialog::initProgressReportVariables()
{
    images.clear();
    attempts.clear();
    rightAnswers.clear();

    int n = answerList.size() > numberOfImages ? numberOfImages:answerList.size();
    for (int i = 0; i < n; ++i)
    {
        QString image = answerList[indexList[i]].split('|').at(0);
        int index = images.indexOf(image);
        if (index == -1)
        {
            images << image;
            attempts << 0.0;
            rightAnswers << 0.0;
        }
    }
}

// Update progress report variables
void QuizDialog::updateProgressReportVariables(bool correct)
{
    // quizOption == 2 => Image Comparison
    // For image comparison the first image is selected
    // from the list of images chosen for the Quiz/Test
    // The second image is selected randomnly  Therefore
    // we add it to the list of chosen amino acids.
    if (quizOption == 2)
    {
        attempts[images.indexOf(image1)] += 0.5;
        int index = images.indexOf(image2);
        if (index == -1)
        {
            images << image2;
            attempts << 0.0;
            rightAnswers << 0.0;
        }
        attempts[images.indexOf(image2)] += 0.5;
    }
    else
        attempts[images.indexOf(image1)] += 1.0;

    // If Image comparison and the answer is correct
    // award 0.5 to each image otherwise 1.0
    if (correct)
    {
        if (quizOption == 2)
        {
            rightAnswers[images.indexOf(image1)] += 0.5;
            rightAnswers[images.indexOf(image2)] += 0.5;
        }
        else
            rightAnswers[images.indexOf(image1)] += 1.0;
    }
}

// Save progress report
void QuizDialog::saveProgress()
{
    double totalRight = 0.0;        // number of right answers
    double totalAttempts = 0.0;     // number of attempts

    QString record="";
    if (quiz)
        record.append("Quiz");
    else
        record.append("Test");

    record.append(",");
    record.append(modeTypes[quizOption]);
    record.append(",");
    record.append(QDateTime::currentDateTime().toString());
    record.append(",");

#ifdef APP_AMINO
    record.append(propertyTypes[propertyType]);
    record.append(",");
    record.append(nameTypes[nameType]);
    record.append(",");
    record.append(imageType);
#else
    record.append(propertyString);
#endif

    for (int i = 0; i < images.size(); ++i)
    {
        record.append("," );
        record.append(images[i]);
        record.append(",");
        double percentage = 0.0;

        if (attempts[i] != 0.0)
        {
            percentage = ((double)rightAnswers[i] / (double)attempts[i]) * 100;
            totalRight += rightAnswers[i];
            totalAttempts += attempts[i];
        }

        record.append(QString::number(percentage, 'f', 2));
    }

    record.append(",");
    double total = answerList.size() < numberOfImages ? answerList.size() : numberOfImages;
    double overallPercentage = (totalRight / total) * 100;
    double percentageComplete = (totalAttempts / total) * 100;
    record.append(QString::number(percentageComplete, 'f', 2));
    record.append(",");
    record.append(QString::number(overallPercentage, 'f', 2));
    record.append("\n");
    records.append(record);

    hide();

    if ((quiz && viewProgressAfterQuiz) || (!quiz && viewProgressAfterTest))
    {
        qDebug() << "generating report '" << UserDataFolder().c_str() << "' for user " << username;
        ProgressReport::instance()->moveToCenter();
        ProgressReport::instance()->generateReport(records, username);
        ProgressReport::instance()->exec();
    }
}

// Maximize dialog and place widgets as required
void QuizDialog::organizeDialog()
{
    QSize dialogSize = size();

    // If the quiz/test option is NOT "Image Naming with prompt"
    // textbox, buttons etc. are to displayed in the middle
    // of the screen.
    int h = quizOption > 0 ? dialogSize.height() / 2 : dialogSize.height() - ppp(95);
    int midway = dialogSize.width() / 2;

    enterAnswerHereLabel->setGeometry(midway - ppp(280 - 200 - 10), h, ppp(200), ppp(30));
    answerLineEdit->setGeometry(midway - ppp(280), h, ppp(410), ppp(30));
    answerLineEdit->setFocus();
    okButton->setGeometry(midway + ppp(130 + 10), h, ppp(110), ppp(30));
    cancelButton->setGeometry(midway + ppp(130 + 10 + 110 + 10), h, ppp(110), ppp(30));

    // Only in Image Comparison would we need 2 images
    if (quizOption != 2)
    {
        imageLabel1->setGeometry(0, 0, dialogSize.width(), dialogSize.height() - ppp(100));
        imageLabel2->setVisible(false);
    }
    else
    {
        imageLabel1->setGeometry(ppp(1), ppp(1), dialogSize.width() / 2 - ppp(2), dialogSize.height() - ppp(2));
        imageLabel2->setVisible(true);
        imageLabel2->setGeometry(dialogSize.width() / 2 + ppp(1), ppp(2), dialogSize.width() / 2 - ppp(2), dialogSize.height() - ppp(2));
    }

    answerLabel->setGeometry(0, dialogSize.height() - ppp(50), dialogSize.width(), ppp(50));
    incorrectAnswerLabel->setGeometry(QRect(0, 0, dialogSize.width(), dialogSize.height()));
    initProgressReportVariables();
    quizInProgress = true;

    updateLabel();
}

// Initialize Yes/No list
void QuizDialog::initYNList()
{
    ynListIndex = 0;     // Yes/No list index
    int n = filenameList.size()<numberOfImages?filenameList.size():numberOfImages;
    int i = 0;

    // Initialize half the list to 1
    // and the rest to 0 then randomize

    for (; i < n / 2; ++i)
        ynList << 1;

    for (; i < n; ++i)
        ynList << 0;

    for (i = 1; i < n; ++i)
    {
        int index1 = rand() % n;
        int index2 = rand() % n;
        while (index1 == index2)
            index2 = rand() % n;
        int temp = ynList[index1];
        ynList[index1] = ynList[index2];
        ynList[index2] = temp;
    }
}

// Initialize variables before starting Quiz/Test session
void QuizDialog::initialize( bool flag )
{
    setPalette(initialPalette);
    initYNList();
    currentImageIndex = -1;
    intervalCounter = 2;
    firstAttempt = true;
    incorrectAnswer = false;
    quiz = flag;
    answerLabel->setText("");
    organizeDialog();
}

void QuizDialog::setSize(QSize size)
{
   setMaximumSize(size);
   setMinimumSize(size);
}

// Find the number of matching characters in the given answer
int QuizDialog::getNumberOfMatchingCharacters(QString correctAnswer, QString attempt)
{
    int i = 0;
    int j = 0;
    int count = 0;
    int correctAnswerLength = correctAnswer.length();  // length of the correct answer
    int attemptLength = attempt.length();              // length of the attempted answer

    if (correctAnswerLength == 0 || attemptLength == 0)
        return 0;

    // Find first pair of matching characters
    while (i < correctAnswerLength)
    {
        if (correctAnswer.at(i) == attempt.at(j))
            break;

        j++;

        if (j == attemptLength || j == MAX_SEARCH_LENGTH)   // MAX_SEARCH_LENGTH=3
        {
            i++;
            j = 0;
        }
    }

    // Get the matching substring begining at i, j
    if (i < correctAnswerLength)
    {
        int p = i + 1;
        int q = j + 1;
        while (p < correctAnswerLength && q < attemptLength )
        {
            if (correctAnswer.at(p) == attempt.at(q))
            {
                p++;
                q++;
            }
            else
                break;
        }

        // Add to list for tester to see.
        // Make recursive call with rest of words.
        if (p > i)
        {
            count = p - i;
            if (p < correctAnswerLength && q < attemptLength)
            {
                correctAnswer.remove(0, p);
                attempt.remove(0, q);
                count += getNumberOfMatchingCharacters(correctAnswer, attempt);
            }
        }
    }

    return count;
}

// Method that returns if the answer is correct or not
// depending on the spell check senisitivity. Spelling
// sensitivity is added to each individual word in the
// answer and not the answer as a whole.
bool QuizDialog::isCorrectAnswer(QString correctAnswer, QString attempt)
{
    // Looking for an exact match
    if (correctAnswer == attempt)
        return true;

    QStringList correctList = correctAnswer.simplified().split(' ');      // List that contains words in the answer
    QStringList attemptList = attempt.simplified().split(' ');            // List that contains the words in the attempt

    int a = attemptList.size();

    if (correctList.size() != a)
        return false;

    for (int i = 0; i  attemptList.at(i).length()?
            correctList.at(i).length():attemptList.at(i).length();
        if (n / maxLength < spellingSensitivity)
            return false;
    }
    return true;
}

// Method if cancel is clicked
void QuizDialog::cancelClicked()
{
    enterAnswerHereLabel->setVisible(false);
    answerLineEdit->setVisible(false);
    okButton->setVisible(false);
    cancelButton->setVisible(false);

    int yesNo = QMessageBox::question(this, "Quit", "Are you sure?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    if (yesNo == QMessageBox::Yes)
        saveProgress();
    else
        getAnswer();
}

// Listening to the keyboard
void QuizDialog::keyPressEvent(QKeyEvent * e)
{
    if (incorrectAnswer)
    {
        incorrectAnswer = true;

        // The right answer
        QString image1 = answerList.at(indexList[currentImageIndex]).split('|').at(1);

        // If image comparison, then answer
        // string has name of both images.
        if (quizOption == 2)      // Image Comparison
        {
            QString image2 = answerList.at(indexList[randomIndex]).split('|').at(1);
            image1 = "Left: " + image1 + "
" + "Right: " + image2;
        }

        // Press y to see the correct answer before repeating the question.
        // Press n to go on to the next question without repeating the question.
        // Press r to repeat the question without seeing the correct answer.
        int key = e->key();
        switch( key )
        {
            case Qt::Key_Y:
                currentImageIndex--;
                firstAttempt = false;
                font.setPixelSize(ppp(25));
                incorrectAnswerLabel->setFont(font);
                incorrectAnswerLabel->setText(changeFontColor(image1));
                if (quizOption == 2)
                    QTimer::singleShot(1000, this, SLOT(updateLabel()));
                else
                    QTimer::singleShot(1500, this, SLOT(updateLabel()));
                break;
            case Qt::Key_N:
                firstAttempt = true;
                updateLabel();
                break;
            case Qt::Key_R:
                currentImageIndex--;
                firstAttempt = false;
                updateLabel();
                break;
        }
    }
}

// Method to ask show the text that asks the user
// what he wants to do once he gets the answer wrong.
// if the visibility is true otherwise toggle
void QuizDialog::setVisibleIncorrectAnswerLabel(bool visibility)
{
    imageLabel1->setVisible(!visibility);

#ifdef APP_AMINO
    answerLabel->setText(" ");
#endif

    if (quizOption == 2)
        imageLabel2->setVisible(!visibility);

    incorrectAnswerLabel->setVisible(visibility);

    if (visibility)
    {
        font.setPixelSize(ppp(15));
        incorrectAnswerLabel->setFont(font);
        incorrectAnswerLabel->setText(changeFontColor(
            "Your answer is incorrect.
\
            Press \"y\" to see the correct answer before repeating the question.
\
            Press \"n\" to go on to the next question without repeating the question.
\
            Press \"r\" to repeat the question without seeing the correct answer."
            )
        );
    }

    incorrectAnswer = visibility;
}

// Method if Ok button is
// clicked or Return is hit
void QuizDialog::answerEntered()
{
    enterAnswerHereLabel->setVisible(false);
    answerLabel->setText(" ");
    answerLineEdit->setVisible(false);
    okButton->setVisible(false);
    cancelButton->setVisible(false);

#ifndef APP_AMINO
    imageLabel1->setText(" ");
#endif

    // Find out if the answer is correct or not
    bool correct = isCorrectAnswer(
        answer1.toLower().trimmed(),
        answerLineEdit->text().toLower().trimmed()
    );

    // Save report only for the first attempt
    if (firstAttempt)
        updateProgressReportVariables( correct );

    // Notify the user of right or wrong answer
    // only in quiz mode.
    if (quiz)
    {
        if (correct)
        {
            int tempIndex = rand() % MAX;
            while (messageIndex == tempIndex )
                tempIndex = rand() % MAX;

            messageIndex = tempIndex;
            QMessageBox::information(this, "Correct Answer", message[messageIndex], QMessageBox::Ok, QMessageBox::Ok);
            firstAttempt = true;
        }
        else
        {
            setVisibleIncorrectAnswerLabel(true);
            return;
        }
    }

    updateLabel();
}

// Ask the user to enter the answer
void QuizDialog::getAnswer()
{
    enterAnswerHereLabel->setVisible(true);
    answerLineEdit->setVisible(true);
    debugString += answer1;

    answerLineEdit->setText("");
    answerLineEdit->selectAll();
    answerLineEdit->setFocus();
    okButton->setVisible(true);
    cancelButton->setVisible(true);
    enterAnswerHereLabel->setText(changeFontColor("Answer:"));

#ifndef APP_AMINO
    imageLabel1->setVisible(true);
    if (quizOption == 0)
       answerLabel->setVisible(true);
#endif

    if (quizOption > 1)
        enterAnswerHereLabel->setText(changeFontColor("Same?(y/n)"));

    if (quizOption != 0)
    {
        imageLabel1->setText(" ");
        imageLabel2->setText(" ");
        answerLabel->setText(" ");
        intervalCounter = 2;
    }
    else
        intervalCounter = 0;
}

void QuizDialog::setBackgroundColor(int color)
{
    int blackColor = Qt::white;

#ifdef APP_AMINO
    blackColor = Qt::black;
#endif

    backgroundColor = color;
    QPalette pal;
    switch (color)
    {
        case Qt::black:
            pal.setColor(QPalette::Window, blackColor);
            break;
        case Qt::white:
            pal.setColor(QPalette::Window, Qt::white);
            break;
    }

    setPalette(pal);
}

QString QuizDialog::changeFontColor(QString caption)
{
    QString paddedString;
    QString blackColorString = "";

#ifdef APP_AMINO
    blackColorString = "";
#endif

    switch (backgroundColor)
    {
        case Qt::black:
            paddedString = blackColorString + caption + "";
            break;
        case Qt::white:
            paddedString = "" + caption + "";
            break;
    }
    return paddedString;
}

void QuizDialog::loadImage(int index)
{
    fname = (ResourceFolder() + "Images/").c_str();
    debugString += QString("%1").arg(filenameList.at(indexList[index])) + "|";
    fname = fname + QString("%1").arg(filenameList.at(indexList[index]));
    fname = fname + ".jpg";

    qDebug() << "loading image " << fname;
    image.load(fname);

    if (!image.load(fname))
    {
        QMessageBox::critical(this, "Error loading image",
            "A problem occured while trying to load the image. Terminating session.",
            QMessageBox::Ok, QMessageBox::Ok);

        hide();
        return;
    }
}

// Method specifically for Image Comparison and Verification
// that would return a random index depending on whether we
// want the answer to be yes or no.
int QuizDialog::generateRandomIndex()
{
    int x;
    int n = filenameList.size();
    bool yes = ynList[ynListIndex];
    int i = 0;
    if (yes)
    {
        for (; i < n; ++i)
        {
            answer2 = answerList.at(indexList[i]).split('|').at(1);
            if (i != currentImageIndex && answer1 == answer2 )
                break;
        }

        // If the for loop does not end that mean
        // an appropriate index was found else the
        // the only possible index is itself.
        if (i != n)
            x = i;
        else
            x = currentImageIndex;

        answer1 = "y";
    }
    else
    {
        x = rand() % n;
        while (currentImageIndex == x)
            x = rand() % n;

        answer2 = answerList.at(indexList[x]).split('|').at(1);
        while (answer1 == answer2)
        {
            x = rand() % n;
            while (currentImageIndex == x)
                x = rand() % n;
            answer2 = answerList.at(indexList[x]).split('|').at(1);
        }

        answer1 = "n";
    }

    ynListIndex++;
    return x;
}

void QuizDialog::updateLabel()
{
    setVisibleIncorrectAnswerLabel( false );
    int n = filenameList.size();
    if ((currentImageIndex < n - 1 && currentImageIndex < numberOfImages - 1) || intervalCounter == 1)
    {
        setBackgroundColor( backgroundColor );

        //intervalCounter 0 ->  Show image(s)
        //intervalCounter 1 ->  This is specifically for Image Verification
        //                      Here the user is shown the answer for a second
        //                      and the asked to verify y or n
        //intervalCounter 2 ->  Fixation interval
        switch (intervalCounter)
        {
            case 0:
                debugString = QString("%1").arg( currentImageIndex+2 ) + "|";
                loadImage(++currentImageIndex);

                if (imageLabel1->width() < image.width() || imageLabel1->height() < image.height())
                    imageLabel1->setPixmap(QPixmap::fromImage(image.scaled(imageLabel1->size(), Qt::KeepAspectRatio)));
                else
                    imageLabel1->setPixmap(QPixmap::fromImage(image));

                if (firstAttempt)
                {
                    answer1 = answerList.at(indexList[ currentImageIndex ] ).split('|').at(1);
                    image1 = answerList.at(indexList[currentImageIndex]).split('|').at(0);
                    debugString += image1 + "|";
                }
                answerLabel->setText(changeFontColor(answer1));
                if (quizOption == 2)
                {
                    if (firstAttempt)
                        randomIndex = generateRandomIndex();

                    loadImage(randomIndex);
                    answer2 = answerList.at(indexList[randomIndex]).split('|').at(1);
                    image2 = answerList.at(indexList[randomIndex]).split('|').at(0);

                    if (imageLabel2->width() < image.width() || imageLabel2->height() < image.height())
                        imageLabel2->setPixmap(QPixmap::fromImage(image.scaled(imageLabel2->size(), Qt::KeepAspectRatio)));
                else
                    imageLabel2->setPixmap(QPixmap::fromImage(image));
                }

                // If not Image Verification, wait for a while
                // and then ask the user to answer.
                if (quizOption != 3)
                    QTimer::singleShot(interval, this, SLOT(getAnswer()));
                else
                {
                    intervalCounter = 1;
                    QTimer::singleShot(interval, this, SLOT(updateLabel()));
                }
                break;
            case 1:
                if (firstAttempt)
                    randomIndex = generateRandomIndex();
                image2 = answerList.at(indexList[randomIndex]).split('|').at(0);
                answer2 = answerList.at(indexList[randomIndex]).split('|').at(1);
                debugString += image2 + "|";
                imageLabel1->setText(changeFontColor(answer2));
                QTimer::singleShot(1000, this, SLOT(getAnswer()));
                break;
            case 2:
                imageLabel1->setText(changeFontColor("+"));
                imageLabel2->setText(changeFontColor("+"));
                intervalCounter = 0;
                QTimer::singleShot(fixationInterval, this, SLOT(updateLabel()));
                break;
        }
    }
    else
    {
        timerSet = false;
        saveProgress();
    }
}

void QuizDialog::setInterval(int value)
{
    interval = value;
}

void QuizDialog::setFixationInterval(int value)
{
    fixationInterval = value;
}

void QuizDialog::setSpellingSensitivity(int value)
{
    switch(value)
    {
        case 0:
            spellingSensitivity = 1.0f;
            break;
        case 1:
            spellingSensitivity = 0.9f;
            break;
        case 2:
            spellingSensitivity = 0.8f;
            break;
        case 3:
            spellingSensitivity = 0.7f;
            break;
    }
}

void QuizDialog::setNumberOfImages(int value)
{
    switch (value)
    {
        case 0:
            numberOfImages = INT_MAX;
            break;
        case 1:
            numberOfImages = 15;
            break;
        case 2:
            numberOfImages = 20;
            break;
        case 3:
            numberOfImages = 25;
            break;
        case 4:
            numberOfImages = 30;
            break;
        case 5:
            numberOfImages = 35;
            break;
        case 6:
            numberOfImages = 40;
            break;
        case 7:
            numberOfImages = 45;
            break;
    }
}

void QuizDialog::setQuizOption(int option)
{
    quizOption = option;
    switch (quizOption)
    {
        case 0:
            answerLabel->setVisible( true );
            break;
        default:
            answerLabel->setVisible( false );
            break;
    }
}

void QuizDialog::closeEvent(QCloseEvent * e)
{
    e->ignore();
}

void QuizDialog::reject()
{
}

void QuizDialog::setUsername(QString uname)
{
    qDebug() << "set username -> " << uname;
    username = uname;
}

#ifdef APP_AMINO
void QuizDialog::setNameType(int nType)
{
    nameType = nType;
}

void QuizDialog::setImageType(QString iType)
{
    imageType = iType;
}

void QuizDialog::setPropertyType(int pType)
{
    propertyType = pType;
}

#else
void QuizDialog::setPropertyType(int pType, QString pString)
{
   propertyType = pType;
   propertyString = pString;
}
#endif

void QuizDialog::setQuizProgressReport(bool flag)
{
    viewProgressAfterQuiz = flag;
}

void QuizDialog::setTestProgressReport(bool flag)
{
    viewProgressAfterTest = flag;
}

QStringList QuizDialog::getCurrentRecords()
{
    return records;
}

QuizDialog* QuizDialog::instance(QWidget * parent)
{
    if (!s_instance)
        s_instance = new QuizDialog(parent);
    return s_instance;
}

QuizDialog::~QuizDialog()
{
}


text:
<?php

use umi\config\entity\IConfig;
use umi\config\io\IConfigIO;
use umi\hmvc\component\IComponent;
use umi\hmvc\dispatcher\IDispatcher;
use umi\hmvc\IMvcEntityFactory;
use umi\http\Request;
use umi\http\Response;
use umi\spl\config\TConfigSupport;
use umi\toolkit\IToolkit;
use umi\toolkit\Toolkit;

/**
 * Класс Bootstrap. Инициализирует приложение.
 */
class Bootstrap
{
    const OPTION_TOOLKIT = 'toolkit';
    const OPTION_SETTINGS = 'settings';
    /**
     * Символическое имя конфигурационного файла.
     */
    const GENERAL_CONFIG = '~/general.php';

    use TConfigSupport;

    /**
     * @var IToolkit $tools
     */
    protected $toolkit;
    /**
     * @var IConfig $config
     */
    protected $configuration;

    /**
     * Конструктор
     * @param array $configuration boot-конфигурация
     */
    public function __construct(array $configuration)
    {
        $this->initToolkit($configuration);
    }

    /**
     * Запускает приложение.
     */
    public function runApplication()
    {
        /**
         * @var IDispatcher $dispatcher
         */
        $dispatcher = $this->toolkit->getService('umi\hmvc\dispatcher\IDispatcher');
        $this->initTemplateEngines($dispatcher);

        /**
         * @var Request $request
         */
        $request = $this->toolkit->getService('umi\http\Request');
        $this->validateRequest($request);

        $application = $this->createApplication();

        try {
            $dispatcher->dispatch($application, $request);
        } catch (\Exception $e) {
            throw new ErrorException(
                'Unhandled exception thrown.', 0, 1, __FILE__, __LINE__, $e
            );
        }
    }

    /**
     * Возвращает toolkit.
     * @return IToolkit
     */
    protected function getToolkit()
    {
        return $this->toolkit;
    }

    /**
     * Создает компонент приложения.
     * @return IComponent
     */
    protected function createApplication()
    {
        $appConfig = $this->configToArray($this->configuration->get('application'));

        /**
         * @var IMvcEntityFactory $mvcEntityFactory
         */
        $mvcEntityFactory = $this->toolkit->getService('umi\hmvc\IMvcEntityFactory');

        return $mvcEntityFactory->createComponent('application', 'application', $appConfig);
    }

    /**
     * Задает инициализаторы для добавления расширений в шаблонизаторы
     * @param IDispatcher $dispatcher
     */
    protected function initTemplateEngines(IDispatcher $dispatcher)
    {
        //TODO
    }

    /**
     * Загружает и регистрирует конфигурацию тулбокса.
     */
    protected function initToolkit($bootConfig)
    {
        $this->toolkit = new Toolkit();

        if (isset($bootConfig[self::OPTION_TOOLKIT])) {
            $this->toolkit->registerToolboxes($bootConfig[self::OPTION_TOOLKIT]);
        }

        if (isset($bootConfig[self::OPTION_SETTINGS])) {
            $this->toolkit->setSettings($bootConfig[self::OPTION_SETTINGS]);
        }

        /**
         * @var IConfigIO $configIO
         */
        $configIO = $this->toolkit->getService('umi\config\io\IConfigIO');

        $this->configuration = $configIO->read(self::GENERAL_CONFIG);
        $this->toolkit->setSettings($this->configuration['toolkit'] ? : []);
    }

    /**
     * Проверяет необходимость редиректа и выполняет его
     * в случае наличия лишних слешей в запросе.
     * @param Request $request
     */
    protected function validateRequest(Request $request)
    {
        $pathInfo = $request->getPathInfo();

        if ($pathInfo != '/' && substr($pathInfo, -1, 1) == '/') {

            $url = rtrim($pathInfo, '/');
            if ($queryString = $request->getQueryString()) {
                $url .= '?' . $queryString;
            }
            /**
             * @var Response $response
             */
            $response = $this->toolkit->getService('umi\http\Response');
            $response->setStatusCode(Response::HTTP_MOVED_PERMANENTLY)
                ->headers->set('Location',  $request->getSchemeAndHttpHost() . $url);

            $response->send();
            exit();
        }
    }

}


text:
<Record>
<Term>Tafenoquine</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Antiparasitic Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Anti-Infective Agent/Antiparasitic Agent/Antiprotozoal Agent/Antimalarial Agent/Tafenoquine,/NCIThesaurus/Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Anti-Infective Agent/Antiparasitic Agent/Tafenoquine</ClassificationPath>
<BroaderTerm>Antiparasitic Agent</BroaderTerm>
<BroaderTerm>Tafenoquine,</BroaderTerm>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>NCIThesaurus</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Anti-Infective Agent</BroaderTerm>
<BroaderTerm>Antiprotozoal Agent</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<BroaderTerm>Tafenoquine</BroaderTerm>
<BroaderTerm>Antimalarial Agent</BroaderTerm>
<Synonym>TAFENOQUINE</Synonym>
<Synonym>Tafenoquine</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
---
layout: post
title:  "Swift, Labels, Default Parameters, oh my!"
date:   2015-02-16 10:00:00
categories: 'dalton'
tags: Swift
keywords: swift label parameter argument method function default
---

The other day I was working on [Jazz](https://github.com/daltoniam/Jazz) and got to fully appreciate the convenience of default parameters in Swift. Default parameters combined with labels gives a simple and flexible method signature. This is in stark contrast to some other method signatures in other development environments. methods in these environments can have an upwards of 10 parameters, all with arbitrary names. Let's take a look at an example of such methods:

```c
LPTSTR szCmdline[] = _tcsdup(TEXT("\"C:\\Program Files\\MyApp\" -L -S"));
CreateProcess(NULL, szCmdline, /*...*/);
```

This is an old C++ Windows API (the shock and horror). Want to guess how many parameters this method has? 2, 3, 7? This method has a total of 10 parameters. Here is the full method signature:

```
  _In_opt_     LPCTSTR lpApplicationName,
  _Inout_opt_  LPTSTR lpCommandLine,
  _In_opt_     LPSECURITY_ATTRIBUTES lpProcessAttributes,
  _In_opt_     LPSECURITY_ATTRIBUTES lpThreadAttributes,
  _In_         BOOL bInheritHandles,
  _In_         DWORD dwCreationFlags,
  _In_opt_     LPVOID lpEnvironment,
  _In_opt_     LPCTSTR lpCurrentDirectory,
  _In_         LPSTARTUPINFO lpStartupInfo,
  _Out_        LPPROCESS_INFORMATION lpProcessInformation
);

```

Now in its defense, C++ does allow for default parameters, thus making the total _required_ parameters 4. The ambiguity arises when trying to figure out what value is being passed for which parameter. Swift solves this problem by pulling in the verbosity of Objective-C by allowing parameters to be labeled. Here is an example from Jazz:

```swift
public func play(length: NSTimeInterval, delay: NSTimeInterval = 0, springDamping: CGFloat = 1, velocity: CGFloat = 1, animation:((Void) -> Void)) -> Jazz
```

This allows for the method to be simple in average use cases, but still being flexible and clear. Here is the simplest use case:

```swift
play(0.25, animation: {
    //do animations
})
```

Now let's add some delay.

```swift
play(0.25, delay: 1.0, animation: {
    //do animations
})
```

Still very clear and we get to use the same method. Let's remove the delay and change the springDamping.

```swift
play(0.25, springDamping: 0.5, animation: {
    //do animations
})
```

We know exactly which parameter we are modifying and don't have to waste time checking the documentation or method signature. Now let's set both delay and springDamping.

```swift
play(0.25, delay: 1.0, springDamping: 0.5, animation: {
    //do animations
})
```

Simple, flexible, and clear. Everything we could want from a method. It is great to see how Swift pulled in some nice features from different languages and executed them in such a way that makes the features more powerful by being combined. As always questions, comments, feedback, discussions, and random rants are appreciated. Find me at [@daltoniam](http://twitter.com/daltoniam)

- [Swift Guide: Methods](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html)


text:
service "tomcat7" do
  supports :restrart => true, :status => true, :reload => true
  action [:restart]
end