text:
/**
 * @author sunag / http://www.sunag.com.br/
 */

import { StandardNode } from './nodes/StandardNode.js';
import { NodeMaterial } from './NodeMaterial.js';
import { NodeUtils } from '../core/NodeUtils.js';

function StandardNodeMaterial() {

	var node = new StandardNode();

	NodeMaterial.call( this, node, node );

	this.type = "StandardNodeMaterial";

}

StandardNodeMaterial.prototype = Object.create( NodeMaterial.prototype );
StandardNodeMaterial.prototype.constructor = StandardNodeMaterial;

NodeUtils.addShortcuts( StandardNodeMaterial.prototype, 'fragment', [
	'color',
	'alpha',
	'roughness',
	'metalness',
	'reflectivity',
	'clearCoat',
	'clearCoatRoughness',
	'normal',
	'emissive',
	'ambient',
	'light',
	'shadow',
	'ao',
	'environment',
	'mask',
	'position'
] );

export { StandardNodeMaterial };

redpajama_set_name: RedPajamaGithub


text:
from __future__ import division

from datetime import date, datetime

from vistrails.core.system import strftime, time_strptime

class SQLDAO:
    def __init__(self):
        pass

    def convertFromDB(self, value, type, db_type):
        if value is not None:
            if type == 'str':
                return str(value)
            elif type == 'long':
                return long(value)
            elif type == 'float':
                return float(value)
            elif type == 'int':
                return int(value)
            elif type == 'date':
                if db_type == 'date':
                    return value
                else:
                    return date(*time_strptime(str(value), '%Y-%m-%d')[0:3])
            elif type == 'datetime':
                if db_type == 'datetime':
                    return value
                else:
                    return datetime(*time_strptime(str(value),
                                                   '%Y-%m-%d %H:%M:%S')[0:6])
        return None

    def convertToDB(self, value, type, db_type):
        if value is not None:
            if type == 'str':
                return "'" + str(value) + "'"
            elif type == 'long':
                return str(value)
            elif type == 'float':
                return str(value)
            elif type == 'int':
                return str(value)
            elif type == 'date':
                return "'" + value.isoformat() + "'"
            elif type == 'datetime':
                return "'" + strftime(value, '%Y-%m-%d %H:%M:%S') + "'"
            else:
                return str(value)

        return "''"

    def createSQLSelect(self, table, columns, whereMap, orderBy=None):
        columnStr = ', '.join(columns)
        whereStr = ''
        whereClause = ''
        for column, value in whereMap.iteritems():
            whereStr += '%s %s = %s' % \
                        (whereClause, column, value)
            whereClause = ' AND'
        dbCommand = """SELECT %s FROM %s WHERE %s""" % \
                    (columnStr, table, whereStr)
        if orderBy is not None:
            dbCommand += " ORDER BY " + orderBy
        return dbCommand

    def createSQLInsert(self, table, columnMap):
        columns = []
        values = []
        for column, value in columnMap.iteritems():
            if value is None:
                value = 'NULL'
            columns.append(column)
            values.append(value)
        columnStr = ', '.join(columns)
        valueStr = ', '.join(values)
        dbCommand = """INSERT INTO %s(%s) VALUES (%s)""" % \
                    (table, columnStr, valueStr)
        return dbCommand

    def createSQLUpdate(self, table, columnMap, whereMap):
        setStr = ''
        comma = ''
        for column, value in columnMap.iteritems():
            if value is None:
                value = 'NULL'
            setStr += '%s %s = %s' % (comma, column, value)
            comma = ','
        whereStr = ''
        whereClause = ''
        for column, value in whereMap.iteritems():
            whereStr += '%s %s = %s' % \
                        (whereClause, column, value)
            whereClause = ' AND'
        dbCommand = """UPDATE %s SET %s WHERE %s""" % \
                    (table, setStr, whereStr)
        return dbCommand

    def executeSQL(self, db, dbCommand, isFetch):
        # print 'dbCommand: %s' % dbCommand
        data = None
        cursor = db.cursor()
        cursor.execute(dbCommand)
        if isFetch:
            data = cursor.fetchall()
        else:
            data = cursor.lastrowid
        cursor.close()
        return data


text:
define([
    '../progression/plan'
], function (
    Plan
) {
    'use strict';

    /**
     * The DisciplineModule class is the base class for all discipline modules.
     *
     * @class
     * @alias DisciplineModule
     * @memberof Kalulu.GameLogic.Core
    **/
    function
    DisciplineModule (rafiki, staticData, userProfile) { //toto

        //console.log(staticData);

        /**
         * id of the module
         * @type {string}
         * @private
        **/
        this._id = staticData.name.toLowerCase();

        /**
         * The User Profile
         * @type {UserProfile}
         * @private
        **/
        this._userProfile = userProfile;

        /**
         * The list of activity types for each assessment
        **/
        this._assessments = this._initAssessmentsList(staticData.assessments);

        /**
         * Reference to the plan object
         * @type {Plan}
         * @private
        **/
        this._plan = new Plan(userProfile, staticData.plan, this);

        /**
         * Reference to Rafiki, the remediation engine
         * @private
        **/
        this._rafiki = rafiki;

        /**
         * List of matrices used by the module
         * @private
        **/
        this._matrices = null;

        /**
         * The player stored difficulty level. Defaults to 3 first time.
        **/
        this._difficultyLevel = 3;

        /**
         * The global remediation parameters of the latest activity started.
        **/
        this._currentActivityParams = null;

        this._minigamesRecords = {};
    }

    // ###############################################################################################################################################
    // ###  GETTERS & SETTERS  #######################################################################################################################
    // ###############################################################################################################################################

    Object.defineProperties(DisciplineModule.prototype, {

        /**
         * Returns the id of the Discipline Module
         * @type {string}
         * @memberof Kalulu.GameLogic.Core.DisciplineModule#
        **/
        id: { get: function () { return this._id; } },

        /**
         * Returns the pedagogic plan of the Discipline Module
         *
         * @type {Plan}
         * @memberof Kalulu.GameLogic.Core.DisciplineModule#
        **/
        plan: {
            get: function () {
                if (this._plan === null) {
                    console.error("[Discipline Module] Impossible to provide Plan. Please initialise DisciplineModule first.");
                    return null;
                }
                return this._plan;
            }
        },

        /**
         * Returns the list of exercise types indexed by id
         * @type {Object.<string, ExerciseType>}
         * @memberof Kalulu.GameLogic.Core.DisciplineModule#
        **/
        //exerciseTypes : { get: function () { return this._exerciseTypes; } },

        matrices : { get: function () { return this._matrices; } }
    });

    // ##############################################################################################################################################
    // ###  PUBLIC METHODS  #########################################################################################################################
    // ##############################################################################################################################################

    /**
     * @param progressionNode {ProgressionNode} the node for which we need a setup (necessary an activity node)
     * @return {object} A populated setup object for the minigame
    **/
    DisciplineModule.prototype.getActivitySetup = function getActivitySetup (progressionNode) {
        return null;
    };

    /**
     * Unlocks the first Chapter, first Lesson and first Activity of this module's plan.
    **/
    DisciplineModule.prototype.unlockPlan = function unlockPlan () {
        this._plan.isUnlocked = true;
    };

    DisciplineModule.prototype.getPedagogicData = function getPedagogicData () {
        console.warn("[Discipline module] getPedagogicData to be implemented in subclass");
        return null;
    };

    /**
     * @return {Array<boolean>} for each chapter a boolean stating the availability of the Chapter (true => isUnlocked, false => !isUnlocked)
    **/
    DisciplineModule.prototype.getChaptersProgression = function getChaptersProgression () {
        var lChaptersProgression = [];
        for (var i in this._plan.children) {
            var lChapter = this._plan.children[i];
            lChaptersProgression.push(lChapter.isUnlocked);
        }
        return lChaptersProgression;
    };

    /**
     * @return {Array<Chapter>} the list of chapters for this discipline
    **/
    DisciplineModule.prototype.getChaptersData = function getChaptersData () {
        return this._plan.children;
    };

    DisciplineModule.prototype.getDifficultyParams = function getDifficultyParams (progressionNode) {
        var level, stage;

        if (this._userProfile[progressionNode.discipline.type].minigamesRecords[progressionNode.activityType]) {
            level = this._userProfile[progressionNode.discipline.type].minigamesRecords[progressionNode.activityType].globalLevel;
            stage = this._userProfile[progressionNode.discipline.type].minigamesRecords[progressionNode.activityType].localLevel;
        }
        else {
            level = 3;
            stage = 3;
        }

        return {
            globalLevel : level,
            localStage : stage
        };
    };

    DisciplineModule.prototype.getLatestRecord = function getLatestRecord (progressionNode) {
        var arrayRecord = this._userProfile[progressionNode.discipline.type].minigamesRecords.records;

        if(arrayRecord)
            if(arrayRecord.length > 0) return arrayRecord[arrayRecord.length - 1];
        else return null;
    };

    DisciplineModule.prototype.getNotionsForLesson = function getNotionsForLesson (lessonNumber) {
        return null;
    };

    DisciplineModule.prototype.getNotionIdsForLesson = function getNotionIdsForLesson (lessonNumber) {
        return null;
    };

    DisciplineModule.prototype.getNotionsByCumul = function getNotionsByCumul (lessonNumber) {
        return null;
    };

    DisciplineModule.prototype.getAssessmentActivity = function getAssessmentActivity (chapterNumber) {
        // console.log('[DisciplineModule] Looking for activity type for chapter ' + chapterNumber + '\'s assessment');
        // console.log(this._assessments);
        return this._assessments[chapterNumber];
    };

    // ##############################################################################################################################################
    // ###  PROVATE METHODS  ########################################################################################################################
    // ##############################################################################################################################################

    DisciplineModule.prototype._initAssessmentsList = function _initAssessmentsList (csvData) {

        var assessments = {};

        for (var i = 0 ; i < csvData.length ; i++) {
            var datarow = csvData[i];
            assessments[datarow.CHAPTER] = [datarow.MINIGAME_1, datarow.MINIGAME_2];
        }

        return assessments;

    };

    return DisciplineModule;
});


text:
use super::{ExecutionStrategy,
            Scope};
use crate::{command::pkg::uninstall_impl::{self,
                                           UninstallSafety},
            error::Result};
use clap::ArgMatches;
use habitat_common::ui::UI;
use habitat_core::package::PackageIdent;
use std::path::Path;

#[derive(Clone, Copy)]
pub enum UninstallMode {
    Single,
    KeepLatest(usize),
}

impl<'a> From<&'a ArgMatches<'a>> for UninstallMode {
    fn from(m: &ArgMatches) -> Self {
        m.value_of("KEEP_LATEST")
         .and_then(|s| s.parse().ok())
         .map(Self::KeepLatest)
         .unwrap_or(Self::Single)
    }
}

pub async fn start(ui: &mut UI,
                   ident: &PackageIdent,
                   fs_root_path: &Path,
                   execution_strategy: ExecutionStrategy,
                   mode: UninstallMode,
                   scope: Scope,
                   excludes: &[PackageIdent])
                   -> Result<()> {
    match mode {
        UninstallMode::Single => {
            uninstall_impl::uninstall(ui,
                                      ident,
                                      fs_root_path,
                                      execution_strategy,
                                      scope,
                                      excludes,
                                      UninstallSafety::Safe).await
        }
        UninstallMode::KeepLatest(number_latest_to_keep) => {
            uninstall_impl::uninstall_all_but_latest(ui,
                                                     ident,
                                                     number_latest_to_keep,
                                                     fs_root_path,
                                                     execution_strategy,
                                                     scope,
                                                     excludes,
                                                     UninstallSafety::Safe).await?;
            Ok(())
        }
    }
}


text:
#ifndef MXGL_h
#define MXGL_h

#if TARGET_IOS

#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>

#elif (!(TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH))

#import <OpenGL/OpenGL.h>

// OpenGL 3.2 is only supported on MacOS X Lion and later
// CGL_VERSION_1_3 is defined as 1 on MacOS X Lion and later
#if CGL_VERSION_1_3
// Set to 0 to run on the Legacy OpenGL Profile
#define ESSENTIAL_GL_PRACTICES_SUPPORT_GL3 0
#else
#define ESSENTIAL_GL_PRACTICES_SUPPORT_GL3 0
#endif //!CGL_VERSION_1_3

#if ESSENTIAL_GL_PRACTICES_SUPPORT_GL3
#import <OpenGL/gl3.h>
#elif (!(TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH))
#import <OpenGL/gl.h>
#endif //!ESSENTIAL_GL_PRACTICES_SUPPORT_GL3

#endif // !TARGET_IOS

//The name of the VertexArrayObject are slightly different in
// OpenGLES, OpenGL Core Profile, and OpenGL Legacy
// The arguments are exactly the same across these APIs however
#if TARGET_IOS
#define glBindVertexArray glBindVertexArrayOES
#define glGenVertexArrays glGenVertexArraysOES
#define glDeleteVertexArrays glDeleteVertexArraysOES
#else
#if ESSENTIAL_GL_PRACTICES_SUPPORT_GL3
#define glBindVertexArray glBindVertexArray
#define glGenVertexArrays glGenVertexArrays
#define glGenerateMipmap glGenerateMipmap
#define glDeleteVertexArrays glDeleteVertexArrays
#else
#define glBindVertexArray glBindVertexArrayAPPLE
#define glGenVertexArrays glGenVertexArraysAPPLE
#define glGenerateMipmap glGenerateMipmapEXT
#define glDeleteVertexArrays glDeleteVertexArraysAPPLE
#endif //!ESSENTIAL_GL_PRACTICES_SUPPORT_GL3
#endif //!TARGET_IOS

static inline const char * GetGLErrorString(GLenum error)
{
  const char *str;
  switch( error )
  {
    case GL_NO_ERROR:
      str = "GL_NO_ERROR";
      break;
    case GL_INVALID_ENUM:
      str = "GL_INVALID_ENUM";
      break;
    case GL_INVALID_VALUE:
      str = "GL_INVALID_VALUE";
      break;
    case GL_INVALID_OPERATION:
      str = "GL_INVALID_OPERATION";
      break;
#if defined __gl_h_ || defined __gl3_h_
    case GL_OUT_OF_MEMORY:
      str = "GL_OUT_OF_MEMORY";
      break;
    case GL_INVALID_FRAMEBUFFER_OPERATION:
      str = "GL_INVALID_FRAMEBUFFER_OPERATION";
      break;
#endif
#if defined __gl_h_
    case GL_STACK_OVERFLOW:
      str = "GL_STACK_OVERFLOW";
      break;
    case GL_STACK_UNDERFLOW:
      str = "GL_STACK_UNDERFLOW";
      break;
    case GL_TABLE_TOO_LARGE:
      str = "GL_TABLE_TOO_LARGE";
      break;
#endif
    default:
      str = "(ERROR: Unknown Error Enum)";
      break;
  }
  return str;
}

#define MXGLError()                                     \
{                                                       \
GLenum err = glGetError();                          \
while (err != GL_NO_ERROR) {                        \
NSLog(@"GLError %s set in File:%s Line:%d\n",   \
GetGLErrorString(err), __FILE__, __LINE__);     \
err = glGetError();                             \
}                                                   \
}

#endif // __GL_UTIL_H__


text:
/* @flow */

import React, { PureComponent, Children, PropTypes } from 'react';
import {
  Animated,
  PanResponder,
  Platform,
  StyleSheet,
  View,
} from 'react-native';
import TabViewStyleInterpolator from './TabViewStyleInterpolator';
import { SceneRendererPropType } from './TabViewPropTypes';
import type { SceneRendererProps } from './TabViewTypeDefinitions';
import type { GestureEvent, GestureState } from './PanResponderTypes';

const styles = StyleSheet.create({
  sheet: {
    flexGrow: 1,
    flexDirection: 'row',
    alignItems: 'stretch',
  },
});

type DefaultProps = {
  swipeDistanceThreshold: number;
  swipeVelocityThreshold: number;
}

type Props = SceneRendererProps & {
  swipeEnabled?: boolean;
  swipeDistanceThreshold: number;
  swipeVelocityThreshold: number;
  children?: any;
}

const DEAD_ZONE = 12;

export default class TabViewPagerPan extends PureComponent<DefaultProps, Props, void> {
  static propTypes = {
    ...SceneRendererPropType,
    swipeEnabled: PropTypes.bool,
    swipeDistanceThreshold: PropTypes.number.isRequired,
    swipeVelocityThreshold: PropTypes.number.isRequired,
    children: PropTypes.node,
  };

  static defaultProps = {
    swipeDistanceThreshold: 120,
    swipeVelocityThreshold: 0.25,
  };

  componentWillMount() {
    this._panResponder = PanResponder.create({
      onMoveShouldSetPanResponder: this._canMoveScreen,
      onMoveShouldSetPanResponderCapture: this._canMoveScreen,
      onPanResponderGrant: this._startGesture,
      onPanResponderMove: this._respondToGesture,
      onPanResponderTerminate: this._finishGesture,
      onPanResponderRelease: this._finishGesture,
      onPanResponderTerminationRequest: () => true,
    });
  }

  _panResponder: Object;
  _lastValue = null;
  _isMoving = null;
  _startDirection = 0;

  _isIndexInRange = (index: number) => {
    const { routes } = this.props.navigationState;
    return (index >= 0 && index <= routes.length - 1);
  };

  _isMovingHorzontally = (evt: GestureEvent, gestureState: GestureState) => {
    return (
      (Math.abs(gestureState.dx) > Math.abs(gestureState.dy * 3)) &&
      (Math.abs(gestureState.vx) > Math.abs(gestureState.vy * 3))
    );
  };

  _isReverseDirection = (gestureState: GestureState) => {
    if (this._startDirection > 0) {
      return gestureState.vx < 0;
    } else {
      return gestureState.vx > 0;
    }
  };

  _getNextIndex = (evt: GestureEvent, gestureState: GestureState) => {
    const { index } = this.props.navigationState;

    let swipeVelocityThreshold = this.props.swipeVelocityThreshold;

    if (Platform.OS === 'android') {
      // on Android, velocity is way lower due to timestamp being in nanosecond
      // normalize it to have the same velocity on both iOS and Android
      swipeVelocityThreshold /= 1000000;
    }

    if (
      Math.abs(gestureState.dx) > this.props.swipeDistanceThreshold ||
      Math.abs(gestureState.vx) > swipeVelocityThreshold
    ) {
      const nextIndex = index - (gestureState.dx / Math.abs(gestureState.dx));
      if (this._isIndexInRange(nextIndex)) {
        return nextIndex;
      }
    }
    return index;
  };

  _canMoveScreen = (evt: GestureEvent, gestureState: GestureState) => {
    if (this.props.swipeEnabled === false) {
      return false;
    }
    const { navigationState: { routes, index } } = this.props;
    const canMove = this._isMovingHorzontally(evt, gestureState) && (
      (gestureState.dx >= DEAD_ZONE && index >= 0) ||
      (gestureState.dx <= -DEAD_ZONE && index <= routes.length - 1)
    );
    if (canMove) {
      this._startDirection = gestureState.dx;
    }
    return canMove;
  };

  _startGesture = () => {
    this._lastValue = this.props.getLastPosition();
    this.props.position.stopAnimation();
  };

  _respondToGesture = (evt: GestureEvent, gestureState: GestureState) => {
    const { layout: { width } } = this.props;
    const currentPosition = typeof this._lastValue === 'number' ? this._lastValue : this.props.navigationState.index;
    const nextPosition = currentPosition - (gestureState.dx / width);
    if (this._isMoving === null) {
      this._isMoving = this._isMovingHorzontally(evt, gestureState);
    }
    if (this._isMoving && this._isIndexInRange(nextPosition)) {
      this.props.position.setValue(nextPosition);
    }
  };

  _finishGesture = (evt: GestureEvent, gestureState: GestureState) => {
    const currentIndex = this.props.navigationState.index;
    const currentValue = this.props.getLastPosition();
    if (currentValue !== currentIndex) {
      if (this._isMoving && !this._isReverseDirection(gestureState)) {
        const nextIndex = this._getNextIndex(evt, gestureState);
        this.props.jumpToIndex(nextIndex);
      } else {
        this.props.jumpToIndex(currentIndex);
      }
    }
    this._lastValue = null;
    this._isMoving = null;
  };

  render() {
    const { navigationState, layout } = this.props;
    const { routes } = navigationState;

    const style = TabViewStyleInterpolator.forHorizontal(this.props);

    return (
      <Animated.View style={[ styles.sheet, style, { width: layout.width * routes.length } ]} {...this._panResponder.panHandlers}>
        {Children.map(this.props.children, (child, i) => (
          <View
            key={navigationState.routes[i].key}
            testID={navigationState.routes[i].testID}
            style={{ width: layout.width }}
          >
            {child}
          </View>
        ))}
      </Animated.View>
    );
  }
}


text:
<?php
ob_start();

$title="experiment mainpage";

include ("header.php");

	if (!$_REQUEST['experiment_id']) redirect ("admin/");
		else $experiment_id=$_REQUEST['experiment_id'];

	$allow=check_allow('experiment_show','experiment_main.php');

	// load experiment data into array experiment
    	$experiment=orsee_db_load_array("experiments",$experiment_id,"experiment_id");

	echo '

'.$experiment['experiment_name'].'

		';

	show_message();

// show basic settings

	echo '

'.$lang['basic_data'].'

'.$lang['id'].':	'.$experiment['experiment_id'].'

'.$lang['name'].':	'.$experiment['experiment_name'].'

'.$lang['public_name'].':	'.$experiment['experiment_public_name'].'

'.$lang['type'].':
		'.$lang[$experiment['experiment_type']].' ('.$experiment['experiment_ext_type'].')

'.$lang['class'].':
			'.experiment__get_experiment_class_names($experiment['experiment_class']).'

'.$lang['description'].':	'.$experiment['experiment_description'].'

'.$lang['experimenter'].':	'.experiment__list_experimenters($experiment['experimenter'],true,true).
			'

'.$lang['get_emails'].':	'.experiment__list_experimenters($experiment['experimenter_mail'],true,true).
			'

'.$lang['email_sender_address'].':	'.$experiment['sender_mail'].'

		';

	if ($experiment['experiment_type']=="laboratory") {
		echo '
'.$lang['from'].':
			'.sessions__get_first_date($experiment['experiment_id']).'

'.$lang['to'].':
			'.sessions__get_last_date($experiment['experiment_id']).'
';
		}
	if (downloads__files_downloadable($experiment['experiment_id'])) {
			echo '
'.$lang['files'].':
				';
			downloads__list_files($experiment['experiment_id']);
			echo '
';
			}

	// does the following make sense? we order them on different pages! OK, but this is the
	// experiment show page. Maybe the user has forgotten ... ;-)
	if ($experiment['experiment_type']=="laboratory") {
		echo '
';
		if ($experiment['experiment_finished']=="y")
			echo $lang['experiment_finished'];
		   else echo $lang['experiment_not_finished'];
		echo '
';
		}

	echo '

		'.$lang['options'].':

';
					if (check_allow('experiment_edit')) echo '
						'.
							$lang['edit_basic_data'].'';
	echo '					';
					if (check_allow('download_experiment_upload')) {
					echo ''.
						$lang['upload_file'].' ';
 					echo help('upload_files');
					}
	echo '

	';

	if ($experiment['experiment_type']=="laboratory") {
	// session summary

	echo '

'.$lang['sessions'].'

				'.experiment__count_sessions($experiment['experiment_id']).' '.
				$lang['xxx_sessions_registered'].'

';

     	$query="SELECT *
      		FROM ".table('sessions')."
        	WHERE experiment_id='".$experiment['experiment_id']."'
      		ORDER BY session_start_year, session_start_month, session_start_day,
		 session_start_hour, session_start_minute";
	$done=orsee_query($query,"sessions__format_alist");

	echo '

				'.$lang['options'].':

			';
				if (check_allow('session_edit')) echo '
					'.
					$lang['create_new'].'';
	echo '

		';

}

/*

<when <string-eq '.$experiment['experiment_type'].' "online-survey">>
////////////////////////////////////////////////;;
// Experiment-Daten in Package experiment laden
////////////////////////////////////////////////;
<sql::with-open-database db dsn=<site::dsn> nolock=true>
  <set-var loaded?=<sql::database-load-record db <get-var posted::experiment_id> TABLE=os_properties KEYNAME=experiment_id PACKAGE=os>>
</sql::with-open-database>
//------------------------------------------------------------------------

<set-var os::results=<os::any-results? '.$experiment['experiment_id'].'>>

'.$lang['os_properties'].'

<when <get-var loaded?>>

'.$lang['description'].':	<get-var os::public_description>

'.$lang['from'].':	<time::format year=<get-var os::start_year> month=<get-var os::start_month> day=<get-var os::start_day> hour=<get-var os::start_hour> minute=<get-var os::start_minute> hide_second=true>

'.$lang['to'].':	<time::format year=<get-var os::stop_year> month=<get-var os::stop_month> day=<get-var os::stop_day> hour=<get-var os::stop_hour> minute=<get-var os::stop_minute> hide_second=true>

</when>

'.$lang['window_size'].':	<get-var os::window_size_x>x<get-var os::window_size_y>

'.$lang['options'].':

'.$lang['edit_os_properties'].'

<defun make-page-link page>
	<when <string-eq <get-var os::<get-var page>> "y">>
		<A HREF="os_extra_pages_edit.php?experiment_id='.$experiment['experiment_id'].'&page_name=<get-var page>"><%%eval '.$lang[edit_<get-var page].'>>

	</when>
</defun>
<make-page-link introduction>
<make-page-link instructions>
<make-page-link final_page>

'.$lang['test_whole_online_survey'].'

<when <string-eq <get-var os::data_form> "y">>
////////////////////////////////////////////////;;
// Experiment-Daten in Package experiment laden
////////////////////////////////////////////////;
<sql::with-open-database db dsn=<site::dsn> nolock=true>
  <set-var loaded?=<sql::database-load-record db <get-var posted::experiment_id> TABLE=os_data_form KEYNAME=experiment_id PACKAGE=os_data>>
</sql::with-open-database>
//------------------------------------------------------------------------

'.$lang['os_personal_data_form'].'

'.$lang['position'].':

<if <get-var os_data::position> <group <if <string-eq <get-var os_data::position> "e"> '.$lang['at_end'].' '.$lang['at_start'].'>> <concat "???">>

'.$lang['options'].':

'.$lang['edit_os_data_form'].'

</when>

<include ../scripts/open_os_question_js.php>

'.$lang['questions'].'

<if <survey::random-order? experiment_id='.$experiment['experiment_id'].'>
				'.$lang['presented_in_random_order'].'
				'.$lang['presented_ordered_by_number'].'>

// question list
////////////////////////////////////////
// daten ausgeben
<sql::with-open-database db dsn=<site::dsn> nolock=true>
    <sql::database-query
     db true
     "SELECT *
      FROM os_questions
        WHERE experiment_id='.$experiment['experiment_id'].'
      ORDER BY question_order"
       format =<survey::questions-format-alist <package-to-alist>>>
</sql::with-open-database>

'.$lang['options'].':

'.$lang['create_new'].'

<when <gt <survey::count-questions '.$experiment['experiment_id'].'> 1>>
'.$lang['order_questions'].'
</when>

</when>

*/

// participant summary for laboratory experiments
	if ($experiment['experiment_type']=="laboratory") {

		$allow_sp=check_allow('experiment_show_participants'); // show links to participant lists?

		echo '

'.$lang['participants'].'

				';
					if ($allow_sp) echo '';
					echo $lang['assigned_subjects'];
					if ($allow_sp) echo '';
					echo ':
					'.help('assigned_subjects').'

					'.experiment__count_participate_at($experiment['experiment_id']).'

				';
					if ($allow_sp) echo '';
					echo $lang['invited_subjects'];
					if ($allow_sp) echo '';
					echo ':
					'.help('invited_subjects').'

					'.experiment__count_invited($experiment['experiment_id']).'

				';
					if ($allow_sp) echo '';
					echo $lang['registered_subjects'];
					if ($allow_sp) echo '';
					echo ':
					'.help('registered_subjects').'

					'.experiment__count_registered($experiment['experiment_id']).'

				';
					if ($allow_sp) echo '';
					echo $lang['shownup_subjects'];
					if ($allow_sp) echo '';
					echo ':
					'.help('shownup_subjects').'

					'.experiment__count_shownup($experiment['experiment_id']).'

				';
					if ($allow_sp) echo '';
					echo $lang['subjects_participated'];
					if ($allow_sp) echo '';
					echo ':
					'.help('subjects_participated').'

					'.experiment__count_participated($experiment['experiment_id']).'

					'.$lang['options'].':

';
			if (check_allow('experiment_assign_participants')) echo '

					'.$lang['assign_subjects'].'

					'.
					$lang['delete_assigned_subjects'].'

';
		echo '

				';
					if (check_allow('experiment_invitation_edit')) echo '
						'.$lang['send_invitations'].'
';
		echo '

			';
		}

/*

//////////////////////////////////////////;;
// participant summary for online-survey experiments
////////////////////////////////////////;
<when <string-eq '.$experiment['experiment_type'].' "online-survey">>

'.$lang['participants'].'

'.$lang['assigned'].'
'.$lang['invited'].'
'.$lang['participated'].'
'.$lang['finished'].'
'.$lang['dataform'].'
'.$lang['to_subpool'].'

// row for participants from subject pool

		'.$lang['participants_from_subject_pool'].'

		<experiment::count-participate_at '.$experiment['experiment_id'].'>

		<experiment::count-invited '.$experiment['experiment_id'].'>

		<experiment::count-participated '.$experiment['experiment_id'].'>

		<survey::count-finished '.$experiment['experiment_id'].' reg="n">

		'.$lang['free_registration'].'

		<survey::count-free-reg '.$experiment['experiment_id'].'>

		<survey::count-finished '.$experiment['experiment_id'].' reg="y">

		<survey::count-dataform '.$experiment['experiment_id'].'>

		<survey::count-joined-subpool '.$experiment['experiment_id'].'>

'.$lang['options'].':

'.$lang['assign_subjects'].'

'.$lang['delete_assigned_subjects'].'

'.$lang['send_invitations'].'

</when>

//////////////////////////////////////////;;
// results summary  and results options for online-survey experiments
////////////////////////////////////////;
<when <string-eq '.$experiment['experiment_type'].' "online-survey">>

Results

'.$lang['options'].':

'.$lang['download_decision_data'].'

'.$lang['download_participant_data'].'

</when>

*/

include ("footer.php");

?>


text:
cask 'calibre' do
  if MacOS.release <= :lion
    version '1.48.0'
    sha256 '0533283965fbc9a6618d0b27c85bdf3671fe75ff0e89eeff406fe1457ee61b14'
  else
    version '2.55.0'
    sha256 '59ccc8a3911d66d1dec4753b1767b56c15572debeeb03807b3cdff50e383833c'
    appcast 'https://github.com/kovidgoyal/calibre/releases.atom',
            checkpoint: '9f5892de1350f03aaa8eb6f951dbdea22854dd350c098b2c4cb736bddcaaed1e'
  end

  url "https://download.calibre-ebook.com/#{version}/calibre-#{version}.dmg"
  name 'calibre'
  homepage 'https://calibre-ebook.com/'
  license :gpl

  app 'calibre.app'
  binary 'calibre.app/Contents/MacOS/calibre'
  binary 'calibre.app/Contents/MacOS/calibre-complete'
  binary 'calibre.app/Contents/MacOS/calibre-customize'
  binary 'calibre.app/Contents/MacOS/calibre-debug'
  binary 'calibre.app/Contents/MacOS/calibre-parallel'
  binary 'calibre.app/Contents/MacOS/calibre-server'
  binary 'calibre.app/Contents/MacOS/calibre-smtp'
  binary 'calibre.app/Contents/MacOS/calibredb'
  binary 'calibre.app/Contents/MacOS/ebook-convert'
  binary 'calibre.app/Contents/MacOS/ebook-device'
  binary 'calibre.app/Contents/MacOS/ebook-edit'
  binary 'calibre.app/Contents/MacOS/ebook-meta'
  binary 'calibre.app/Contents/MacOS/ebook-polish'
  binary 'calibre.app/Contents/MacOS/ebook-viewer'
  binary 'calibre.app/Contents/MacOS/fetch-ebook-metadata'
  binary 'calibre.app/Contents/MacOS/lrf2lrs'
  binary 'calibre.app/Contents/MacOS/lrfviewer'
  binary 'calibre.app/Contents/MacOS/lrs2lrf'
  binary 'calibre.app/Contents/MacOS/markdown-calibre'
  binary 'calibre.app/Contents/MacOS/web2disk'

  zap delete: [
                '~/Library/Preferences/net.kovidgoyal.calibre.plist',
                '~/Library/Preferences/calibre',
                '~/Library/Caches/calibre',
              ]
end


text:
package se.oyabun.criters.test.data;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;

/**
 * Test entity Baz
 * Neutrally compliant with javax persistence API to enable reuse for different implementations
 *
 * @author Daniel Sundberg
 */
@Entity
public class Baz {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String value;

    @OneToOne
    private Bar bar;

    public long getId() {

        return id;
    }

    public void setId(final long id) {

        this.id = id;
    }

    public Bar getBar() {

        return bar;

    }

    public void setBar(Bar bar) {

        this.bar = bar;

    }

    public String getValue() {

        return value;
    }

    public void setValue(final String value) {

        this.value = value;
    }

    @Override
    public boolean equals(final Object o) {

        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final Baz baz = (Baz) o;

        return new EqualsBuilder().append(id,
                                          baz.id)
                                  .isEquals();
    }

    @Override
    public int hashCode() {

        return new HashCodeBuilder(17,
                                   37).append(id)
                                      .toHashCode();
    }
}


text:
package org.onosproject.bgpio.types.attr;

import org.junit.Test;

import com.google.common.testing.EqualsTester;

/**
 * Test for Link attribute name Tlv.
 */
public class BgpLinkAttrNameTest {
    private final byte[] array = new byte[] {0x01, 0x02, 0x03, 0x04};
    private final byte[] array1 = new byte[] {0x01, 0x02, 0x03, 0x01};

    private final BgpLinkAttrName isisData = BgpLinkAttrName.of(array);
    private final BgpLinkAttrName sameAsIsisData = BgpLinkAttrName.of(array);
    private final BgpLinkAttrName isisDiff = BgpLinkAttrName.of(array1);

    @Test
    public void basics() {
        new EqualsTester().addEqualityGroup(isisData, sameAsIsisData)
                .addEqualityGroup(isisDiff).testEquals();
    }
}


text:
output = """
Interface                  IP-Address      OK? Method Status                Protocol
FastEthernet0              unassigned      YES unset  down                  down
FastEthernet1              unassigned      YES unset  down                  down
FastEthernet2              unassigned      YES unset  down                  down
FastEthernet3              unassigned      YES unset  down                  down
FastEthernet4              10.220.88.20    YES NVRAM  up                    up
Vlan1                      unassigned      YES unset  down                  down   """

lines = output.splitlines()
for line in lines:
    if '10.220.88.20' in line:
        print line


text: module.exports = require('jsss-contextual');


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Threading.Tasks

Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Expansion
    Public Class NameExpansionTests
        Inherits AbstractExpansionTest

#Region "C# Tests"

        <WorkItem(604392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604392")>
        <Fact, Trait(Traits.Feature, Traits.Features.Expansion)>
        Public Async Function TestNoExpansionForPropertyNamesOfObjectInitializers() As Task
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class Program
{
    static void Main()
    {
        int z = 1;
        var c = new C { {|Expand:X|} = { Y = { z } } };
    }
}

class C
{
    public dynamic X;
}
        </Document>
    </Project>
</Workspace>

            Dim expected =

class Program
{
    static void Main()
    {
        int z = 1;
        var c = new C { X = { Y = { z } } };
    }
}

class C
{
    public dynamic X;
}

            Await TestAsync(input, expected)
        End Function

        <WorkItem(1913, "https://github.com/dotnet/roslyn/issues/1913")>
        <Fact, Trait(Traits.Feature, Traits.Features.Expansion)>
        Public Async Function TestCSharp_SimpleIdentifierAliasExpansion_AliasBinds() As Task
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;
namespace NS
{
    using Short = LongNamespace;
    class Test
    {
        public object Method1()
        {
            return (new {|Expand:Short|}.MyClass()).Prop;
        }
    }
}
namespace LongNamespace
{
    public class MyClass
    {
        public object Prop { get; }
    }
}
        </Document>
    </Project>
</Workspace>

            Dim expected =

using System;
namespace NS
{
    using Short = LongNamespace;
    class Test
    {
        public object Method1()
        {
            return (new global::LongNamespace.MyClass()).Prop;
        }
    }
}
namespace LongNamespace
{
    public class MyClass
    {
        public object Prop { get; }
    }
}

            Await TestAsync(input, expected)
        End Function

        <WorkItem(1913, "https://github.com/dotnet/roslyn/issues/1913")>
        <Fact, Trait(Traits.Feature, Traits.Features.Expansion)>
        Public Async Function TestCSharp_SimpleIdentifierAliasExpansion_AliasDoesNotBind() As Task
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;
namespace NS
{
    using Short = LongNamespace;
    class Test
    {
        public object Method1()
        {
            return (new {|Expand:Short|}.MyClass()).Prop;
        }
    }
}
        </Document>
    </Project>
</Workspace>

            Dim expected =

using System;
namespace NS
{
    using Short = LongNamespace;
    class Test
    {
        public object Method1()
        {
            return (new LongNamespace.MyClass()).Prop;
        }
    }
}

            Await TestAsync(input, expected)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.Expansion)>
        Public Async Function TestCSharp_GenericNameExpansion_DontExpandAnonymousTypes() As Task
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
class C
{
    static void Mumble<T>(T anonymousType) { }

    static void M()
    {
        {|Expand:Mumble|}(new { x = 42 });
    }
}
        </Document>
    </Project>
</Workspace>

            Dim expected =

class C
{
    static void Mumble<T>(T anonymousType) { }

    static void M()
    {
        global::C.Mumble(new { x = 42 });
    }
}

            Await TestAsync(input, expected)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.Expansion)>
        Public Async Function TestCSharp_LambdaParameter_DontExpandAnonymousTypes1() As Task
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;
class C
{
    static void Mumble<T>(T anonymousType, Action<T, int> lambda) { }

    static void M()
    {
        Mumble(new { x = 42 }, {|Expand:a => a.x|});
    }
}
        </Document>
    </Project>
</Workspace>

            Dim expected =

using System;
class C
{
    static void Mumble<T>(T anonymousType, Action<T, int> lambda) { }

    static void M()
    {
        Mumble(new { x = 42 }, a => a.x);
    }
}

            Await TestAsync(input, expected, expandParameter:=True)
        End Function

        <Fact, Trait(Traits.Feature, Traits.Features.Expansion)>
        Public Async Function TestCSharp_LambdaParameter_DontExpandAnonymousTypes2() As Task
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document>
using System;
class C
{
    static void Mumble<T>(T anonymousType, Action<T, int, int> lambda) { }

    static void M()
    {
        Mumble(new { x = 42 }, {|Expand:(a, y) => a.x|});
    }
}
        </Document>
    </Project>
</Workspace>

            Dim expected =

using System;
class C
{
    static void Mumble<T>(T anonymousType, Action<T, int, int> lambda) { }

    static void M()
    {
        Mumble(new { x = 42 }, (a, y) => a.x);
    }
}

            Await TestAsync(input, expected, expandParameter:=True)
        End Function

#End Region

#Region "Visual Basic tests"

        <WorkItem(1913, "https://github.com/dotnet/roslyn/issues/1913")>
        <Fact, Trait(Traits.Feature, Traits.Features.Expansion)>
        Public Async Function TestVisualBasic_SimpleIdentifierAliasExpansion_AliasBinds() As Task
            Dim input =
<Workspace>
    <Project Language="Visual Basic" CommonReferences="true">
        <Document>
Imports System
Imports ShortName = LongNamespace
Namespace NS
    Class Test
        Public Function Method1() As Object
            Return (New {|Expand:ShortName|}.Class1()).Prop
        End Function
    End Class
End Namespace
Namespace LongNamespace
    Public Class Class1
        Public Readonly Property Prop As Object
            Get
                Return Nothing
            End Get
        End Property
    End Class
End Namespace
        </Document>
    </Project>
</Workspace>

            Dim expected =

Imports System
Imports ShortName = LongNamespace
Namespace NS
    Class Test
        Public Function Method1() As Object
            Return (New Global.LongNamespace.Class1()).Prop
        End Function
    End Class
End Namespace
Namespace LongNamespace
    Public Class Class1
        Public Readonly Property Prop As Object
            Get
                Return Nothing
            End Get
        End Property
    End Class
End Namespace

            Await TestAsync(input, expected)
        End Function

        <WorkItem(1913, "https://github.com/dotnet/roslyn/issues/1913")>
        <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/2805"), Trait(Traits.Feature, Traits.Features.Expansion)>
        Public Async Function TestVisualBasic_SimpleIdentifierAliasExpansion_AliasDoesNotBind() As Task
            Dim input =
<Workspace>
    <Project Language="Visual Basic" CommonReferences="true">
        <Document>
Imports System
Imports ShortName = LongNamespace
Namespace NS
    Class Test
        Public Function Method1() As Object
            Return (New {|Expand:ShortName|}.Class1()).Prop
        End Function
    End Class
End Namespace
        </Document>
    </Project>
</Workspace>

            Dim expected =

Imports System
Imports ShortName = LongNamespace
Namespace NS
    Class Test
        Public Function Method1() As Object
            Return (New LongNamespace.Class1()).Prop
        End Function
    End Class
End Namespace

            Await TestAsync(input, expected)
        End Function

#End Region

    End Class
End Namespace


text:
type edge.js > out.js
type vertex.js >> out.js
REM Google Closure Compiler to minify js
java -jar compiler.jar --js out.js --js_output_file mavis3d.min.js
REM Unminified copy
type out.js > mavis3d.js
del out.js
pause


text:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';
import { UserService } from '../../services/user.service';

@Component({
    templateUrl: 'app/components/account/account-password-page.component.html'
})
export class AccountPasswordPageComponent implements OnInit {
    user: any;
    form: FormGroup;
    formSubmitted: boolean;
    passwords: any;

    constructor(
        private _router: Router,
        private _authService: AuthService,
        private _userService: UserService
    ) { }

    ngOnInit() {
        this.passwords = {
            oldPassword: '',
            newPassword: '',
            confirmPassword: ''
        };

        let currentPasswordValidator = (c: FormControl) => {
            return this.user && c.value === this.user.password ? null : {
                passwordIncorect: 'password is incorrect'
            };
        };

        let confirmPasswordValidator = (c: FormControl) => {
            return c.value === this.passwords.newPassword ? null : {
                mustMatch: 'passwords must match'
            };
        };

        this.form = new FormGroup({
            oldPassword: new FormControl('', [Validators.required, currentPasswordValidator]),
            newPassword: new FormControl('', Validators.required),
            confirmPassword: new FormControl('', [Validators.required, confirmPasswordValidator])
        });

        let currentUser = this._authService.getCurrentUser();
        this._userService.getById(currentUser._id)
            .then(user => this.user = user);
    }

    cancel() {
        this._router.navigate(['/account']);
    }

    save() {
        this.formSubmitted = true;
        if (this.form.valid) {
            this.user.password = this.passwords.newPassword;
            this._authService.updateUser(this.user)
                .then(success => {
                    if (success) {
                        this._router.navigate(['/account']);
                    } else {
                        console.log('user update failed');
                    }
                });
        }
    }
}


text:
var Promise = require('bluebird');
var _ = require('lodash');
var generateName = require('sillyname');
var debounce = _.debounce;
var observer = require('../observer');

module.exports = exports = function lastModifiedPlugin(schema, options) {
    schema.plugin(require('./_common_helper'), options);

    schema.methods.findOrAssign = function(userId) {
        var Quest = this.db.model('Quest');
        return Quest.findOrAssign(this, userId);
    };
    schema.methods.findOrAssignMany = function(userIds) {
        var Quest = this.db.model('Quest');
        var quest = this;
        return Promise.map(userIds, function (uid) {
            return Quest.findOrAssign(quest, uid);
        }).then(function (uqs) {
            return uqs;
        });
    };

    /**
     * Assign quest to user or updates requirements if already assigned
     * @param  {ObjectId} userId  [description]
     * @param  {Quest} quest [description]
     * @return {UserQuest}       [description]
     */
    schema.statics.findOrAssign = function(quest, userId) {
        if(!quest.isPublished) return Promise.reject('You can not assign an Un-Published quest');
        var UserQuest = this.db.model('UserQuest');
        return Promise.fulfilled().then(function() {
            return UserQuest.findOne({
                quest: quest.id,
                user: userId
            }).exec();
        }).then(function (uq) {
            if(uq) return uq;
            return UserQuest.create({
                name:quest.name,
                description:quest.description,
                rp:quest.rp,
                quest: quest.id,
                user: userId
            });
        }).then(function (uq) {
            observer.emit('quest.join', uq);
            return uq.setRequirements(quest.requirements);
        });
    };

    schema.statics.getById = function(id) {
        var Quest = this.db.model('Quest');
        return Promise.fulfilled().then(function() {
            return Quest.findOne({
                _id: id
            }).exec();
        });
    };
    schema.statics.getById_404 = function(id) {
        var Quest = this.db.model('Quest');
        return Quest.getById(id).then(function(g) {
            if (!g) throw {
                http_code: 404,
                message: "Not Found"
            };
            return g;
        });
    };

    schema.statics.findOrCreate = function(memb) {
        var Quest = this.db.model('Quest');
        return Promise.fulfilled().then(function () {
            return Quest.findOne({group:memb.group, user:memb.user}).exec();
        }).then(function(m) {
            if (m) return m;
            return Quest.create(memb);
        });
    };

    schema.statics.getGroups = function(user) {
        var Quest = this.db.model('Quest');
        return Promise.fulfilled().then(function() {
            return Quest.find({
                user: user.id
            }).populate('group').exec();
        }).then(function (memeberships) {
            return _.map(memeberships, 'group');
        });
    };

};


text:
namespace net {

base::Value NetLogURLRequestConstructorParams(
    const GURL& url,
    RequestPriority priority,
    NetworkTrafficAnnotationTag traffic_annotation) {
  base::Value dict(base::Value::Type::DICTIONARY);
  dict.SetStringKey("url", url.possibly_invalid_spec());
  dict.SetStringKey("priority", RequestPriorityToString(priority));
  dict.SetIntKey("traffic_annotation", traffic_annotation.unique_id_hash_code);
  return dict;
}

base::Value NetLogURLRequestStartParams(
    const GURL& url,
    const std::string& method,
    int load_flags,
    const IsolationInfo& isolation_info,
    const SiteForCookies& site_for_cookies,
    const absl::optional<url::Origin>& initiator,
    int64_t upload_id) {
  base::Value dict(base::Value::Type::DICTIONARY);
  dict.SetStringKey("url", url.possibly_invalid_spec());
  dict.SetStringKey("method", method);
  dict.SetIntKey("load_flags", load_flags);
  dict.SetStringKey("network_isolation_key",
                    isolation_info.network_isolation_key().ToDebugString());
  std::string request_type;
  switch (isolation_info.request_type()) {
    case IsolationInfo::RequestType::kMainFrame:
      request_type = "main frame";
      break;
    case IsolationInfo::RequestType::kSubFrame:
      request_type = "subframe";
      break;
    case IsolationInfo::RequestType::kOther:
      request_type = "other";
      break;
  }
  dict.SetStringKey("request_type", request_type);
  dict.SetStringKey("site_for_cookies", site_for_cookies.ToDebugString());
  dict.SetStringKey("initiator", initiator.has_value() ? initiator->Serialize()
                                                       : "not an origin");
  if (upload_id > -1)
    dict.SetStringKey("upload_id", base::NumberToString(upload_id));
  return dict;
}

}  // namespace net


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

body {
    background: #FAFAFA;
    margin: 0px;
   font-family: "Open Sans", sans-serif;

}

#header {
    height: 30px;
    background-color: #353735;
    padding: 0 10px 0 10px;
}

#footer {
    padding: 9px 10px 10px 10px;
    text-align: center;
    border:0;
    width: 100%;
    height: 9px;
    position: fixed;
    bottom: 0;
    font-size: 10.4px;
}

#footer a {
  color: #2ba6cb;
  text-decoration: none;
  line-height: inherit;
    font-size:      13px;
}

#logo {
    padding-top: 6px;
    font-size: 1.1em;
    font-weight: bold;
    color: white;
    font-family:    Arial, Verdana, Geneva, Helvetica, sans-serif;
    font-size:      13px;
}

#wrapper{
    margin-left: auto;
    margin-right: auto;
    width: 900px;
    text-align: center;
}

div#logo_sunstone {
    position: relative;
    height: 200px;
    width: 800px;
    top: 65px;
    margin-left: auto;
    margin-right: auto;
    vertical-align: center;
}

div#login {
    width: 400px;
    height: 300px;
    position: relative;

    margin-left: auto;
    margin-right: auto;
    top: 30px;
    padding-left: 80px;
    padding-right: 80px;
    background: url(../images/panel.png) no-repeat center ;

    vertical-align: center;
}

.box {
    font-size:0.8em;
    width: 300px;
    height: 25px;
    background: #FFFFFF;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 10px;
    border-bottom-color: gray;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
    border-bottom-style: solid;
    border-bottom-width: 1px;
    border-left-color: gray;
    border-left-style: solid;
    border-left-width: 1px;
    border-right-color: gray;
    border-right-style: solid;
    border-right-width: 1px;
    border-top-color: gray;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    border-top-style: solid;
    border-top-width: 1px;
    -moz-border-radius: 5px;
    -moz-border-radius-topleft: 5px;
    -moz-border-radius-topright: 5px;
    -moz-border-radius-bottomright: 5px;
    -moz-border-radius-bottomleft: 5px;
}

div#login input#login_btn {
    width: 130px;
    height: 45px;
    cursor: pointer;
    margin-left: auto;
    margin-right: 43px;
    margin-top: 20px;
    background-color: transparent;
    border:0;
    float: right;
    background:  url(../images/login.png) no-repeat center ;
}

div#login input#login_btn:hover {
  width: 130px;
  height: 45px;
  cursor: pointer;
  margin-left: auto;
  margin-right: 43px;
  margin-top: 20px;
  background-color: transparent;
  border:0;
  float: right;
  background:  url(../images/login_over.png) no-repeat center ;
}

#login_spinner {
    left: 22px;
    position: relative;
    top: 2px;
}

#label_remember {
  color:#353735;
  font-size:0.4em;
  font-family: Arial, Helvetica, sans-serif;
}

.content {
  padding-top:40px;
  font-size:1.8em;
  margin-bottom:0px;
  margin-left:50px;
  text-align:left;
  font-family: Arial, Helvetica, sans-serif;
}

#check_remember {

  margin-top: 35px;
  margin-left:0px;
}

div.alert-box {
  display: block;
  padding: 6px 7px 7px;
  font-size: 14px;
  color: white;
  background-color: #2ba6cb;
  border: 1px solid rgba(0, 0, 0, 0.1);
  margin-bottom: 12px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  -ms-border-radius: 3px;
  -o-border-radius: 3px;
  border-radius: 3px;
  text-shadow: 0 -1px rgba(0, 0, 0, 0.3);
  position: relative;
  font-family: Arial, Helvetica, sans-serif;
}

div.alert-box.alert {
  background-color: #c0392b;
  color: #fff;
  text-shadow: 0 -1px rgba(0, 0, 0, 0.3);
}

div.alert-box a.close {
  color: #333;
  position: absolute;
  right: 4px;
  top: -1px;
  font-size: 17px;
  opacity: 0.2;
  padding: 4px;
}
/* line 34, ../../../../../../../.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/zurb-foundation-3.2.5/scss/foundation/components/modules/_ui.scss */
div.alert-box a.close:hover, div.alert-box a.close:focus {
  opacity: 0.4;
}

#error_box {
  margin-top:70px;
}


text:
/*global app, confirm, mod*/

mod.controller('overviewController', ['logger', 'subscriptionHandler', 'settings', '$filter', 'notification',
    function (logger, subscriptionHandler, settings, $filter, notification) {
      'use strict';

      // continuous access to caller and some important objects
      var that = this;

      // list of subscription infos
      that.subscriptions = [];

      // map of subscription names to episode infos
      that.newEpisodes = {};

      /**
       * Gets the number of days that have passed since the specified date.
       * @param {Date} date - Reference date from which the days difference is calculated.
       * @returns {Number} The number of days since the specified date.
       */
      that.getNumberOfDaysSinceDate = function (date) {
        return (new Date().getTime() - new Date(date).getTime()) / 1000 / 3600 / 24;
      };

      // public methods

      /**
       * Retrieves updates for one subscription.
       * @param {String} subscriptionName - Name of the subscription for which to find updates.
       */
      that.findSubscriptionUpdates = function (subscriptionName) {
        subscriptionHandler.findSubscriptionUpdates(subscriptionName)
          .then(function (response) {
            handleSubscriptionUpdatesResponse(response, subscriptionName);

            // because the last update date changed, retrieve the subscription again
            getSubscription(subscriptionName);
          })
        .catch(function (err) {
          notification.show('Error ' + err.status + ' while requesting updates for subscription ' + subscriptionName + ':\n' + (err.data || {}).message);
        });
      };

      /**
       * Retrieves links to download the last episode for one subscription.
       * @param {String} subscriptionName - Name of the subscription for which to find downloads.
       */
      that.findSubscriptionLastEpisode = function (subscriptionName, currentEpisode) {
        subscriptionHandler.findSubscriptionLastEpisode(subscriptionName, currentEpisode)
          .then(function (response) {
            handleSubscriptionUpdatesResponse(response, subscriptionName);

            // because the last episode and update date changed, retrieve the subscription again
            getSubscription(subscriptionName);
          })
        .catch(function (err) {
          notification.show('Error ' + err.status + ' while requesting last episode for subscription ' + subscriptionName + ':\n' + (err.data || {}).message);
        });
      };

      /**
       * Retrieves subscription updates for all subscriptions.
       */
      that.findAllSubscriptionUpdates = function () {
        notification.show('Checking for updates for all subscriptions...');
        that.subscriptions.forEach(function (sub) {
          that.findSubscriptionUpdates(sub.name);
        });
      };

      /**
       * Tells the server to start the download of a specific episode.
       * @param {String} subscriptionName - Name of the subscription to which the episode belongs.
       * @param {Object} episodeInfo - Container for information about the episode to download.
       * @param {Number} episodeInfo.season - Number of the season of the episode.
       * @param {Number} episodeInfo.episode - Number of the episode.
       * @param {String} episodeInfo.link - Link of the torrent to download.
       * @param {Boolean} [episodeInfo.isDownloade] - True if the episode had already been downloaded.
       */
      that.downloadEpisode = function (subscriptionName, episodeInfo) {
        if (episodeInfo.isDownloaded) {
          // we've already downloaded the episode so we're requesting a refresh instead
          // refresh means, we retrieve the subscription info again and check for updates
          getSubscription(subscriptionName)
            .then(function () {
              that.findSubscriptionUpdates(subscriptionName);
            });
          return;
        }

        // request download of episode
        subscriptionHandler.downloadEpisode(subscriptionName, episodeInfo.season, episodeInfo.episode, episodeInfo.link)
          .then(function (response) {
            if (response.status !== 200) {
              notification.show('Unexpected episode download response code ' + response.status + '!\nMessage: ' + (response.data || {}).message);
              return;
            }

            notification.show('Successfully started torrent download with message: ' + (response.data || {}).message);

            // when we get a successful response, we assume the download was started, so we update the properties
            // so we update the properties of the episode that was downloaded
            // this leaves other links to the same torrent still downloadable
            that.newEpisodes[subscriptionName].forEach(function (sub) {
              if (sub.link == episodeInfo.link) {
                sub.isDownloaded = true;
              }
            });
          })
        .catch(function (err) {
          notification.show('Error ' + err.status + ' while requesting download of ' + subscriptionName + ', S' + $filter('twoDigits')(episodeInfo.season) + 'E' + $filter('twoDigits')(episodeInfo.episode) + ':\n' + (err.data || {}).message);
        });
      };

      // internal methods

      /**
       * Retrieves information about a single subscription.
       * @param {String} subscriptionName - Name of the subscription to retrieve.
       * @returns {Promise} Promise that is returned by the SubscriptionHandler.
       */
      function getSubscription (subscriptionName) {
        logger.logConsole('Retrieving info for subscription "' + subscriptionName + '".');

        return subscriptionHandler.getSubscription(subscriptionName)
          .then(function (resp) {
            handleSubscriptionResponse(resp);
          })
        .catch(function (err) {
          notification.show('Error ' + err.status + ' while requesting infors for subscription ' + subscriptionName + ':\n' + (err.data || {}).message);
        });
      }

      /**
       * Processes the response that was received to a subscription update request,
       * updating the list of new episodes for the subscription.
       * @param {Object} response - Response as it was received from the server.
       * @param {String} subscriptionName - Name of the subscription to which the updates belong.
       */
      function handleSubscriptionUpdatesResponse (response, subscriptionName) {
          if (response.status !== 200) {
            notification.show('Unexpected subscription update response code ' + response.status + '!\nMessage: ' + (response.data || {}).message);
            return;
          }

          logger.logConsole('Handling subscription update response for ' + subscriptionName + ' with message: ' + (response.data || {}).message);

          var responseData = response.data.data,
            lastEpisode,
            isAlternate = true;

          // remove all previously present new episodes for the subscription
          that.newEpisodes[subscriptionName] = [];
          // add the own new episodes for the subscription
          responseData.forEach(function (torrent, index) {
            // add flag to alternate episodes
            if (torrent.episode != lastEpisode) {
              isAlternate = !isAlternate;
              lastEpisode = torrent.episode;
            }
            torrent.isAlternateEpisode = isAlternate;

            that.newEpisodes[subscriptionName].push(torrent);
          });
      }

      /**
       * Processes the response that was received to a subscription info request,
       * adding it to the subscription list.
       * @param {Object} response - Response as it was received from the server.
       */
      function handleSubscriptionResponse (response) {
        if (response.status !== 200) {
          notification.show('Unexpected subscription response code ' + response.status + '!\nMessage: ' + (response.data || {}).message);
          return;
        }

        var responseData = response.data.data;
        logger.logConsole('Handling subscription response with message: ' + response.data.message);

        // the response data is either an object with information about one subscription...
        if (responseData.name) {
          updateSubscriptionInfo(responseData);
          return;
        }

        // ... or an array with such objects
        // update list of subscription infos - process each new info separately
        // for each retrieved subscription info, remove all known infos from the current list
        // and add the new one
        responseData.forEach(updateSubscriptionInfo);
      }

      /**
       * Updates the subscription info of one subscription.
       * @param {Object} newSubscriptionInfo - Container for the new subscription information.
       * @param {String} newSubscriptionInfo.name - Name of the subscription.
       * @param {Number} newSubscriptionInfo.lastSeason - Current season number of the subscription.
       * @param {Number} newSubscriptionInfo.lastEpisode - Current episode number of the subscription.
       * @param {String} newSubscriptionInfo.searchParameters - Search parameters of the subscription.
       * @param {Date} newSubscriptionInfo.lastDownloaded - Date when the subscription was last modified.
       */
      function updateSubscriptionInfo (newSubscriptionInfo) {
        var sorting = {
          alphabetical: function (a, b) {
            return a.name > b.name;
          },
          lastTorrentDownload: function (a, b) {
            if (a.lastDownloadTime == b.lastDownloadTime) {
              return sorting.alphabetical(a, b);
            }
            return a.lastDownloadTime < b.lastDownloadTime;
          }
        };

        that.subscriptions = that.subscriptions.filter(sub => sub.name != newSubscriptionInfo.name);
        that.subscriptions.push(new app.Subscription(newSubscriptionInfo.name, new app.ShowEpisode(newSubscriptionInfo.lastSeason, newSubscriptionInfo.lastEpisode), newSubscriptionInfo.searchParameters, newSubscriptionInfo.lastDownloadTime, newSubscriptionInfo.lastUpdateCheckTime));
        that.subscriptions.sort(sorting[settings.getSubscriptionSort()]);
      }

      // initialization - retrieve all subscriptions
      subscriptionHandler.getAllSubscriptions()
        .then(function (resp) {
          handleSubscriptionResponse(resp);
        });
    }]);


text:
#include "LSHReservoirSampler.h"

/*
* Function:  segmentedSortKV
* --------------------
* Segmented sorting of KV pairs, based on the value of the key. Sorted order is bitonic across segments.
*
*  key_in (in/out): input keys, as cl_mem (on which the sort's value is based), length required to be a power of two
*
*  val_in (in/out): input values, as cl_mem, length required to be a power of two
*
*  segmentSize: length of each segment to be sorted, required to be a power of two
*
*  numSegments: number of segments to be sorted
*
*  returns: nothing
*/
void LSHReservoirSampler::segmentedSortKV(cl_mem* key_in, cl_mem* val_in, int segmentSize, int numSegments, unsigned int valMax) {
	int stage, high_stage, num_stages;
	size_t localSize, globalSize;
	localSize = std::min(512, segmentSize / 8);
	globalSize = segmentSize * numSegments / 8;
	num_stages = (int) 2 * (segmentSize / 8) / localSize;

	/* Preprocess. */
	_err = clSetKernelArg(kernel_bsort_preprocess, 0, sizeof(cl_mem), key_in);
	_err = clSetKernelArg(kernel_bsort_preprocess, 1, sizeof(cl_mem), val_in);
	_err = clSetKernelArg(kernel_bsort_preprocess, 2, sizeof(unsigned int), &valMax);
	clCheckError(_err, "kernel_bsort_preprocess set argument failed!");
	_err = clEnqueueNDRangeKernel(command_queue_gpu, kernel_bsort_preprocess, 1, NULL, &globalSize,
		&localSize, 0, NULL, NULL);
	clCheckError(_err, "kernel_bsort_preprocess failed!");

	/* Create kernel argument */
	_err = clSetKernelArg(kernel_bsort_init_manning_kv, 0, sizeof(cl_mem), key_in);
	_err |= clSetKernelArg(kernel_bsort_stage_0_manning_kv, 0, sizeof(cl_mem), key_in);
	_err |= clSetKernelArg(kernel_bsort_stage_n_manning_kv, 0, sizeof(cl_mem), key_in);
	_err |= clSetKernelArg(kernel_bsort_init_manning_kv, 1, 8 * localSize * sizeof(unsigned int), NULL);
	_err |= clSetKernelArg(kernel_bsort_stage_0_manning_kv, 1, 8 * localSize * sizeof(unsigned int), NULL);
	_err |= clSetKernelArg(kernel_bsort_stage_n_manning_kv, 1, 8 * localSize * sizeof(unsigned int), NULL);
	_err |= clSetKernelArg(kernel_bsort_init_manning_kv, 2, sizeof(cl_mem), val_in);
	_err |= clSetKernelArg(kernel_bsort_stage_0_manning_kv, 2, sizeof(cl_mem), val_in);
	_err |= clSetKernelArg(kernel_bsort_stage_n_manning_kv, 2, sizeof(cl_mem), val_in);
	_err |= clSetKernelArg(kernel_bsort_init_manning_kv, 3, 8 * localSize * sizeof(unsigned int), NULL);
	_err |= clSetKernelArg(kernel_bsort_stage_0_manning_kv, 3, 8 * localSize * sizeof(unsigned int), NULL);
	_err |= clSetKernelArg(kernel_bsort_stage_n_manning_kv, 3, 8 * localSize * sizeof(unsigned int), NULL);

	clCheckError(_err, "kernel_bsort_kv set argument failed!");

	/* Enqueue initial sorting kernel */
	_err = clEnqueueNDRangeKernel(command_queue_gpu, kernel_bsort_init_manning_kv, 1, NULL, &globalSize,
		&localSize, 0, NULL, NULL);
	clCheckError(_err, "kernel_bsort_init_manning_kv failed!");

	/* Execute further stages */
	for (high_stage = 2; high_stage < num_stages; high_stage <<= 1) {

		_err = clSetKernelArg(kernel_bsort_stage_0_manning_kv, 4, sizeof(int), &high_stage);
		_err |= clSetKernelArg(kernel_bsort_stage_n_manning_kv, 5, sizeof(int), &high_stage);
		clCheckError(_err, "kernel_bsort_kv set argument failed!");

		for (stage = high_stage; stage > 1; stage >>= 1) {

			_err = clSetKernelArg(kernel_bsort_stage_n_manning_kv, 4, sizeof(int), &stage);
			clCheckError(_err, "kernel_bsort_kv set argument failed!");

			_err = clEnqueueNDRangeKernel(command_queue_gpu, kernel_bsort_stage_n_manning_kv, 1, NULL,
				&globalSize, &localSize, 0, NULL, NULL);
			clCheckError(_err, "kernel_bsort_stage_n_manning_kv failed!");
		}

		_err = clEnqueueNDRangeKernel(command_queue_gpu, kernel_bsort_stage_0_manning_kv, 1, NULL,
			&globalSize, &localSize, 0, NULL, NULL);
		clCheckError(_err, "kernel_bsort_stage_0_manning_kv failed!");
	}

	/* Postprocess. */
	_err = clSetKernelArg(kernel_bsort_postprocess, 0, sizeof(cl_mem), key_in);
	_err = clSetKernelArg(kernel_bsort_postprocess, 1, sizeof(cl_mem), val_in);
	_err = clSetKernelArg(kernel_bsort_postprocess, 2, sizeof(unsigned int), &valMax);
	clCheckError(_err, "kernel_bsort_postprocess set argument failed!");
	_err = clEnqueueNDRangeKernel(command_queue_gpu, kernel_bsort_postprocess, 1, NULL, &globalSize,
		&localSize, 0, NULL, NULL);
	clCheckError(_err, "kernel_bsort_postprocess failed!");
	clFinish(command_queue_gpu);

}

/*
* Function:  segmentedSort
* --------------------
* Segmented sorting. Sorted order is bitonic across segments.
*
*  in (in/out): input values, as cl_mem (on which the sort's value is based), length required to be a power of two
*
*  segmentSize: length of each segment to be sorted, required to be a power of two
*
*  numSegments: number of segments to be sorted
*
*  returns: nothing
*/
void LSHReservoirSampler::segmentedSort(cl_mem* in, int segmentSize, int numSegments) {
	int stage, high_stage, num_stages;
	size_t localSize, globalSize;
	localSize = std::min(1024, segmentSize / 8);
	globalSize = segmentSize * numSegments / 8;
	num_stages = (int) 2 * (segmentSize / 8) / localSize;

	/* Create kernel argument */
	_err = clSetKernelArg(kernel_bsort_init_manning, 0, sizeof(cl_mem), in);
	_err |= clSetKernelArg(kernel_bsort_stage_0_manning, 0, sizeof(cl_mem), in);
	_err |= clSetKernelArg(kernel_bsort_stage_n_manning, 0, sizeof(cl_mem), in);
	_err |= clSetKernelArg(kernel_bsort_init_manning, 1, 8 * localSize * sizeof(unsigned int), NULL);
	_err |= clSetKernelArg(kernel_bsort_stage_0_manning, 1, 8 * localSize * sizeof(unsigned int), NULL);
	_err |= clSetKernelArg(kernel_bsort_stage_n_manning, 1, 8 * localSize * sizeof(unsigned int), NULL);
	clCheckError(_err, "kernel_bsort set argument failed!");

	/* Enqueue initial sorting kernel */
	_err = clEnqueueNDRangeKernel(command_queue_gpu, kernel_bsort_init_manning, 1, NULL, &globalSize,
		&localSize, 0, NULL, NULL);
	clCheckError(_err, "kernel_bsort_init_manning failed!");

	/* Execute further stages */
	for (high_stage = 2; high_stage < num_stages; high_stage <<= 1) {

		_err = clSetKernelArg(kernel_bsort_stage_0_manning, 2, sizeof(int), &high_stage);
		_err |= clSetKernelArg(kernel_bsort_stage_n_manning, 3, sizeof(int), &high_stage);
		clCheckError(_err, "kernel_bsort set argument failed!");

		for (stage = high_stage; stage > 1; stage >>= 1) {

			_err = clSetKernelArg(kernel_bsort_stage_n_manning, 2, sizeof(int), &stage);
			clCheckError(_err, "kernel_bsort set argument failed!");

			_err = clEnqueueNDRangeKernel(command_queue_gpu, kernel_bsort_stage_n_manning, 1, NULL,
				&globalSize, &localSize, 0, NULL, NULL);
			clCheckError(_err, "kernel_bsort_stage_n_manning failed!");
		}

		_err = clEnqueueNDRangeKernel(command_queue_gpu, kernel_bsort_stage_0_manning, 1, NULL,
			&globalSize, &localSize, 0, NULL, NULL);
		clCheckError(_err, "kernel_bsort_stage_0_manning failed!");
	}
	clFinish(command_queue_gpu);
}


text:
import { configure } from '@storybook/vue';

// automatically import all files ending in *.stories.js
const req = require.context('../src/stories', true, /.stories.js$/);
function loadStories() {
  req.keys().forEach(filename => req(filename));
}

configure(loadStories, module);


text: Docker Image for Spark Tutorial


text:
/** \file emitter.cpp
 *  \author Lukáš Huták, xhutak01
 *	\author Michal Kozubík, xkozub03
 */

#include "emitter.h"
#include <boost/asio.hpp>

/**
 * \brief Konstruktor
 * \param[in] client Klient pro komunikaci se serverem
 */
emitter::emitter(Client *client) :
cl(client)
{
}

/**
 * \brief Hlavní funkce vlákna
 */
void emitter::run()
{
	/* naslouchání serveru a poslání signálu vláknu s GUI */
	cl->listen_this_thread([this](std::stringstream & ss) {
		emit signalGUI(ss);
	});
}


text:
require 'cinch'
require 'cinch/plugins/game_bot'
require 'codenames/game'
require 'codenames/text'

module Cinch; module Plugins; class Codenames < GameBot
  include Cinch::Plugin

  match(/teams?(?:\s+(a|b|r|x))?/i, method: :team)
  match(/words(?:\s+(##?\w+))?/i, method: :words)
  match(/history(?:\s+(##?\w+))?/i, method: :history)

  match(/me$/i, method: :become_hinter)
  match(/rand(?:om)?$/i, method: :random_hinter)

  match(/h(?:int)?\s+(\S+)(?:\s+(\S+))?/i, method: :hint)
  match(/c(?:lue)?\s+(\S+)(?:\s+(\S+))?/i, method: :hint)

  match(/g(?:uess)?\s+(.+)/i, method: :guess)

  # We don't want !status to accidentally trigger !s, or the like.
  match(/s$|p$/i, method: :no_guess)
  match(/stop/i, method: :no_guess)
  match(/pass/i, method: :no_guess)
  match(/noguess/i, method: :no_guess)

  match(/help(?: (.+))?/i, method: :help)
  match(/rules/i, method: :rules)

  match(/peek(?:\s+(##?\w+))?/i, method: :peek)

  add_common_commands

  TEAMS = [
    [:bold, :blue, 'Team Blue'],
    [:bold, :red, 'Team Red'],
  ]
  NEUTRAL = 'Civilian'
  ASSASSIN = 'Assassin'

  def initialize(*args)
    super
    # Game strips out whitespace, but just to be sure!
    possible_words = config[:words_file] ? IO.readlines(config[:words_file]).map(&:chomp) : config[:words]
    ::Codenames::Game.possible_words = possible_words
  end

  #--------------------------------------------------------------------------------
  # Implementing classes should override these
  #--------------------------------------------------------------------------------

  def min_players; ::Codenames::Game::MIN_PLAYERS end
  def max_players; ::Codenames::Game::MAX_PLAYERS end
  def game_name; ::Codenames::Game::GAME_NAME end

  def do_start_game(m, channel_name, players, settings, start_args)
    players_and_preferences = players.map { |p| [p.user, p.data[:team_preference]] }.to_h
    begin
      game = ::Codenames::Game.new(channel_name, players_and_preferences)
    rescue => e
      m.reply("Failed to start game because #{e}", true)
      return
    end

    chan = Channel(game.channel_name)
    chan.send("Welcome to game #{game.id}")
    teams_and_players = game.teams.map { |team|
      "#{format_team(team.id)}: #{team.users.map(&:nick).join(', ')}"
    }.join(' and ')
    chan.send("The teams for game #{game.id} are #{teams_and_players}")

    if game.current_phase == :choose_hinter
      chan.send("All teams: please have one player volunteer to be #{::Codenames::Text::ROLES[:hint]} (!me) or randomly decide (!random).")
    else
      self.send_initial_info(game)
    end

    game
  end

  def do_reset_game(game)
    return unless game.teams.all?(&:picked_roles?)
    Channel(game.channel_name).send(self.endgame_word_info(game))
  end

  def do_replace_user(game, replaced_user, replacing_user)
    # I don't think we need to do anything.
  end

  #game_status aliased to decision_info later

  #--------------------------------------------------------------------------------
  # Game
  #--------------------------------------------------------------------------------

  def become_hinter(m)
    self.choose_hinter(m)
  end

  def random_hinter(m)
    self.choose_hinter(m, random: true)
  end

  def choose_hinter(m, random: false)
    game = self.game_of(m)
    return unless game

    role_name = ::Codenames::Text::ROLES[:hint]

    # Actually if success == true then error is a boolean,
    # but I don't even need to rely on that.
    success, error = game.choose_hinter(m.user, random: random)
    if success
      # Is it OK to highlight the previous hinters when a new hinter is picked?
      # Well, a new hinter being picked always moves the game along, then yes.
      # We can revisit this if it turns out to be a problem later.
      m.reply(game.teams.select(&:picked_roles?).map { |team|
        hinters = team.hinters.map(&:nick)
        "#{format_team(team.id)}'s #{role_name}#{hinters.size == 1 ? ' is' : 's are'} #{hinters.join(', ')}"
      }.join(' and '))
    else
      m.reply("Failed to choose #{role_name} because #{error}", true)
    end

    # If all hinters have been chosen, move the game along.
    self.send_initial_info(game) if game.teams.all?(&:picked_roles?)
  end

  def hint(m, word, num)
    game = self.game_of(m)
    return unless game

    success, error = game.hint(m.user, word, num)
    if success
      chan = Channel(game.channel_name)
      chan.send(self.public_word_info(game))
      chan.send(decision_info(game))
    else
      m.reply("Failed to give clue because #{error}", true)
    end
  end

  def guess(m, guessed)
    game = self.game_of(m)
    return unless game

    # Save these because they could change after guess is done.
    team_name = format_team(game.current_team_id)
    other_team = game.teams[game.other_team_id]

    success, error = game.guess(m.user, guessed)

    if success
      chan = Channel(game.channel_name)
      guess_info = error

      prefix = "#{m.user} of #{team_name} contacted #{guessed.strip.capitalize}"
      case guess_info.role
      when :assassin
        chan.send("#{prefix} the #{ASSASSIN}! #{team_name} loses!")
        self.congratulate_winners(game)
      when :neutral
        chan.send("#{prefix} the #{NEUTRAL}. #{team_name}'s turn is over.")
        self.prompt_hinters(game, other_team.hinters)
      when Integer
        if guess_info.winner
          chan.send("#{prefix} the #{format_team(guess_info.role)} agent! #{format_team(guess_info.winner)} has found all their agents!")
          self.congratulate_winners(game)
        else
          what_next = guess_info.turn_ends ? "#{team_name}'s turn is over." : "#{team_name} can continue guessing."
          chan.send("#{prefix} the #{format_team(guess_info.role)} agent. #{what_next}")
          if guess_info.turn_ends
            self.prompt_hinters(game, other_team.hinters)
          else
            chan.send(decision_info(game))
          end
        end
      else
        chan.send("Unknown word type #{guess_info.role}, unclear how to proceed.")
        chan.send(decision_info(game))
      end
    else
      m.reply("Failed to guess because #{error}", true)
    end
  end

  def no_guess(m)
    game = self.game_of(m)
    return unless game

    success, error = game.no_guess(m.user)
    if success
      # At this point current_team is no longer the passing team.
      # It's the team who needs to give a hint, so current_team is correct.
      self.prompt_hinters(game, game.current_team.hinters)
    else
      m.reply("Failed to pass on guessing because #{error}", true)
    end
  end

  def team(m, arg = nil)
    # Game started: show teams.
    if (game = self.game_of(m))
      game.teams.each { |team|
        if team.picked_roles?
          msg = [:hint, :guess].map { |role|
            users = team.with_role(role)
            role_name = "#{::Codenames::Text::ROLES[role]}#{'s' if users.size != 1}"
            "#{format_team(team.id)} #{role_name}: #{users.map { |u| dehighlight_nick(u.nick) }.join(', ')}"
          }.join(', ')
        else
          msg = "#{format_team(team.id)}: #{team.users.map { |u| dehighlight_nick(u.nick) }.join(', ')}"
        end
        m.reply(msg)
      }
      return
    end

    waiting_room = self.waiting_room_of(m)

    if arg
      # Not started and arg given: change team preference.
      case arg.downcase
      when 'a'; team = 0
      when 'b'; team = 1
      else; team = nil
      end
      waiting_room.data[m.user][:team_preference] = team
      team_name = team ? 'AB'[team] : 'Random'
      m.reply("You joined team #{team_name}.", true)
    else
      # Not started and no arg: show teams.
      prefs = waiting_room.players.group_by { |p| p.data[:team_preference] }
      return if prefs.empty?
      team_ids = (0...::Codenames::Game::NUM_TEAMS).to_a
      team_ids << nil
      # We're not mapping over prefs[i] because I want this specific order.
      teams = team_ids.map { |i|
        next nil unless prefs[i] && !prefs[i].empty?
        team_name = i ? 'AB'[i] : 'Random'
        "Team #{team_name} (#{prefs[i].size}): #{prefs[i].map { |p| dehighlight_nick(p.user.nick) }.join(', ')}"
      }.compact.join(', ')
      m.reply(teams)
    end
  end

  def words(m, channel_name = nil)
    game = self.game_of(m, channel_name, ['see words', '!words'])
    return unless game

    # We don't show words until everyone has chosen roles.
    return unless game.teams.all?(&:picked_roles?)

    if game.role_of(m.user) == :hint
      m.user.send(self.hinter_word_info(game))
    else
      m.reply(self.public_word_info(game))
    end
  end

  def history(m, channel_name = nil)
    game = self.game_of(m, channel_name, ['see history', '!history'])
    return unless game

    if game.hints.empty?
      m.reply("Game #{game.id} history: Nothing yet!")
      return
    end

    m.reply("Game #{game.id} history:\n" + game.hints.map { |entry|
      prefix = "#{format_team(entry.team)} Hint: #{entry.to_s}. Guesses: "
      next "#{prefix}None yet." if entry.guesses.empty?

      # The first N-1 guesses must be the right team (so that the team could continue guessing),
      # so we just need to check the role of the last word.
      last_role = entry.guesses.last.role
      team_results = entry.guesses.size - 1
      team_results += 1 if last_role == entry.team

      guess_roles = []
      guess_roles << "#{team_results} #{format_team(entry.team)}" if team_results > 0
      guess_roles << "1 #{NEUTRAL}" if last_role == :neutral
      # Assassin probably not possible, but maybe one day we'll have retroactive history.
      guess_roles << "1 #{ASSASSIN}" if last_role == :assassin
      guess_roles << "1 #{format_team(last_role)}" if last_role.is_a?(Integer) && last_role != entry.team

      guesses = entry.guesses.map { |g| g.word.capitalize }.join(', ')

      "#{prefix}#{guesses} (#{guess_roles.join(', ')})."
    }.join("\n"))
  end

  def peek(m, channel_name = nil)
    return unless self.is_mod?(m.user)
    game = self.game_of(m, channel_name, ['peek', '!peek'])
    return unless game

    if game.users.include?(m.user)
      m.user.send('Cheater!!!')
      return
    end

    m.user.send(self.endgame_word_info(game))
  end

  #--------------------------------------------------------------------------------
  # Help for player/table info
  #--------------------------------------------------------------------------------

  def send_initial_info(game)
    hinter_info = self.hinter_word_info(game)
    game.teams.each { |team| team.hinters.each { |hinter| hinter.send(hinter_info) } }
    chan = Channel(game.channel_name)
    chan.send("Codenames for game #{game.id}: #{game.public_words[:unguessed].map(&:capitalize).join(', ')}")
    chan.send(decision_info(game))
  end

  def prompt_hinters(game, hinters)
    hinter_info = self.hinter_word_info(game)
    hinters.each { |hinter| hinter.send(hinter_info) }
    Channel(game.channel_name).send(decision_info(game))
  end

  def congratulate_winners(game)
    chan = Channel(game.channel_name)
    chan.send("Congratulations!!! #{game.winning_players.map(&:nick).join(', ')} are the winners!") if game.winning_players
    chan.send(self.endgame_word_info(game))
    self.start_new_game(game)
  end

  def decision_info(game)
    info = case game.current_phase
    when :choose_hinter
      teams_left = game.teams.reject(&:picked_roles?)
      teams_and_players = teams_left.map { |team|
        "#{format_team(team.id)} (#{team.users.map(&:nick).join(', ')})"
      }.join(' and ')

      "#{teams_and_players} #{teams_left.size == 1 ? 'is' : 'are'} choosing a #{::Codenames::Text::ROLES[:hint]}"
    when :hint, :guess
      role = game.current_phase
      team = game.current_team
      players = team.with_role(role)
      intro = "#{format_team(team.id)} #{::Codenames::Text::ROLES[role]}#{'s' if players.size != 1} (#{players.map(&:nick).join(', ')})"
      instructions = if role == :hint
        'Please present a !clue to your team: one word and one number indicating how many codenames are related to the word (or "unlimited").'
      else
        can_stop = game.guessed_this_turn? ? ' or !stop guessing' : ''
        guesses = game.guesses_remaining
        guesses = 'unlimited' if guesses == Float::INFINITY
        "Please make a !guess for the clue \"#{game.current_hint}\"#{can_stop}. You have #{guesses} guess#{'es' if guesses != 1} remaining."
      end
      "#{intro}: #{instructions}"
    end
    "Game #{game.id} turn #{game.turn_number}: #{info}"
  end
  alias :game_status :decision_info

  def classify_one(name, words, max, show_max: true)
    max_str = show_max ? "/#{max}" : ''
    "#{name}#{'s' if max != 1} (#{words.size}#{max_str}): #{words.map(&:capitalize).join(', ')}"
  end

  def classify_words(words, show_max: true)
    lines = []
    ::Codenames::Game::NUM_TEAMS.times { |i|
      if (agents = words[i])
        max = ::Codenames::Game::TEAM_WORDS[i]
        lines << classify_one("#{format_team(i)} agent", agents, max, show_max: show_max)
      end
    }
    if (neutrals = words[:neutral])
      lines << classify_one(NEUTRAL, neutrals, ::Codenames::Game::NEUTRAL_WORDS, show_max: show_max)
    end
    if (assassins = words[:assassin])
      lines << classify_one(ASSASSIN, assassins, ::Codenames::Game::ASSASSIN_WORDS, show_max: show_max)
    end
    lines
  end

  def public_word_info(game)
    words = game.public_words
    lines = ["Game #{game.id} turn #{game.turn_number} status:"]
    lines.concat(classify_words(words[:guessed]))
    lines << "Unidentified (#{words[:unguessed].size}): #{words[:unguessed].map(&:capitalize).join(', ')}"
    lines.join("\n")
  end

  def hinter_word_info(game)
    words = game.hinter_words
    lines = ["Game #{game.id} turn #{game.turn_number} status:"]
    lines.concat(classify_words(words, show_max: false))
    lines.join("\n")
  end

  def endgame_word_info(game)
    words = game.hinter_words(exclude_revealed: false)
    lines = ["Game #{game.id} words:"]
    lines.concat(classify_words(words, show_max: false))
    lines.join("\n")
  end

  def format_team(id)
    Format(*TEAMS[id])
  end

  #--------------------------------------------------------------------------------
  # General
  #--------------------------------------------------------------------------------

  def help(m, page = '')
    page ||= ''
    page = '' if page.strip.downcase == 'mod' && !self.is_mod?(m.user)
    case page.strip.downcase
    when 'mod'
      m.reply('Cheating: peek')
      m.reply('Game admin: kick, reset, replace')
    when '2'
      m.reply("Set team (pre-game): team")
      m.reply("Game info: team, words, status, history")
      m.reply("Game actions: guess (alias g), clue (alias c, hint, h), stop (alias s, pass, p, noguess)")
    when '3'
      m.reply('Getting people to play: invite, subscribe, unsubscribe')
      m.reply('To get PRIVMSG: notice off. To get NOTICE: notice on')
    else
      m.reply("General help: All commands can be issued by '!command' or '#{m.bot.nick}: command' or PMing 'command'")
      m.reply('General commands: join, leave, start, who')
      m.reply('Game-related commands: help 2. Preferences: help 3')
    end
  end

  def rules(m)
    m.reply('https://boardgamegeek.com/filepage/119841/codenames-rulebook-english')
  end
end; end; end


text:
package com.macasaet.fernet.jersey.example.common;

import static java.util.Collections.singleton;

import java.util.Collection;
import java.util.function.Supplier;

import javax.inject.Singleton;

import com.macasaet.fernet.Key;

@Singleton
public class KeySupplier implements Supplier<Collection<? extends Key>> {

    private static final Key key = new Key("oTWTxEsH8OZ2jNR64dibSaBHyj_CX2RGP-eBRxjlkoc=");

    public Collection<? extends Key> get() {
        // alternatively, get this from a datastore or secure key storage like AWS Secrets Manager, AWS KMS, or HashiCorp Vault
        return singleton(key);
    }

}


text:
require 'geo'

require 'csv'
require 'json'
require 'colorize'

$max_ratio = nil

def color(ratio)
  ratio >= 0.5 ? "#27ae60" : (ratio >= 0.1 ? "#e67e22" : "#c0392b")
end

def opacity(ratio)
  max_ratio = ratio >= 0.5 ? $max_ratio : (ratio >= 0.1 ? 1.0 : 0.15)
  Math.log(1 + ratio * (Math::E - 1) / max_ratio)
end

features = []

csv = CSV.parse(File.read('data/github_users_per_state.csv'), :headers => true)
csv.each do |row|
  row_hash = row.to_hash
  abbr = row_hash["Abbr"]
  ratio = row["Dev per 1000 inhab."].to_f
  $max_ratio = ratio if $max_ratio.nil?

  begin
    puts "Fetching #{abbr}"
    features << Geo.new.geo_json(abbr, row_hash, opacity(ratio), color(ratio))
  rescue OpenURI::HTTPError => e
    puts "Could not fetch geojson for #{abbr} - #{e.message}".colorize(:yellow)
    retry unless e.message =~ /404/
  end
end

File.open('data/github_users_per_state.geojson', 'w') do |f|
  f.write JSON.pretty_generate({
    "type" => "FeatureCollection",
    "features" => features
  })
end


text:
QUnit.test('once call tests', function ( assert ) {
  var callback = sinon.spy(),
    onceCallback = onceCall( callback );

  onceCallback();
  assert.ok( callback.calledOnce );
  onceCallback();
  assert.ok( callback.calledOnce );

  var callback = sinon.stub().returns(5),
    onceCallback = onceCall( callback );
  assert.equal( onceCallback(), 5, 'message' );
  assert.equal( onceCallback(), 5, 'message' );
});

QUnit.test('get todo items', function ( assert ) {
  var xhr = sinon.useFakeXMLHttpRequest(),
    requests = [];
  xhr.onCreate = function ( req ) {
    requests.push( req );
  }
  getTodoItems( 5, sinon.spy() );
  assert.equal( requests.length, 1 );
  assert.equal( requests[0].url, '/todo/5/items' );
  xhr.restore();

  var server = sinon.fakeServer.create(),
  callback = sinon.spy();
  getTodoItems( 5, callback );
  server.requests[0].respond(
    200,
    { "Content-Type": "application/json" },
    JSON.stringify([{ id: 1, text: "Provide examples", done: true }])
  );
  assert.ok( callback.calledOnce );
  assert.deepEqual( callback.firstCall.args[0],
    [{ id: 1, text: "Provide examples", done: true }] );
  server.restore();

});

QUnit.test('delayed callback', function ( assert ) {
  var clock = sinon.useFakeTimers(),
    callback = sinon.spy(),
    delayed = delay( callback, 500 );
  delayed();
  clock.tick(499);
  assert.ok( !callback.called );
  clock.tick(1);
  assert.ok( callback.calledOnce );
});


text:
Dimension Labels
================
Pops up a HUD element in the upper left corner of the screen whenever a player travels to a dimension, with the name of that dimension on it.  The element then fades out after a few seconds.  Custom config for adding new ID:String mappings for custom dimensions.


text:
package javax.sound.sampled;

/**
 * Ports are simple lines for input or output of audio to or from audio devices.
 * Common examples of ports that act as source lines (mixer inputs) include the microphone,
 * line input, and CD-ROM drive.  Ports that act as target lines (mixer outputs) include the
 * speaker, headphone, and line output.  You can access port using a {@link Port.Info}
 * object.
 *
 * @author Kara Kytle
 * @since 1.3
 */
public interface Port extends Line {

    // INNER CLASSES

    /**
     * The Port.Info class extends {@link Line.Info}
     * with additional information specific to ports, including the port's name
     * and whether it is a source or a target for its mixer.
     * By definition, a port acts as either a source or a target to its mixer,
     * but not both.  (Audio input ports are sources; audio output ports are targets.)
     *

     * To learn what ports are available, you can retrieve port info objects through the
     * {@link Mixer#getSourceLineInfo getSourceLineInfo} and
     * {@link Mixer#getTargetLineInfo getTargetLineInfo}
     * methods of the Mixer interface.  Instances of the
     * Port.Info class may also be constructed and used to obtain
     * lines matching the parameters specified in the Port.Info object.
     *
     * @author Kara Kytle
     * @since 1.3
     */
    public static class Info extends Line.Info {

        // AUDIO PORT TYPE DEFINES

        // SOURCE PORTS

        /**
         * A type of port that gets audio from a built-in microphone or a microphone jack.
         */
        public static final Info MICROPHONE = new Info(Port.class,"MICROPHONE", true);

        /**
         * A type of port that gets audio from a line-level audio input jack.
         */
        public static final Info LINE_IN = new Info(Port.class,"LINE_IN", true);

        /**
         * A type of port that gets audio from a CD-ROM drive.
         */
        public static final Info COMPACT_DISC = new Info(Port.class,"COMPACT_DISC", true);

        // TARGET PORTS

        /**
         * A type of port that sends audio to a built-in speaker or a speaker jack.
         */
        public static final Info SPEAKER = new Info(Port.class,"SPEAKER", false);

        /**
         * A type of port that sends audio to a headphone jack.
         */
        public static final Info HEADPHONE = new Info(Port.class,"HEADPHONE", false);

        /**
         * A type of port that sends audio to a line-level audio output jack.
         */
        public static final Info LINE_OUT = new Info(Port.class,"LINE_OUT", false);

        // FUTURE DIRECTIONS...

        // telephone
        // DAT
        // DVD

        // INSTANCE VARIABLES

        private String name;
        private boolean isSource;

        // CONSTRUCTOR

        /**
         * Constructs a port's info object from the information given.
         * This constructor is typically used by an implementation
         * of Java Sound to describe a supported line.
         *
         * @param lineClass the class of the port described by the info object.
         * @param name the string that names the port
         * @param isSource true if the port is a source port (such
         * as a microphone), false if the port is a target port
         * (such as a speaker).
         */
        public Info(Class<?> lineClass, String name, boolean isSource) {

            super(lineClass);
            this.name = name;
            this.isSource = isSource;
        }

        // METHODS

        /**
         * Obtains the name of the port.
         * @return the string that names the port
         */
        public String getName() {
            return name;
        }

        /**
         * Indicates whether the port is a source or a target for its mixer.
         * @return true if the port is a source port (such
         * as a microphone), false if the port is a target port
         * (such as a speaker).
         */
        public boolean isSource() {
            return isSource;
        }

        /**
         * Indicates whether this info object specified matches this one.
         * To match, the match requirements of the superclass must be
         * met and the types must be equal.
         * @param info the info object for which the match is queried
         */
        public boolean matches(Line.Info info) {

            if (! (super.matches(info)) ) {
                return false;
            }

            if (!(name.equals(((Info)info).getName())) ) {
                return false;
            }

            if (! (isSource == ((Info)info).isSource()) ) {
                return false;
            }

            return true;
        }

        /**
         * Finalizes the equals method
         */
        public final boolean equals(Object obj) {
            return super.equals(obj);
        }

        /**
         * Finalizes the hashCode method
         */
        public final int hashCode() {
            return super.hashCode();
        }

        /**
         * Provides a String representation
         * of the port.
         * @return  a string that describes the port
         */
        public final String toString() {
            return (name + ((isSource == true) ? " source" : " target") + " port");
        }

    } // class Info
}