text:
/* NPCX fan control module. */

#include "clock.h"
#include "clock_chip.h"
#include "fan.h"
#include "fan_chip.h"
#include "gpio.h"
#include "hooks.h"
#include "registers.h"
#include "util.h"
#include "pwm.h"
#include "pwm_chip.h"
#include "console.h"
#include "timer.h"
#include "task.h"

#if !(DEBUG_FAN)
#define CPRINTS(...)
#else
#define CPRINTS(format, args...) cprints(CC_PWM, format, ## args)
#endif

/* Fan operation module */
enum npcx_fan_op_module {
	NPCX_FAN_OP_PWM,
	NPCX_FAN_OP_MFT,
	/* Number of FAN module operations */
	NPCX_FAN_OP_COUNT
};

/* MFT model select */
enum npcx_mft_mdsel {
	NPCX_MFT_MDSEL_1,
	NPCX_MFT_MDSEL_2,
	NPCX_MFT_MDSEL_3,
	NPCX_MFT_MDSEL_4,
	NPCX_MFT_MDSEL_5,
	/* Number of MFT modes */
	NPCX_MFT_MDSEL_COUNT
};

/* MFT clock source */
enum npcx_mft_clk_src {
	TCKC_NOCLK = 0,
	TCKC_PRESCALE_APB1_CLK,
	TCKC_EXTERNAL,
	TCKC_PULSE_ACC,
	TCKC_LFCLK
};

#define RPM_SCALE                   1 /* Fan RPM is multiplier of actual RPM */
#define RPM_EDGES                   1 /* Fan number of edges - 1 */
/*
 * RPM = (n - 1) * m * f * 60 / poles / TACH
 *   n = Fan number of edges = (RPM_EDGES + 1)
 *   m = Fan multiplier defined by RANGE
 *   f = PWM and MFT freq
 *   poles = 2
 */
#define RPM_TO_TACH(pwm_channel, rpm) \
	MIN(((uint32_t)(pwm_channels[pwm_channel].freq)*30*RPM_EDGES*RPM_SCALE \
	/MAX((rpm), 1)), (pwm_channels[pwm_channel].cycle_pulses))

#define TACH_TO_RPM(mft_channel, tach) \
	((mft_channels[mft_channel].freq)*30*RPM_EDGES*RPM_SCALE \
	/MAX((tach), 1))

/* Global variables */
static volatile struct tacho_status_t tacho_status;
static int rpm_target;
static int rpm_actual = -1;
static int fan_init_ch;
/**
 * Select fan operation channel by module.
 *
 * @param   none
 * @param   op_module   npcx operation module
 * @return  npcx operation channel by module
 * @notes   Fan is controlled by PWM/MFT module in npcx chip
 */
static int fan_op_ch(int ch, enum npcx_fan_op_module op_module)
{
	uint8_t op_ch;

	switch (ch) {
	case 0:
		if (op_module == NPCX_FAN_OP_PWM)
			op_ch = PWM_CH_FAN;
		else
			op_ch = MFT_CH_0;
		break;
	default:
		op_ch = 0;
		break;
	}
	return op_ch;
}

/**
 * MFT start measure.
 *
 * @param   ch      operation channel
 * @return  none
 */
static void mft_startmeasure(int ch)
{
	int mft_ch = fan_op_ch(ch, NPCX_FAN_OP_MFT);

	/* Start measurement */
#ifdef CONFIG_MFT_INPUT_LFCLK
	/* Set the LFCLK clock. */
	if (NPCX_MFT_MODULE_PORT_TB == mft_channels[mft_ch].port)
		NPCX_TCKC(mft_channels[mft_ch].module) =
			(NPCX_TCKC(mft_channels[mft_ch].module)
			&(~(((1<<3)-1)<<NPCX_TCKC_C2CSEL)))
			|(TCKC_LFCLK<<NPCX_TCKC_C2CSEL);
	else
		NPCX_TCKC(mft_channels[mft_ch].module) =
			(NPCX_TCKC(mft_channels[mft_ch].module)
			&(~(((1<<3)-1)<<NPCX_TCKC_C1CSEL)))
			|(TCKC_LFCLK<<NPCX_TCKC_C1CSEL);
#else
	/* Set the core clock. */
	if (NPCX_MFT_MODULE_PORT_TB == mft_channels[mft_ch].port)
		NPCX_TCKC(mft_channels[mft_ch].module) =
			(NPCX_TCKC(mft_channels[mft_ch].module)
			&(~(((1<<3)-1)<<NPCX_TCKC_C2CSEL)))
			|(TCKC_PRESCALE_APB1_CLK<<NPCX_TCKC_C2CSEL);
	else
		NPCX_TCKC(mft_channels[mft_ch].module) =
			(NPCX_TCKC(mft_channels[mft_ch].module)
			&(~(((1<<3)-1)<<NPCX_TCKC_C1CSEL)))
			|(TCKC_PRESCALE_APB1_CLK<<NPCX_TCKC_C1CSEL);
#endif
}

/**
 * MFT stop measure.
 *
 * @param   ch      operation channel
 * @return  none
 */
static void mft_stopmeasure(int ch)
{
	int mft_ch = fan_op_ch(ch, NPCX_FAN_OP_MFT);

	/* Clear all pending flag */
	NPCX_TECLR(mft_channels[mft_ch].module) =
			NPCX_TECTRL(mft_channels[mft_ch].module);

	/* Stop the timer */
	if (NPCX_MFT_MODULE_PORT_TB == mft_channels[mft_ch].port)
		NPCX_TCKC(mft_channels[mft_ch].module) =
				(NPCX_TCKC(mft_channels[mft_ch].module)
				&(~(((1<<3)-1)<<NPCX_TCKC_C2CSEL)))
				|(TCKC_NOCLK<<NPCX_TCKC_C2CSEL);
	else
		NPCX_TCKC(mft_channels[mft_ch].module) =
				(NPCX_TCKC(mft_channels[mft_ch].module)
				&(~(((1<<3)-1)<<NPCX_TCKC_C1CSEL)))
				|(TCKC_NOCLK<<NPCX_TCKC_C1CSEL);
}

/**
 * MFT final measure.
 *
 * @param   ch      operation channel
 * @return  none
 */
static void mft_finalmeasure(int ch)
{
	int mft_ch = fan_op_ch(ch, NPCX_FAN_OP_MFT);

	/*
	 * Start of the last tacho cycle is detected -
	 * calculated tacho cycle duration
	 */
	if (NPCX_MFT_MODULE_PORT_TB == mft_channels[mft_ch].port)
		tacho_status.edge_interval =
				(uint32_t)(mft_channels[mft_ch].default_count
				- NPCX_TCRB(mft_channels[mft_ch].module));
	else
		tacho_status.edge_interval =
				(uint32_t)(mft_channels[mft_ch].default_count
				- NPCX_TCRA(mft_channels[mft_ch].module));
}

/**
 * Preset fan operation clock.
 *
 * @param   none
 * @return  none
 * @notes   changed when initial or HOOK_FREQ_CHANGE command
 */
#ifndef CONFIG_MFT_INPUT_LFCLK
void mft_freq_changed(void)
{
	uint16_t prescaler_divider    = 0;
	int mft_ch = fan_op_ch(fan_init_ch, NPCX_FAN_OP_MFT);

	/* Set clock prescaler divider to MFT module*/
	prescaler_divider = (uint16_t)(clock_get_apb1_freq()
			/mft_channels[mft_ch].freq);
	if (prescaler_divider >= 1)
		prescaler_divider = prescaler_divider - 1;
	if (prescaler_divider > 0xFF)
		prescaler_divider = 0xFF;

	NPCX_TPRSC(mft_channels[mft_ch].module) = (uint8_t)prescaler_divider;
}
DECLARE_HOOK(HOOK_FREQ_CHANGE, mft_freq_changed, HOOK_PRIO_DEFAULT);
#endif

/**
 * Fan configuration.
 *
 * @param ch                        operation channel
 * @param enable_mft_read_rpm       FAN_USE_RPM_MODE enable flag
 * @return none
 */
static void fan_config(int ch, int enable_mft_read_rpm)
{
	int pwm_ch = fan_op_ch(ch, NPCX_FAN_OP_PWM);
	int mft_ch = fan_op_ch(ch, NPCX_FAN_OP_MFT);

	fan_init_ch = ch;
	pwm_config(pwm_ch);

	/* Mux mft */
	CLEAR_BIT(NPCX_DEVALT(3), NPCX_DEVALT3_TB1_TACH2_SL1);
	/* Configure pins from GPIOs to FAN */
	gpio_config_module(MODULE_PWM_FAN, 1);

	if (enable_mft_read_rpm) {
		/* Set mode 5 to MFT module*/
		NPCX_TMCTRL(mft_channels[mft_ch].module) =
				(NPCX_TMCTRL(mft_channels[mft_ch].module)
				& (~(((1<<3)-1)<<NPCX_TMCTRL_MDSEL)))
				| (NPCX_MFT_MDSEL_5<<NPCX_TMCTRL_MDSEL);

#ifndef CONFIG_MFT_INPUT_LFCLK
		/* Set MFT operation frequence */
		mft_freq_changed();
		/* Set the active power mode. */
		CLEAR_BIT(NPCX_TCKC(mft_channels[mft_ch].module),
				NPCX_TCKC_LOW_PWR);
#else
		/* Set the low power mode. */
		SET_BIT(NPCX_TCKC(mft_channels[mft_ch].module),
				NPCX_TCKC_LOW_PWR);
#endif
		if (NPCX_MFT_MODULE_PORT_TB == mft_channels[mft_ch].port) {
			/* Set the default count-down timer. */
			NPCX_TCNT2(mft_channels[mft_ch].module) =
					mft_channels[mft_ch].default_count;
			NPCX_TCRB(mft_channels[mft_ch].module) =
					mft_channels[mft_ch].default_count;
			/* Set the edge polarity to rising. */
			SET_BIT(NPCX_TMCTRL(mft_channels[mft_ch].module),
					NPCX_TMCTRL_TBEDG);
			/* Enable capture TCNT2 into TCRB and preset TCNT2. */
			SET_BIT(NPCX_TMCTRL(mft_channels[mft_ch].module),
					NPCX_TMCTRL_TBEN);
			/* Enable input debounce logic into TB. */
			SET_BIT(NPCX_TCFG(mft_channels[mft_ch].module),
					NPCX_TCFG_TBDBEN);
			/* Set the no clock to TCNT2. */
			NPCX_TCKC(mft_channels[mft_ch].module) =
					(NPCX_TCKC(mft_channels[mft_ch].module)
					& (~(((1<<3)-1)<<NPCX_TCKC_C2CSEL)))
					| (TCKC_NOCLK<<NPCX_TCKC_C2CSEL);
			/* Set timer wake-up enable */
			SET_BIT(NPCX_TWUEN(mft_channels[mft_ch].module),
					NPCX_TWUEN_TBWEN);
			SET_BIT(NPCX_TWUEN(mft_channels[mft_ch].module),
					NPCX_TWUEN_TDWEN);
		} else {
			/* Set the default count-down timer. */
			NPCX_TCNT1(mft_channels[mft_ch].module) =
					mft_channels[mft_ch].default_count;
			NPCX_TCRA(mft_channels[mft_ch].module) =
					mft_channels[mft_ch].default_count;
			/* Set the edge polarity to rising. */
			SET_BIT(NPCX_TMCTRL(mft_channels[mft_ch].module),
					NPCX_TMCTRL_TAEDG);
			/* Enable capture TCNT1 into TCRA and preset TCNT1. */
			SET_BIT(NPCX_TMCTRL(mft_channels[mft_ch].module),
					NPCX_TMCTRL_TAEN);
			/* Enable input debounce logic into TA. */
			SET_BIT(NPCX_TCFG(mft_channels[mft_ch].module),
					NPCX_TCFG_TADBEN);
			/* Set the no clock to TCNT1. */
			NPCX_TCKC(mft_channels[mft_ch].module) =
				  (NPCX_TCKC(mft_channels[mft_ch].module)
				& (~(((1<<3)-1)<<NPCX_TCKC_C1CSEL)))
				| (TCKC_NOCLK<<NPCX_TCKC_C1CSEL);
			/* Set timer wake-up enable */
			SET_BIT(NPCX_TWUEN(mft_channels[mft_ch].module),
					NPCX_TWUEN_TAWEN);
			SET_BIT(NPCX_TWUEN(mft_channels[mft_ch].module),
					NPCX_TWUEN_TCWEN);
		}
	}

	/* Back to Idle mode*/
	tacho_status.cur_state = TACHO_IN_IDLE;
}

/**
 * Set fan enabled.
 *
 * @param   ch      operation channel
 * @param   enabled enabled flag
 * @return  none
 */
void fan_set_enabled(int ch, int enabled)
{
	int pwm_ch = fan_op_ch(ch, NPCX_FAN_OP_PWM);

	pwm_enable(pwm_ch, enabled);
}

/**
 * Check fan enabled.
 *
 * @param   ch  operation channel
 * @return  enabled or not
 */
int fan_get_enabled(int ch)
{
	int pwm_ch = fan_op_ch(ch, NPCX_FAN_OP_PWM);

	return pwm_get_enabled(pwm_ch);
}

/**
 * Set fan duty cycle.
 *
 * @param   ch      operation channel
 * @param   percent duty cycle percent
 * @return  none
 */
void fan_set_duty(int ch, int percent)
{
	int pwm_ch = fan_op_ch(ch, NPCX_FAN_OP_PWM);

	CPRINTS("set duty percent=%d", percent);

	/* Set the duty cycle */
	pwm_set_duty(pwm_ch, percent);
}

/**
 * Get fan duty cycle.
 *
 * @param   ch  operation channel
 * @return  duty cycle
 */
int fan_get_duty(int ch)
{
	int pwm_ch = fan_op_ch(ch, NPCX_FAN_OP_PWM);

	/* Return percent */
	return pwm_get_duty(pwm_ch);
}

/**
 * Check fan is rpm operation mode.
 *
 * @param   ch  operation channel
 * @return  rpm operation mode or not
 * @notes   not support in npcx chip
 */
int fan_get_rpm_mode(int ch)
{
	/* TODO: (Benson_TBD_4) not support rpm mode, return 0 always */
	return 0;
}

/**
 * Set fan to rpm operation mode.
 *
 * @param   ch          operation channel
 * @param   rpm_mode    rpm operation mode flag
 * @return  none
 * @notes   not support in npcx chip
 */
void fan_set_rpm_mode(int ch, int rpm_mode)
{
	/* TODO: (Benson_TBD_4) not support rpm mode */
}

/**
 * Get fan actual operation rpm.
 *
 * @param   ch  operation channel
 * @return  actual operation rpm value
 */
int fan_get_rpm_actual(int ch)
{
	int mft_ch = fan_op_ch(ch, NPCX_FAN_OP_MFT);
	uint8_t capture_pnd = NPCX_TECTRL_TBPND,
		underflow_pnd = NPCX_TECTRL_TDPND;
	uint8_t capture_clr = NPCX_TECLR_TBCLR,
		underflow_clr = NPCX_TECLR_TDCLR;

	/* Init pending/clear flag bit */
	if (NPCX_MFT_MODULE_PORT_TA == mft_channels[mft_ch].port) {
		capture_pnd = NPCX_TECTRL_TAPND;
		underflow_pnd = NPCX_TECTRL_TCPND;
		capture_clr = NPCX_TECLR_TACLR;
		underflow_clr = NPCX_TECLR_TCCLR;
	}
	/* Start measure and return previous value when fan is working*/
	if ((fan_get_enabled(ch)) && (fan_get_duty(ch))) {
		if (tacho_status.cur_state == TACHO_IN_IDLE) {
			CPRINTS("mft_startmeasure");
			if ((0 == rpm_actual) || (-1 == rpm_actual))
				rpm_actual = fans[ch].rpm_min;
			/* Clear all pending flags */
			NPCX_TECLR(mft_channels[mft_ch].module) =
				   NPCX_TECTRL(mft_channels[mft_ch].module);
			/* Start from first edge state */
			tacho_status.cur_state = TACHO_WAIT_FOR_1_EDGE;
			/* Start measure */
			mft_startmeasure(ch);
		}
		/* Check whether MFT underflow flag is occurred */
		else if (IS_BIT_SET(NPCX_TECTRL(mft_channels[mft_ch].module),
				underflow_pnd)) {
			/* Measurement is active - stop the measurement */
			mft_stopmeasure(fan_init_ch);
			/* Need to avoid underflow state happen */
			rpm_actual = fans[ch].rpm_max;
			/*
			 * Flag TDPND means mft underflow happen then complete
			 * measurement immediately
			 */
			tacho_status.cur_state = TACHO_UNDERFLOW;
			CPRINTS("TACHO_UNDERFLOW");

			/* Clear pending flags */
			SET_BIT(NPCX_TECLR(mft_channels[mft_ch].module),
					underflow_clr);
		}
		/* Check whether MFT signal detection flag is occurred */
		else if (IS_BIT_SET(NPCX_TECTRL(mft_channels[mft_ch].module),
				capture_pnd)) {
			/* Start of tacho cycle is detected */
			switch (tacho_status.cur_state) {
			case TACHO_WAIT_FOR_1_EDGE:
				CPRINTS("TACHO_WAIT_FOR_1_EDGE");
				/*
				 * Start of the first tacho cycle is detected
				 * and wait for the second tacho cycle
				 * (second edge)
				 */
				tacho_status.cur_state = TACHO_WAIT_FOR_2_EDGE;
				/* Send previous rpm before complete measure */
				break;
			case TACHO_WAIT_FOR_2_EDGE:
				/* Complete measure tach and get actual tach */
				mft_finalmeasure(fan_init_ch);
				/* Stop the measurement */
				mft_stopmeasure(ch);
				/* Transfer actual tach to actual rpm */
				rpm_actual = (tacho_status.edge_interval > 0) ?
					     (TACH_TO_RPM(mft_ch,
					     tacho_status.edge_interval)) : 0;
				/* Back to Idle mode*/
				tacho_status.cur_state = TACHO_IN_IDLE;
				CPRINTS("TACHO_WAIT_FOR_2_EDGE");
				CPRINTS("edge_interval=%x",
						tacho_status.edge_interval);
				CPRINTS("rpm_actual=%d", rpm_actual);
				break;
			default:
				break;
			}
			/* Clear pending flags */
			SET_BIT(NPCX_TECLR(mft_channels[mft_ch].module),
						capture_clr);
		}
	} else {
		CPRINTS("preset rpm");
		/* Send preset rpm before fan is working */
		if (fan_get_enabled(ch))
			rpm_actual = fans[ch].rpm_min;
		else
			rpm_actual = 0;

		tacho_status.cur_state = TACHO_IN_IDLE;
	}
	return rpm_actual;
}

/**
 * Get fan setting rpm.
 *
 * @param   ch  operation channel
 * @return  setting rpm value
 */
int fan_get_rpm_target(int ch)
{
	return rpm_target;
}

/**
 * Set fan setting rpm.
 *
 * @param   ch  operation channel
 * @param   rpm setting rpm value
 * @return  none
 */
void fan_set_rpm_target(int ch, int rpm)
{
	uint32_t percent = 0;
	int pwm_ch = fan_op_ch(ch, NPCX_FAN_OP_PWM);

	rpm_target = rpm;
	/* Transfer rpm to tach then calculate percentage */
	percent = (RPM_TO_TACH(pwm_ch, rpm_target)*100)
		/(pwm_channels[pwm_ch].cycle_pulses);

	if (percent < 0)
		percent = 0;
	else if (percent > 100)
		percent = 100;

	/* RPM is inverse ratio to tach and percentage */
	percent = 100 - percent;

	pwm_set_duty(pwm_ch, percent);
}

/**
 * Check fan operation status.
 *
 * @param   ch          operation channel
 * @return  fan_status  fan operation status
 */
enum fan_status fan_get_status(int ch)
{
	int rpm_actual;

	rpm_actual = fan_get_rpm_actual(ch);

	if (((fan_get_duty(ch)) && (0 == rpm_actual))
			|| ((!fan_get_duty(ch)) && (rpm_actual)))
		return FAN_STATUS_FRUSTRATED;
	else if ((rpm_actual == 0) && (!fan_get_duty(ch)))
		return FAN_STATUS_STOPPED;
	else
		return FAN_STATUS_LOCKED;
}

/**
 * Check fan is stall condition.
 *
 * @param   ch          operation channel
 * @return  non-zero    if fan is enabled but stalled
 */
int fan_is_stalled(int ch)
{
	int rpm_actual;

	rpm_actual = fan_get_rpm_actual(ch);

	/* Check for normal condition, others are stall condition */
	if ((!fan_get_enabled(ch)) || ((fan_get_duty(ch)) && (rpm_actual))
			|| ((!fan_get_duty(ch)) && (!rpm_actual)))
		return 0;

	return 1;
}

/**
 * Fan channel setup.
 *
 * @param ch        operation channel
 * @param flags     input flags
 * @return none
 */
void fan_channel_setup(int ch, unsigned int flags)
{
	fan_config(ch, (flags & FAN_USE_RPM_MODE));
}

/**
 * Fan initial.
 *
 * @param none
 * @return none
 */
static void fan_init(void)
{
#ifdef CONFIG_PWM_DSLEEP
	/* Enable the fan module and delay a few clocks */
	clock_enable_peripheral(CGC_OFFSET_FAN, CGC_FAN_MASK, CGC_MODE_ALL);
#else
	/* Enable the fan module and delay a few clocks */
	clock_enable_peripheral(CGC_OFFSET_FAN, CGC_FAN_MASK,
			CGC_MODE_RUN | CGC_MODE_SLEEP);
#endif
}
DECLARE_HOOK(HOOK_INIT, fan_init, HOOK_PRIO_INIT_PWM);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectCodeStyleSettingsManager">
    <option name="PER_PROJECT_SETTINGS">
      <value>
        <option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
      </value>
    </option>
    <option name="USE_PER_PROJECT_SETTINGS" value="true" />
  </component>
</project>

redpajama_set_name: RedPajamaGithub


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Debugger](./puppeteer.protocol.debugger.md) > [SetScriptSourceResponse](./puppeteer.protocol.debugger.setscriptsourceresponse.md) > [stackChanged](./puppeteer.protocol.debugger.setscriptsourceresponse.stackchanged.md)

## Protocol.Debugger.SetScriptSourceResponse.stackChanged property

Whether current call stack was modified after applying the changes.

<b>Signature:</b>

```typescript
stackChanged?: boolean;
```


text:
{% extends "base.html" %}
{% block content %}
    {% if LANDING_PAGE_ABOUT and LANDING_PAGE_ABOUT.details %}
      {% if LANDING_PAGE_ABOUT and LANDING_PAGE_ABOUT.title %}

{{ LANDING_PAGE_ABOUT.title }}

      {% endif %}

            {{ LANDING_PAGE_ABOUT.details }}

          {% if PORTRAIT_IMG %}

          {% endif %}

    {% endif %}

    {% if SOFTWARE %}
    <software>

Software Projects

      {% for project in SOFTWARE %}

{{ project.name }}

{{ project.description }}

      {% endfor %}
    </software>
    {% endif %}

    {% if articles %}

Posts

        {% for article in (articles_page.object_list if articles_page else articles) %}

{{ article.title }}

{{ article.summary }}
                    {# Uncomment if you want to show comment counts #}
                    {#{% include 'includes/comment_count.html' %}#}
                    more ...

        {% endfor %}
    {% endif %}

    {% if articles_page and articles_paginator.num_pages > 1 %}

            {% if articles_page.has_previous() %}
                {% set num = articles_page.previous_page_number() %}

 1 else '' }}.html">«

            {% else %}

«

            {% endif %}
            {% for num in range( 1, 1 + articles_paginator.num_pages ) %}

 1 else '' }}.html">{{ num }}

            {% endfor %}
            {% if articles_page.has_next() %}

»

            {% else %}

«

            {% endif %}

    {% endif %}
{% endblock content %}


text:
<?php
namespace Fwk\Security\User\Providers;

use Fwk\Security\User\Provider;
use Fwk\Security\Exceptions\UserNotFound;
use Fwk\Security\Exceptions\UserIsExpired;
use Fwk\Security\User;

/**
 * In memory user storage
 */
class Memory implements Provider, \IteratorAggregate, \Countable
{
    /**
     * List of "registered" users
     *
     * @var array
     */
    protected $users = array();

    /**
     * Registers a User
     *
     * @param User $user To-be-added user
     *
     * @return Memory
     */
    public function add(User $user)
    {
        $this->users[$user->getIdentifier()] = $user;

        return $this;
    }

    /**
     *
     * @param User $user To-be-removed user
     *
     * @return Memory
     */
    public function remove(User $user)
    {
        unset($this->users[$user->getIdentifier()]);

        return $this;
    }

    /**
     * Returns a User by its unique Identifier
     *
     * @param mixed $identifier User unique identifier
     *
     * @return User
     * @throws UserNotFound if no user exists under this identifier
     */
    public function getById($identifier)
    {
        if (!array_key_exists($identifier, $this->users)) {
            throw new UserNotFound(
                sprintf('User id:%s does not exists in memory.', $identifier)
            );
        }

        return $this->users[$identifier];
    }

    /**
     * Returns a User by its Username
     *
     * @param string  $userName Username
     * @param boolean $strict   Case sensitive check?
     *
     * @return User
     * @throws UserNotFound if no user exists with this username
     */
    public function getByUsername($userName, $strict = true)
    {
        $return = null;
        foreach ($this->users as $user) {
            if ($strict && $user->getUsername() === $userName
            || (!$strict &&  $user->getUsername() == $userName)) {
                $return = $user;
                break;
            }
        }

        if (!$return instanceof User) {
            throw new UserNotFound(
                sprintf('User username:%s does not exists in memory.', $userName)
            );
        }

        return $return;
    }

    /**
     * Tells if the user exists
     *
     * @param User $user
     *
     * @return boolean
     */
    public function has(User $user)
    {
        return array_key_exists($user->getIdentifier(), $this->users);
    }

    /**
     *
     * @param array $users List of User instances to be added
     *
     * @return Memory
     */
    public function addAll(array $users)
    {
        foreach ($users as $user) {
            $this->add($user);
        }

        return $this;
    }

    /**
     * Delete all users
     *
     * @return Memory
     */
    public function removeAll()
    {
        $this->users = array();

        return $this;
    }

    /**
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->users);
    }

    /**
     * Tells how many users are registered
     *
     * @return integer
     */
    public function count()
    {
        return count($this->users);
    }

    /**
     * Refreshs the User data
     *
     * @param User $user To-be-refreshed user
     *
     * @return User
     * @throws UserHasExpired if user is no longer registered
     */
    public function refresh(User $user)
    {
        if (!$this->has($user)) {
            throw new UserIsExpired();
        }

        return $user;
    }

    /**
     * Tells if this Provider can handle the User object
     *
     * @param User $user User instance to be supported
     *
     * @return boolean
     */
    public function supports(User $user)
    {
        return true;
    }

    /**
     * Factory method.
     *
     * @return Memory
     */
    public static function factory()
    {
        return new self;
    }
}


text:
'use strict';

module.exports = function(app) {
	var users = require('../../app/controllers/users.server.controller');
	var loans = require('../../app/controllers/loans.server.controller');

	// Loans Routes
	app.route('/loans')
		.get(loans.list)
		.post(users.requiresLogin, loans.create);

	app.route('/loans/:loanId')
		.get(loans.read)
		.put(users.requiresLogin, loans.hasAuthorization, loans.update)
		.delete(users.requiresLogin, loans.hasAuthorization, loans.delete);

	// Finish by binding the Loan middleware
	app.param('loanId', loans.loanByID);
};


text:
<!DOCTYPE html>

        <title>Demo</title>
        <meta name="description" content="Twitter Bootstrap Ajax Typeahead Plugin Demo">
        <meta name="keywords" content="Twitter Bootstrap, Ajax Typeahead, Plugin">
        <meta name="author" content="Alexey Gordeyev (aleksej@gordejev.lv)">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="robots" content="index, follow">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

                                          Saldo

                                            <input name="id_city1" placeholder="id city s" class="form-control" type="text"  required >

                                          Saldo1

                                            <input name="Name1" placeholder="Nombre" class="form-control" type="text"  required >

Demo #4

                        <input id="demo4" type="text" class="col-md-12 form-control" placeholder="Search cities..." autocomplete="off" />

    <button class="btn btn-success" onclick="add_person()"> Add Person</button>

          First Name
          Last Name
          Gender
          Address
          Date of Birth
          Action

              <form role="form">

                      sub total

                        $
                        <input name="firstName8" placeholder="por horas trabajadas" class="form-control" type="text">

                      Descuentos

                        $
                        <input name="firstName8" placeholder="Descuentos varios" class="form-control" type="text">

                      IVA

                        $
                        <input name="firstName8" placeholder="Iva Incluido" class="form-control" type="text">

                      Total a Pagar

                        $
                        <input name="firstName8" placeholder="Total a pagar" class="form-control" type="text">

            </form>

                            Modals

                            <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
                                Launch Demo Modal
                            </button>

                                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal title

                                            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                            <button type="button" class="btn btn-primary">Save changes</button>


text:
package org.conqat.engine.core.core;

/**
 * The interface for ConQAT processors.
 *
 * @author Benjamin Hummel
 * @author Lukas D. Kuhn
 * @author $Author: kinnen $
 *
 * @version $Rev: 41751 $
 * @ConQAT.Rating GREEN Hash: 929B97A15A2277CDA28A5F6A159DA5B5
 */
public interface IConQATProcessor {

	/**
	 * Initialization of the processor. The processor will receive information
	 * on itself and its execution context via this function.
	 *

	 * This method is guaranteed to be called exactly once for each processor
	 * object, and before any other method is called on it. This way the
	 * processor can use this {@link IConQATProcessorInfo} in its setters
	 * already.
	 *
	 * @param processorInfo
	 *            information about the runtime context in which the processor
	 *            is executed.
	 */
	public void init(IConQATProcessorInfo processorInfo) throws ConQATException;

	/**
	 * Perform processing on the parameters provided earlier and return the
	 * result. You should use covariance to supply a more specialized return
	 * type in your implementation, as the return type is used for type checking
	 * when using the result of this processor as input to another processor.
	 *

	 * Most processors will accept additional parameters. To make these visible
	 * from the XML configuration file, the driver requires hints in the form of
	 * annotations. Details on the available annotations and their usage can be
	 * found in the package documentation: {@link org.conqat.engine.core.core}
	 *
	 * @return the result from this processor's execution.
	 * @throws ConQATException
	 *             if something goes wrong.
	 */
	public Object process() throws ConQATException;
}


text:
#ifndef SURVIVAL_FOREST_DATA_H_
#define SURVIVAL_FOREST_DATA_H_

#include <vector>
#include <iostream>
#include <numeric>
#include <random>
#include <algorithm>
#include <utility>

#include "survival_forest_globals.h"

namespace ranger {

	class Data {
	public:
		Data();

		Data(const Data&) = delete;

		Data(std::vector<double> data, std::vector<std::string> variable_names, size_t num_rows, size_t num_cols) :
		  data { std::move(data) } {
			this->variable_names = variable_names;
			this->num_rows = num_rows;
			this->num_cols = num_cols;
			this->num_cols_no_snp = num_cols;
		}

		Data& operator=(const Data&) = delete;

		virtual ~Data() = default;

		double get(size_t row, size_t col) const  {
			// Use permuted data for corrected impurity importance
			if (col >= num_cols) {
				col = getUnpermutedVarID(col);
				row = getPermutedSampleID(row);
			}

			if (col < num_cols_no_snp) {
				return data[col * num_rows + row];
			}
		};

		size_t getVariableID(const std::string& variable_name) const;

		void reserveMemory()  {
			data.resize(num_cols * num_rows);
		};

		void set(size_t col, size_t row, double value, bool& error) {
			data[col * num_rows + row] = value;
		}
		;

		void getAllValues(std::vector<double>& all_values, std::vector<size_t>& sampleIDs, size_t varID) const;

		void getMinMaxValues(double& min, double&max, std::vector<size_t>& sampleIDs, size_t varID) const;

		size_t getIndex(size_t row, size_t col) const {
			// Use permuted data for corrected impurity importance
			if (col >= num_cols) {
				col = getUnpermutedVarID(col);
				row = getPermutedSampleID(row);
			}

			if (col < num_cols_no_snp) {
				return index_data[col * num_rows + row];
			}
		}

		void loadData(std::vector <std::vector<double> > Input_Data, std::vector<std::string> variable_names){
			this->variable_names = variable_names;
			this->num_rows = Input_Data.size();
			this->num_cols = variable_names.size();
			this->num_cols_no_snp = this->num_cols;

			size_t row;
			size_t column ;
			bool error = false;
			reserveMemory();
			for(row = 0; row < this->num_rows; row++){

				for(column = 0; column < this->num_cols; column++){
						set(column, row, Input_Data[row][column], error);
				}

			}

		}

		double getUniqueDataValue(size_t varID, size_t index) const {
			// Use permuted data for corrected impurity importance
			if (varID >= num_cols) {
				varID = getUnpermutedVarID(varID);
			}

			if (varID < num_cols_no_snp) {
				return unique_data_values[varID][index];
			} else {
				// For GWAS data the index is the value
				return (index);
			}
		}

		size_t getNumUniqueDataValues(size_t varID) const {
			// Use permuted data for corrected impurity importance
			if (varID >= num_cols) {
				varID = getUnpermutedVarID(varID);
			}

			if (varID < num_cols_no_snp) {
				return unique_data_values[varID].size();
			} else {
				// For GWAS data 0,1,2
				return (3);
			}
		}

		void sort();

		const std::vector<std::string>& getVariableNames() const {
			return variable_names;
		}
		size_t getNumCols() const {
			return num_cols;
		}
		size_t getNumRows() const {
			return num_rows;
		}

		size_t getMaxNumUniqueValues() const {
			if (snp_data == 0 || max_num_unique_values > 3) {
				// If no snp data or one variable with more than 3 unique values, return that value
				return max_num_unique_values;
			} else {
				// If snp data and no variable with more than 3 unique values, return 3
				return 3;
			}
		}

		const std::vector<size_t>& getNoSplitVariables() const noexcept {
			return no_split_variables;
		}

		void addNoSplitVariable(size_t varID) {
			no_split_variables.push_back(varID);
			std::sort(no_split_variables.begin(), no_split_variables.end());
		}

		std::vector<bool>& getIsOrderedVariable() noexcept {
			return is_ordered_variable;
		}

		void setIsOrderedVariable(const std::vector<std::string>& unordered_variable_names) {
			is_ordered_variable.resize(num_cols, true);
			for (auto& variable_name : unordered_variable_names) {
				size_t varID = getVariableID(variable_name);
				is_ordered_variable[varID] = false;
			}
		}

		void setIsOrderedVariable(std::vector<bool>& is_ordered_variable) {
			this->is_ordered_variable = is_ordered_variable;
		}

		bool isOrderedVariable(size_t varID) const {
			// Use permuted data for corrected impurity importance
			if (varID >= num_cols) {
				varID = getUnpermutedVarID(varID);
			}
			return is_ordered_variable[varID];
		}

		void permuteSampleIDs(std::mt19937_64 random_number_generator) {
			permuted_sampleIDs.resize(num_rows);
			std::iota(permuted_sampleIDs.begin(), permuted_sampleIDs.end(), 0);
			std::shuffle(permuted_sampleIDs.begin(), permuted_sampleIDs.end(), random_number_generator);
		}

		size_t getPermutedSampleID(size_t sampleID) const {
			return permuted_sampleIDs[sampleID];
		}

		size_t getUnpermutedVarID(size_t varID) const {
			if (varID >= num_cols) {
				varID -= num_cols;

				for (auto& skip : no_split_variables) {
					if (varID >= skip) {
						++varID;
					}
				}
			}
			return varID;
		}

	private:
		std::vector<double> data;

	protected:
		std::vector<std::string> variable_names;
		size_t num_rows;
		size_t num_rows_rounded;
		size_t num_cols;

		unsigned char* snp_data;
		size_t num_cols_no_snp;

		bool externalData;

		std::vector<size_t> index_data;
		std::vector<std::vector<double>> unique_data_values;
		size_t max_num_unique_values;

		// Variable to not split at (only dependent_varID for non-survival trees)
		std::vector<size_t> no_split_variables;

		// For each varID true if ordered
		std::vector<bool> is_ordered_variable;

		// Permuted samples for corrected impurity importance
		std::vector<size_t> permuted_sampleIDs;

		// Order of 0/1/2 for ordered splitting
		std::vector<std::vector<size_t>> snp_order;
		bool order_snps;
	};

} // namespace ranger

#endif /* SURVIVAL_FOREST_DATA_H_ */


text:
<?php

return [
    'plugin' => [
        'name' =>  'SEO Rozšíření',
        'description' => 'Poskytuje SEO rozšíření pro CMS stránky, statické stránky a blogové články',
    ],
    'settings' => [
        'label' => 'SEO Rozšíření',
        'description' => 'Konfigurace SEO Rozšíření',
        'tab_settings' => [
            'label' => 'Nastavení',
            'site' => 'Použít název stránku v titulku stránky',
            'site_comment' => 'Aktivujte pokud chcete použít název stránek v tagu <title>',
            'sitename' => 'Název stránek',
            'canonical' => 'Použít výchozí URL jako kanonickou URL',
            'canonical_comment' => 'Pokud není kanonická URL zadána, poté se použije výchozí URL jako kanonická',
            'sitename_comment_above' => 'Předpona nebo přípona názvu stránek v tagu <title>',
            'sitename_comment' => 'Název stránek | <nadpis seo/stránky/blogu>',
            'sitename_placeholder' => 'Název stránek |',
            'title_position' => 'Název stránek se ukáže',
            'title_position_comment' => 'Vyberte kde se má název stránek zobrazovat, jestli na začátku, nebo na konci',
            'title_position_prefix' => 'Předpona (na začátku)',
            'title_position_suffix' => 'Přípona (na konci)',
            'other_tags' => 'Ostatní meta tagy',
            'other_tags_comment_above' => 'Zadejte tagy které chcete přidat na všech stránkách',
            'other_tags_comment' => 'Zadejte meta tagy jako například meta author, meta viewport a další',
        ],
        'tab_og' => [
            'label' => 'Open Graph',
            'og' => 'Použít Open Graph (og)',
            'og_comment' => 'Aktivovat Open Graph (og) tagy',
            'sitename' => 'Název stránek pro Open Graph',
            'sitename_comment' => 'Název stránek. Ne URL. Například "SEO Extension" ne "seoextension.com".',
            'fb' => 'ID Facebook Aplikace',
            'fb_comment' => 'Unikátní ID podle kterých dokáže Facebook identifikovat vaše stránky.',
        ],
    ],
    'component' => [
        'blog' => [
            'name' => 'SEO Blogového článku',
            'description' => 'Přidá SEO pole k blogovému článku',
        ],
        'cms' => [
            'name' => 'SEO CMS stránky',
            'description' => 'Přidá SEO pole k CMS stránce',
        ],
        'static' => [
            'name' => 'SEO Statiké stránky',
            'description' => 'Přidá SEO pole k statické stránce',
        ],
    ],
];


text:
from zang.domain.list.base_list import BaseList
from zang.domain.participant import Participant

class Participants(BaseList):

    _arrays = {'participants': Participant}

    def __init__(self):
        super(Participants, self).__init__()

    @property
    def elements(self):
        return self._participants


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Reticularia argentea Poir.

### Remarks
null


text:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE DuplicateRecordFields #-}

module TextEditor where

import qualified System.Console.Terminal.Size  as TS
-- import qualified Data.Sequence as S
import qualified Data.Map as M
import System.Posix.Signals

import TextBuffer
import Prelude as P
import View
import Layout
import Highlight
import Keys
import TTYRender

data BufferManager = BufferManager {textBuffers :: M.Map String Buffer}

-- top left buffer offset
data EditBuffer = EditBuffer Int Int Buffer

instance Show EditBuffer where
  show _ = "EditBuffer"

instance LayoutClass EditBuffer where
  doLayout (Rect t l w h) (EditBuffer row col b) = do
    -- Layout is 0 based, TTY renderer is 1 based
    let viewState = ViewState row col (t+1) (l+1) w h
    draw viewState b
  layoutSize _ = 1
  updateLayout _ 0 n = n
  updateLayout a _ _ = Layout a
  getLayout r a _ = (r, Layout a)

data AppState = AppState { activeLayoutIndex :: Int
                         , layout :: Root
                         , bufferManager :: BufferManager
                         }

updateBuffer :: Keys -> Buffer -> Buffer
updateBuffer k b@Buffer{..} = b' where
   b' = case k of
    Alpha x -> insertCharacter x b
    Backspace | P.null selection -> deleteCharacter b
    Backspace -> deleteSelection b
    CarriageReturn -> breakLine b
    CursorUp -> cursorUp b
    CursorDown -> cursorDown b
    CursorLeft -> cursorLeft b
    CursorRight -> cursorRight b
    End -> endOfLine b
    Home -> startOfLine b
    Alt 'a' -> startSelection b
    Alt _ -> undo b
    Ctrl 'z' -> undo b
    _ -> b

newTop :: Int -> Int -> Int -> Int
newTop top height row | row >= top + height = row - height + 1
newTop top _ row | row < top = row
newTop top _ _  = top

scrollView :: EditBuffer -> Rect -> EditBuffer
scrollView a@(EditBuffer top left b) (Rect t l w h) = EditBuffer top' left' b where
  top' = newTop top h (line (cursor b))
  left' = newTop left w (col (cursor b))

gLayout :: AppState -> Root
gLayout = layout

loop :: AppState -> IO()
loop as@AppState{..} = do
  key <- readKeys
  let (Root win rootLayout) = layout
      (ar, ab) = getLayout win rootLayout activeLayoutIndex
      as' = case (fromLayout ab :: Maybe EditBuffer) of
        Just (EditBuffer row col b) -> as'' where
          b'' = updateSelection $ updateBuffer key b{contentChanged = False}
          dirty = contentChanged b''
          b' = if dirty then  b''{regions  =  highLight (content b'')}  else b'' -- Still too often but better
          eb' = scrollView (EditBuffer row col b') ar
  -- Update the buffer ref in the layout
          layout' = updateRoot layout activeLayoutIndex (Layout eb')
          as'' = as{layout = layout'}
        Nothing -> error "reference to none buffer"
  -- P.putStr (toPos 30 0 ++  show (selection b'))
  layoutRoot (gLayout as')
  loop as'

init :: [(String, Buffer)] -> IO()
init buffers = do
  -- env <- getEnvironment
  -- Prevent Ctrl-Z from suspending the app
  let signalSet = addSignal sigTSTP emptySignalSet
  blockSignals signalSet
  initTTY

  Just sz <- TS.size

  let bufferManager = BufferManager (M.fromList buffers)
      buffer = snd $ head buffers
      window = Rect 0 0 (TS.width sz) 50
      layout = Root window $ Layout (HSplit 14 (Layout (EditBuffer 0 0 buffer)) (Layout (EditBuffer 0 0 buffer)))
      as = AppState 2 layout bufferManager

  case layout of
    Root r l -> do
      print l
      print $ getLayout r l 0
      print $ getLayout r l 1
      print $ getLayout r l 2
  -- error "Ow"

  loop as
  putStrLn "Hello"


text:
#include "Arduino.h"
#include "Srf05.h"

Srf05::Srf05(int pin){
	_pin = pin;
	pinMode(_pin,OUTPUT);
	digitalWrite(_pin, LOW);
}

int Srf05::getData(){
	int sample;
	/* Send a 15us ping */
	pinMode(_pin,OUTPUT);
	digitalWrite(_pin, HIGH);
	delayMicroseconds(10);
	digitalWrite(_pin,LOW);
	/* Read a pulse */
	pinMode(_pin,INPUT);
	sample = pulseIn(_pin,HIGH,5000);
    /* Convert the pulse to distance (us/148 = inch) (us/58=cm) */
	sample = sample/58;
	return sample;
}

/* Revisions
 * 5/5/09 - Changed delay(15) to delayMicroseconds(10) as per notes on
 *          http://robot-electronics.co.uk/htm/arduino_examples.htm
 */


text:
package edu.ku.eecs.agiledev.core;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import edu.ku.eecs.agiledev.floorplan.ServableTable;
import edu.ku.eecs.agiledev.menu.Menu;
import edu.ku.eecs.agiledev.ticket.Ticket;
import edu.ku.eecs.agiledev.users.BaseUser;

/**
 *
 * @author hgrimberg
 *
 */
public class Restaurant implements java.io.Serializable {
	/**
	 *
	 */
	private static final long serialVersionUID = -1302782511204573451L;

	private List<Menu> menus;
	private List<BaseUser> users;
	private List<ServableTable> tables;
	private List<Tax> taxes;
	private Map<UUID,Ticket> openTickets;

	public Restaurant() {

	}

	/**
	 * @return the menus
	 */
	public List<Menu> getMenus() {
		return menus;
	}

	/**
	 * @param menus
	 *            the menus to set
	 */
	public void setMenus(List<Menu> menus) {
		this.menus = menus;
	}

	/**
	 * @return the users
	 */
	public List<BaseUser> getUsers() {
		return users;
	}

	/**
	 * @param users
	 *            the users to set
	 */
	public void setUsers(List<BaseUser> users) {
		this.users = users;
	}

	/**
	 * @return the tables
	 */
	public List<ServableTable> getTables() {
		return tables;
	}

	/**
	 * @param tables
	 *            the tables to set
	 */
	public void setTables(List<ServableTable> tables) {
		this.tables = tables;
	}

	/**
	 * @return the taxes
	 */
	public List<Tax> getTaxes() {
		return taxes;
	}

	/**
	 * @param taxes the taxes to set
	 */
	public void setTaxes(List<Tax> taxes) {
		this.taxes = taxes;
	}

	/**
	 * @return the openTickets
	 */
	public Map<UUID,Ticket> getOpenTickets() {
		return openTickets;
	}

	/**
	 * @param openTickets the openTickets to set
	 */
	public void setOpenTickets(Map<UUID,Ticket> openTickets) {
		this.openTickets = openTickets;
	}

}


text:
SET client_encoding TO 'UTF8';

CREATE OR REPLACE FUNCTION ag_authenticate_user (
  ag_kit_id_ in text,
  kit_password_ in text,
  user_data in out refcursor
)
 RETURNS refcursor AS $body$
BEGIN

  open user_data for
    SELECT  cast(agl.ag_login_id as varchar(100)) as ag_login_id,
            agl.email, agl.name, agl.address, agl.city,
            agl.state, agl.zip, agl.country
    from    ag_login agl
            inner join ag_kit agk
            on agl.ag_login_id = agk.ag_login_id
    where   agk.supplied_kit_id = ag_kit_id_
            and agk.kit_password = kit_password_;

end;
/*BEGIN;
emte4531=# select ag_authenticate_user('DctkP', 'z077$Wcz', 'a');
select all in a;
COMMIT;
*/

$body$
LANGUAGE PLPGSQL;


text:
package cdn

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/Azure/go-autorest/autorest"
)

// CustomDomainResourceState enumerates the values for custom domain resource state.
type CustomDomainResourceState string

const (
	// Active specifies the active state for custom domain resource state.
	Active CustomDomainResourceState = "Active"
	// Creating specifies the creating state for custom domain resource state.
	Creating CustomDomainResourceState = "Creating"
	// Deleting specifies the deleting state for custom domain resource state.
	Deleting CustomDomainResourceState = "Deleting"
)

// EndpointResourceState enumerates the values for endpoint resource state.
type EndpointResourceState string

const (
	// EndpointResourceStateCreating specifies the endpoint resource state creating state for endpoint resource state.
	EndpointResourceStateCreating EndpointResourceState = "Creating"
	// EndpointResourceStateDeleting specifies the endpoint resource state deleting state for endpoint resource state.
	EndpointResourceStateDeleting EndpointResourceState = "Deleting"
	// EndpointResourceStateRunning specifies the endpoint resource state running state for endpoint resource state.
	EndpointResourceStateRunning EndpointResourceState = "Running"
	// EndpointResourceStateStarting specifies the endpoint resource state starting state for endpoint resource state.
	EndpointResourceStateStarting EndpointResourceState = "Starting"
	// EndpointResourceStateStopped specifies the endpoint resource state stopped state for endpoint resource state.
	EndpointResourceStateStopped EndpointResourceState = "Stopped"
	// EndpointResourceStateStopping specifies the endpoint resource state stopping state for endpoint resource state.
	EndpointResourceStateStopping EndpointResourceState = "Stopping"
)

// OriginResourceState enumerates the values for origin resource state.
type OriginResourceState string

const (
	// OriginResourceStateActive specifies the origin resource state active state for origin resource state.
	OriginResourceStateActive OriginResourceState = "Active"
	// OriginResourceStateCreating specifies the origin resource state creating state for origin resource state.
	OriginResourceStateCreating OriginResourceState = "Creating"
	// OriginResourceStateDeleting specifies the origin resource state deleting state for origin resource state.
	OriginResourceStateDeleting OriginResourceState = "Deleting"
)

// ProfileResourceState enumerates the values for profile resource state.
type ProfileResourceState string

const (
	// ProfileResourceStateActive specifies the profile resource state active state for profile resource state.
	ProfileResourceStateActive ProfileResourceState = "Active"
	// ProfileResourceStateCreating specifies the profile resource state creating state for profile resource state.
	ProfileResourceStateCreating ProfileResourceState = "Creating"
	// ProfileResourceStateDeleting specifies the profile resource state deleting state for profile resource state.
	ProfileResourceStateDeleting ProfileResourceState = "Deleting"
	// ProfileResourceStateDisabled specifies the profile resource state disabled state for profile resource state.
	ProfileResourceStateDisabled ProfileResourceState = "Disabled"
)

// ProvisioningState enumerates the values for provisioning state.
type ProvisioningState string

const (
	// ProvisioningStateCreating specifies the provisioning state creating state for provisioning state.
	ProvisioningStateCreating ProvisioningState = "Creating"
	// ProvisioningStateFailed specifies the provisioning state failed state for provisioning state.
	ProvisioningStateFailed ProvisioningState = "Failed"
	// ProvisioningStateSucceeded specifies the provisioning state succeeded state for provisioning state.
	ProvisioningStateSucceeded ProvisioningState = "Succeeded"
)

// QueryStringCachingBehavior enumerates the values for query string caching behavior.
type QueryStringCachingBehavior string

const (
	// BypassCaching specifies the bypass caching state for query string caching behavior.
	BypassCaching QueryStringCachingBehavior = "BypassCaching"
	// IgnoreQueryString specifies the ignore query string state for query string caching behavior.
	IgnoreQueryString QueryStringCachingBehavior = "IgnoreQueryString"
	// NotSet specifies the not set state for query string caching behavior.
	NotSet QueryStringCachingBehavior = "NotSet"
	// UseQueryString specifies the use query string state for query string caching behavior.
	UseQueryString QueryStringCachingBehavior = "UseQueryString"
)

// ResourceType enumerates the values for resource type.
type ResourceType string

const (
	// MicrosoftCdnProfilesEndpoints specifies the microsoft cdn profiles endpoints state for resource type.
	MicrosoftCdnProfilesEndpoints ResourceType = "Microsoft.Cdn/Profiles/Endpoints"
)

// SkuName enumerates the values for sku name.
type SkuName string

const (
	// CustomVerizon specifies the custom verizon state for sku name.
	CustomVerizon SkuName = "Custom_Verizon"
	// PremiumVerizon specifies the premium verizon state for sku name.
	PremiumVerizon SkuName = "Premium_Verizon"
	// StandardAkamai specifies the standard akamai state for sku name.
	StandardAkamai SkuName = "Standard_Akamai"
	// StandardVerizon specifies the standard verizon state for sku name.
	StandardVerizon SkuName = "Standard_Verizon"
)

// CheckNameAvailabilityInput is input of CheckNameAvailability API.
type CheckNameAvailabilityInput struct {
	Name *string `json:"name,omitempty"`
	Type *string `json:"type,omitempty"`
}

// CheckNameAvailabilityOutput is output of check name availability API.
type CheckNameAvailabilityOutput struct {
	autorest.Response `json:"-"`
	NameAvailable     *bool   `json:"NameAvailable,omitempty"`
	Reason            *string `json:"Reason,omitempty"`
	Message           *string `json:"Message,omitempty"`
}

// CustomDomain is CDN CustomDomain represents a mapping between a user specified domain name and a CDN endpoint. This
// is to use custom domain names to represent the URLs for branding purposes.
type CustomDomain struct {
	autorest.Response       `json:"-"`
	ID                      *string `json:"id,omitempty"`
	Name                    *string `json:"name,omitempty"`
	Type                    *string `json:"type,omitempty"`
	*CustomDomainProperties `json:"properties,omitempty"`
}

// CustomDomainListResult is
type CustomDomainListResult struct {
	autorest.Response `json:"-"`
	Value             *[]CustomDomain `json:"value,omitempty"`
}

// CustomDomainParameters is customDomain properties required for custom domain creation or update.
type CustomDomainParameters struct {
	*CustomDomainPropertiesParameters `json:"properties,omitempty"`
}

// CustomDomainProperties is
type CustomDomainProperties struct {
	HostName          *string                   `json:"hostName,omitempty"`
	ResourceState     CustomDomainResourceState `json:"resourceState,omitempty"`
	ProvisioningState ProvisioningState         `json:"provisioningState,omitempty"`
}

// CustomDomainPropertiesParameters is
type CustomDomainPropertiesParameters struct {
	HostName *string `json:"hostName,omitempty"`
}

// DeepCreatedOrigin is deep created origins within a CDN endpoint.
type DeepCreatedOrigin struct {
	Name                         *string `json:"name,omitempty"`
	*DeepCreatedOriginProperties `json:"properties,omitempty"`
}

// DeepCreatedOriginProperties is properties of deep created origin on a CDN endpoint.
type DeepCreatedOriginProperties struct {
	HostName  *string `json:"hostName,omitempty"`
	HTTPPort  *int32  `json:"httpPort,omitempty"`
	HTTPSPort *int32  `json:"httpsPort,omitempty"`
}

// Endpoint is CDN endpoint is the entity within a CDN profile containing configuration information regarding caching
// behaviors and origins. The CDN endpoint is exposed using the URL format <endpointname>.azureedge.net by default, but
// custom domains can also be created.
type Endpoint struct {
	autorest.Response   `json:"-"`
	ID                  *string             `json:"id,omitempty"`
	Name                *string             `json:"name,omitempty"`
	Type                *string             `json:"type,omitempty"`
	Location            *string             `json:"location,omitempty"`
	Tags                *map[string]*string `json:"tags,omitempty"`
	*EndpointProperties `json:"properties,omitempty"`
}

// EndpointCreateParameters is endpoint properties required for new endpoint creation.
type EndpointCreateParameters struct {
	Location                            *string             `json:"location,omitempty"`
	Tags                                *map[string]*string `json:"tags,omitempty"`
	*EndpointPropertiesCreateParameters `json:"properties,omitempty"`
}

// EndpointListResult is
type EndpointListResult struct {
	autorest.Response `json:"-"`
	Value             *[]Endpoint `json:"value,omitempty"`
}

// EndpointProperties is
type EndpointProperties struct {
	HostName                   *string                    `json:"hostName,omitempty"`
	OriginHostHeader           *string                    `json:"originHostHeader,omitempty"`
	OriginPath                 *string                    `json:"originPath,omitempty"`
	ContentTypesToCompress     *[]string                  `json:"contentTypesToCompress,omitempty"`
	IsCompressionEnabled       *bool                      `json:"isCompressionEnabled,omitempty"`
	IsHTTPAllowed              *bool                      `json:"isHttpAllowed,omitempty"`
	IsHTTPSAllowed             *bool                      `json:"isHttpsAllowed,omitempty"`
	QueryStringCachingBehavior QueryStringCachingBehavior `json:"queryStringCachingBehavior,omitempty"`
	Origins                    *[]DeepCreatedOrigin       `json:"origins,omitempty"`
	ResourceState              EndpointResourceState      `json:"resourceState,omitempty"`
	ProvisioningState          ProvisioningState          `json:"provisioningState,omitempty"`
}

// EndpointPropertiesCreateParameters is
type EndpointPropertiesCreateParameters struct {
	OriginHostHeader           *string                    `json:"originHostHeader,omitempty"`
	OriginPath                 *string                    `json:"originPath,omitempty"`
	ContentTypesToCompress     *[]string                  `json:"contentTypesToCompress,omitempty"`
	IsCompressionEnabled       *bool                      `json:"isCompressionEnabled,omitempty"`
	IsHTTPAllowed              *bool                      `json:"isHttpAllowed,omitempty"`
	IsHTTPSAllowed             *bool                      `json:"isHttpsAllowed,omitempty"`
	QueryStringCachingBehavior QueryStringCachingBehavior `json:"queryStringCachingBehavior,omitempty"`
	Origins                    *[]DeepCreatedOrigin       `json:"origins,omitempty"`
}

// EndpointPropertiesUpdateParameters is
type EndpointPropertiesUpdateParameters struct {
	OriginHostHeader           *string                    `json:"originHostHeader,omitempty"`
	OriginPath                 *string                    `json:"originPath,omitempty"`
	ContentTypesToCompress     *[]string                  `json:"contentTypesToCompress,omitempty"`
	IsCompressionEnabled       *bool                      `json:"isCompressionEnabled,omitempty"`
	IsHTTPAllowed              *bool                      `json:"isHttpAllowed,omitempty"`
	IsHTTPSAllowed             *bool                      `json:"isHttpsAllowed,omitempty"`
	QueryStringCachingBehavior QueryStringCachingBehavior `json:"queryStringCachingBehavior,omitempty"`
}

// EndpointUpdateParameters is endpoint properties required for new endpoint creation.
type EndpointUpdateParameters struct {
	Tags                                *map[string]*string `json:"tags,omitempty"`
	*EndpointPropertiesUpdateParameters `json:"properties,omitempty"`
}

// ErrorResponse is
type ErrorResponse struct {
	autorest.Response `json:"-"`
	Code              *string `json:"code,omitempty"`
	Message           *string `json:"message,omitempty"`
}

// LoadParameters is parameters required for endpoint load.
type LoadParameters struct {
	ContentPaths *[]string `json:"contentPaths,omitempty"`
}

// Operation is CDN REST API operation
type Operation struct {
	Name    *string           `json:"name,omitempty"`
	Display *OperationDisplay `json:"display,omitempty"`
}

// OperationDisplay is
type OperationDisplay struct {
	Provider  *string `json:"provider,omitempty"`
	Resource  *string `json:"resource,omitempty"`
	Operation *string `json:"operation,omitempty"`
}

// OperationListResult is
type OperationListResult struct {
	autorest.Response `json:"-"`
	Value             *[]Operation `json:"value,omitempty"`
}

// Origin is CDN origin is the source of the content being delivered via CDN. When the edge nodes represented by an
// endpoint do not have the requested content cached, they attempt to fetch it from one or more of the configured
// origins.
type Origin struct {
	autorest.Response `json:"-"`
	ID                *string `json:"id,omitempty"`
	Name              *string `json:"name,omitempty"`
	Type              *string `json:"type,omitempty"`
	*OriginProperties `json:"properties,omitempty"`
}

// OriginListResult is
type OriginListResult struct {
	autorest.Response `json:"-"`
	Value             *[]Origin `json:"value,omitempty"`
}

// OriginParameters is origin properties needed for origin creation or update.
type OriginParameters struct {
	*OriginPropertiesParameters `json:"properties,omitempty"`
}

// OriginProperties is
type OriginProperties struct {
	HostName          *string             `json:"hostName,omitempty"`
	HTTPPort          *int32              `json:"httpPort,omitempty"`
	HTTPSPort         *int32              `json:"httpsPort,omitempty"`
	ResourceState     OriginResourceState `json:"resourceState,omitempty"`
	ProvisioningState ProvisioningState   `json:"provisioningState,omitempty"`
}

// OriginPropertiesParameters is
type OriginPropertiesParameters struct {
	HostName  *string `json:"hostName,omitempty"`
	HTTPPort  *int32  `json:"httpPort,omitempty"`
	HTTPSPort *int32  `json:"httpsPort,omitempty"`
}

// Profile is CDN profile represents the top level resource and the entry point into the CDN API. This allows users to
// set up a logical grouping of endpoints in addition to creating shared configuration settings and selecting pricing
// tiers and providers.
type Profile struct {
	autorest.Response  `json:"-"`
	ID                 *string             `json:"id,omitempty"`
	Name               *string             `json:"name,omitempty"`
	Type               *string             `json:"type,omitempty"`
	Location           *string             `json:"location,omitempty"`
	Tags               *map[string]*string `json:"tags,omitempty"`
	Sku                *Sku                `json:"sku,omitempty"`
	*ProfileProperties `json:"properties,omitempty"`
}

// ProfileCreateParameters is profile properties required for profile creation.
type ProfileCreateParameters struct {
	Location *string             `json:"location,omitempty"`
	Tags     *map[string]*string `json:"tags,omitempty"`
	Sku      *Sku                `json:"sku,omitempty"`
}

// ProfileListResult is
type ProfileListResult struct {
	autorest.Response `json:"-"`
	Value             *[]Profile `json:"value,omitempty"`
}

// ProfileProperties is
type ProfileProperties struct {
	ResourceState     ProfileResourceState `json:"resourceState,omitempty"`
	ProvisioningState ProvisioningState    `json:"provisioningState,omitempty"`
}

// ProfileUpdateParameters is profile properties required for profile update.
type ProfileUpdateParameters struct {
	Tags *map[string]*string `json:"tags,omitempty"`
}

// PurgeParameters is parameters required for endpoint purge.
type PurgeParameters struct {
	ContentPaths *[]string `json:"contentPaths,omitempty"`
}

// Resource is
type Resource struct {
	ID   *string `json:"id,omitempty"`
	Name *string `json:"name,omitempty"`
	Type *string `json:"type,omitempty"`
}

// Sku is the SKU (pricing tier) of the CDN profile.
type Sku struct {
	Name SkuName `json:"name,omitempty"`
}

// SsoURI is SSO URI required to login to third party web portal.
type SsoURI struct {
	autorest.Response `json:"-"`
	SsoURIValue       *string `json:"ssoUriValue,omitempty"`
}

// TrackedResource is ARM tracked resource
type TrackedResource struct {
	ID       *string             `json:"id,omitempty"`
	Name     *string             `json:"name,omitempty"`
	Type     *string             `json:"type,omitempty"`
	Location *string             `json:"location,omitempty"`
	Tags     *map[string]*string `json:"tags,omitempty"`
}

// ValidateCustomDomainInput is input of the custom domain to be validated.
type ValidateCustomDomainInput struct {
	HostName *string `json:"hostName,omitempty"`
}

// ValidateCustomDomainOutput is output of custom domain validation.
type ValidateCustomDomainOutput struct {
	autorest.Response     `json:"-"`
	CustomDomainValidated *bool   `json:"customDomainValidated,omitempty"`
	Reason                *string `json:"reason,omitempty"`
	Message               *string `json:"message,omitempty"`
}


text:
namespace HanRuEdu.LDAL
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    [MetadataType(typeof(EDU_ZXJZ_20_A09_XSPJPJ_metadata))]
    public partial class EDU_ZXJZ_20_A09_XSPJPJ
    {
        public EDU_ZXJZ_20_A09_XSPJPJ()
        {
            IP = "";
            PJNR = "";
        }
        public class EDU_ZXJZ_20_A09_XSPJPJ_metadata
        {
            [Required(ErrorMessage = "±ØÌî")]
            [Display(Name = "񅧏")]
            public Int32 ID { get; set; }

            [Required(ErrorMessage = "±ØÌî")]
            [Display(Name = "ѧУ")]
            public Int32 SCHOOLID { get; set; }

            [Required(ErrorMessage = "±ØÌî")]
            [Display(Name = "¿¼ÆÀ°à¼¶")]
            public Int32 KPBJID { get; set; }

            [Required(ErrorMessage = "±ØÌî")]
            [Display(Name = "½ÌÖ°¹¤")]
            public Int32 JZGJBSJID { get; set; }

            [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)]
            [Display(Name = "IPµØÖ·")]
            [StringLength(50)]
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public String IP { get; set; }

            [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)]
            [Display(Name = "ÆÀ¼ÛÄÚÈÝ")]
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public String PJNR { get; set; }

        }
    }
}


text:
module Sandthorn
  module AggregateRoot
    module Marshal

      def aggregate_initialize *args
        @aggregate_attribute_deltas = {}
        @aggregate_stored_instance_variables = {}
      end

      def set_instance_variables! attribute
        super attribute
        init_vars = extract_relevant_aggregate_instance_variables

        init_vars.each do |attribute_name|
          @aggregate_stored_instance_variables[attribute_name] =
            ::Marshal.dump(instance_variable_get(attribute_name))
        end
      end

      def get_delta
        deltas = extract_relevant_aggregate_instance_variables
        deltas.each { |d| delta_attribute(d) }

        result = @aggregate_attribute_deltas
        clear_aggregate_deltas
        result
      end

      private

      def delta_attribute attribute_name
        old_dump = @aggregate_stored_instance_variables[attribute_name]
        new_dump = ::Marshal.dump(instance_variable_get(attribute_name))

        unless old_dump == new_dump
          store_attribute_deltas attribute_name, new_dump, old_dump
          store_aggregate_instance_variable attribute_name, new_dump
        end
      end

      def store_attribute_deltas attribute_name, new_dump, old_dump
        new_value_to_store = ::Marshal.load(new_dump)
        old_value_to_store = old_dump ? ::Marshal.load(old_dump) : nil

        @aggregate_attribute_deltas[attribute_name.to_s.delete("@").to_sym] = {
          old_value: old_value_to_store,
          new_value: new_value_to_store
        }
      end

      def store_aggregate_instance_variable attribute_name, new_dump
        @aggregate_stored_instance_variables[attribute_name] = new_dump
      end

      def clear_aggregate_deltas
        @aggregate_attribute_deltas = {}
      end
    end
  end
end


text:
package com.yahoo.leastsquare;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.apache.pig.Algebraic;
import org.apache.pig.EvalFunc;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
/**
 * Test class for Algebraic
 * @author zhenouyang
 */
public class Count extends EvalFunc<Long> implements Algebraic{
    public Long exec(Tuple input) throws IOException {return count(input);}

    public String getInitial() {return Initial.class.getName();}
    public String getIntermed() {return Intermed.class.getName();}
    public String getFinal() {return Final.class.getName();}

    static public class Initial extends EvalFunc<Tuple> {
        public Tuple exec(Tuple input) throws IOException {return TupleFactory.getInstance().newTuple(count(input));}
    }
    static public class Intermed extends EvalFunc<Tuple> {
        public Tuple exec(Tuple input) throws IOException {return TupleFactory.getInstance().newTuple(sum(input));}
    }
    static public class Final extends EvalFunc<Long> {
        public Long exec(Tuple input) throws IOException {return sum(input);}
    }
    static protected Long count(Tuple input) throws ExecException {
        Object values = input.get(0);
        if (values instanceof DataBag) return ((DataBag)values).size();
        else if (values instanceof Map) return new Long(((Map)values).size());
        return new Long(1);
    }
    static protected Long sum(Tuple input) throws ExecException, NumberFormatException {
        DataBag values = (DataBag)input.get(0);
        long sum = 0;
        for (Iterator it = values.iterator(); it.hasNext();) {
            Tuple t = (Tuple)it.next();
            sum += (Long)t.get(0);
        }
        return sum;
    }
}


text:
using System;

namespace LightRail.Amqp
{
    /// <summary>
    /// Like List<T> but with an upper bound to the growth.
    ///
    /// NOT THREAD SAFE!!
    /// </summary>
    public class BoundedList<T>
    {
        public BoundedList(uint initialCapacity, uint maximumCapacity)
        {
            if (initialCapacity > maximumCapacity)
                throw new ArgumentOutOfRangeException(nameof(initialCapacity), "initialCapacity must be less than maximumCapacity");
            MaximumCapacity = maximumCapacity;
            items = new T[initialCapacity];
        }

        private T[] items;
        private static readonly T nullItem = default(T);

        /// <summary>
        /// Returns the current capacity of the list.
        /// </summary>
        public uint Capacity
        {
            get { return (uint)items.Length; }
            private set
            {
                if (value > MaximumCapacity)
                    throw new ArgumentOutOfRangeException(nameof(value), "Capacity must be less than MaximumCapacity");
                var newItems = new T[value];
                Array.Copy(items, 0, newItems, 0, items.Length);
                items = newItems;
            }
        }

        /// <summary>
        /// Returns the maximum capcity of the list.
        /// </summary>
        public uint MaximumCapacity { get; }

        /// <summary>
        /// Adds an item (growing the list if necessary) and returns the index at which it was added.
        ///
        /// Throws an exception if the list is full.
        /// </summary>
        public uint Add(T item)
        {
            var nextIndex = Length;
            EnsureCapacity(nextIndex + 1);
            items[nextIndex] = item;
            Length++;
            return nextIndex;
        }

        /// <summary>
        /// Gets or sets an item at the specific index.
        ///
        /// The index MAY be past the current Length. If so, the Length will be increased.
        ///
        /// Throws an exception if the list is full.
        /// </summary>
        public T this[uint index]
        {
            get
            {
                return items[index];
            }
            set
            {
                EnsureCapacity(index + 1);
                items[index] = value;
                // if adding to an index past the current length
                // set length to show the new length. Elements in between may be empty.
                if (index > (Length - 1) || Length == 0)
                {
                    Length = index + 1;
                }
            }
        }

        /// <summary>
        /// Removes all items (sets each index to default(T)) and sets Length to 0.
        /// </summary>
        public void Clear()
        {
            for (int i = 0; i < items.Length; i++)
            {
                items[i] = nullItem;
            }
            Length = 0;
        }

        /// <summary>
        /// Returns the current length of the list. That is, the last index in which a value as added.
        /// </summary>
        public uint Length { get; private set; }

        /// <summary>
        /// Returns true if the current list length is at or above the maximum capcity of the list. Adding any new
        /// item will result in an exception.
        /// </summary>
        public bool IsFull
        {
            get
            {
                return Length >= MaximumCapacity;
            }
        }

        private double _growthRate = 0.5;
        /// <summary>
        /// The rate at which the list will grow, as needed. As a percentage. Must be 0 < x &lte; 1.
        /// Default is 50%.
        /// </summary>
        public double GrowthRate
        {
            get { return _growthRate; }
            set
            {
                if (!(0 < value && value <= 1))
                    throw new ArgumentOutOfRangeException(nameof(value), "Value must be 0 < x <= 1");
                _growthRate = value;
            }
        }

        private void EnsureCapacity(uint requiredCapacity)
        {
            if (requiredCapacity > Capacity)
            {
                if (requiredCapacity > MaximumCapacity)
                {
                    throw new ArgumentOutOfRangeException(nameof(requiredCapacity), "Capacity of list must be less or equal to than MaximumCapacity");
                }
                // grow by the growth rate, up to the max capacity
                Capacity = Math.Min(requiredCapacity + (uint)Math.Ceiling(requiredCapacity * GrowthRate), MaximumCapacity);
            }
        }

        /// <summary>
        /// Returns in the index of the first null item in the list up to the Length.
        /// </summary>
        /// <returns></returns>
        public uint? IndexOfFirstNullItem()
        {
            for (uint i = 0; i < Length; i++)
            {
                if (Equals(items[i], nullItem))
                    return i;
            }
            return null;
        }

        /// <summary>
        /// Returns either the first index with a null item, or adds a new
        /// index, growing as necessary.
        /// </summary>
        public uint GetFirstNullIndexOrAdd()
        {
            for (uint i = 0; i < Length; i++)
            {
                if (Equals(items[i], nullItem))
                    return i;
            }
            return Add(nullItem);
        }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Lichenologist 32(4): 331 (2000)

#### Original name
Chroodiscus australis subsp. australis Kantvilas & Vezda

### Remarks
null


text:
package com.cobalt.bamboo.plugin.pipeline.domain.model;

import com.atlassian.bamboo.author.Author;
import com.atlassian.bamboo.commit.Commit;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class PerformanceSummaryAddAuthorsTest {
    private static final int COMMIT_LIST_SIZE = 10; // >= 3
    CompletionStats stat;
    ContributorBuilder cb;

	@Before
	public void setup() {

        cb = new ContributorBuilder(null);
        stat = new CompletionStats(1, new Date());
    }

	@Test
	public void testNoCommit() {
		List<Commit> commits = createCommitListWithoutAuthors(0);
        PerformanceSummaryCreator.addAllAuthorsInCommits(stat, commits, cb);
        assertEquals("0 commit should have 0 contributor", 0, stat.getContributors().size());
    }

	@Test
	public void testOneCommit() {
		List<Commit> commits = createCommitListWithoutAuthors(1);
		List<Author> authors = createAuthorListWithNames(1);
		for (int i = 0; i < 1; i++) {
	    	when(commits.get(i).getAuthor()).thenReturn(authors.get(i));
	    	when(commits.get(i).getComment()).thenReturn("comment");
		}
        PerformanceSummaryCreator.addAllAuthorsInCommits(stat, commits, cb);
        assertEquals("1 commit and 1 contributor", 1, stat.getContributors().size());
    }

	@Test
	public void testManyCommitsUniqueAuthors() {
		// create lists of commits and their corresponding authors
		List<Commit> commits = createCommitListWithoutAuthors(COMMIT_LIST_SIZE);
		List<Author> authors = createAuthorListWithNames(10);
		// assign unique authors to each commit
		for (int i = 0; i < COMMIT_LIST_SIZE; i++) {
	    	when(commits.get(i).getAuthor()).thenReturn(authors.get(i));
	    	when(commits.get(i).getComment()).thenReturn("comment");
		}

        PerformanceSummaryCreator.addAllAuthorsInCommits(stat, commits, cb);
        // check that all unique authors are counted
        assertEquals("10 commits, each w/ unique contributor", COMMIT_LIST_SIZE, stat.getContributors().size());
	}

	@Test
	public void testMultipleCommitsDuplicateAuthors() {
		List<Commit> commits = createCommitListWithoutAuthors(COMMIT_LIST_SIZE);
		List<Author> authors = createAuthorListWithNames(3);
		for (int i = 0; i < COMMIT_LIST_SIZE; i++) {
	    	when(commits.get(i).getAuthor()).thenReturn(authors.get(i % 3));
	    	when(commits.get(i).getDate()).thenReturn(new Date());
	    	when(commits.get(i).getComment()).thenReturn("comment");
		}

        PerformanceSummaryCreator.addAllAuthorsInCommits(stat, commits, cb);
        // check the duplicate authors are only counted once
        assertEquals("10 commits w/ duplicate contributors", 3, stat.getContributors().size());
	}

	// ========== Private Helper Methods ==========

	/*
	 * Create a list of commits w/o assigning them the authors
	 */
	private List<Commit> createCommitListWithoutAuthors(int numCommits) {
		List<Commit> commits = new ArrayList<Commit>();
		for (int i = 0; i < numCommits; i++) {
			commits.add(mock(Commit.class));
		}
		return commits;
	}

	/*
	 * Create a list of authors w/o assigning them the names
	 */
	private List<Author> createAuthorListWithNames(int numAuthors) {
		List<Author> authors = new ArrayList<Author>();
		for (int i = 0; i < numAuthors; i++) {
			authors.add(mock(Author.class));
		}
		for (int i = 0; i < numAuthors; i++) {
	    	when(authors.get(i).getLinkedUserName()).thenReturn("author" + i);
	    	when(authors.get(i).getName()).thenReturn("author" + i);
		}
		return authors;
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title>component vevent uri relative</title>
  <link rel="alternate" href="component-vevent-uri-relative.vcf" type="text/calendar" />

    Bad Movie Night - Gigli (blame mike spiegelman)

    Sun, Jan 15 : 8pm


text:
"""Extend pandas with custom array types"""
from typing import List, Optional, Tuple, Type

import numpy as np

from pandas.errors import AbstractMethodError

from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries

class ExtensionDtype:
    """
    A custom data type, to be paired with an ExtensionArray.

    .. versionadded:: 0.23.0

    See Also
    --------
    extensions.register_extension_dtype
    extensions.ExtensionArray

    Notes
    -----
    The interface includes the following abstract methods that must
    be implemented by subclasses:

    * type
    * name
    * construct_from_string

    The following attributes influence the behavior of the dtype in
    pandas operations

    * _is_numeric
    * _is_boolean

    Optionally one can override construct_array_type for construction
    with the name of this dtype via the Registry. See
    :meth:`extensions.register_extension_dtype`.

    * construct_array_type

    The `na_value` class attribute can be used to set the default NA value
    for this type. :attr:`numpy.nan` is used by default.

    ExtensionDtypes are required to be hashable. The base class provides
    a default implementation, which relies on the ``_metadata`` class
    attribute. ``_metadata`` should be a tuple containing the strings
    that define your data type. For example, with ``PeriodDtype`` that's
    the ``freq`` attribute.

    **If you have a parametrized dtype you should set the ``_metadata``
    class property**.

    Ideally, the attributes in ``_metadata`` will match the
    parameters to your ``ExtensionDtype.__init__`` (if any). If any of
    the attributes in ``_metadata`` don't implement the standard
    ``__eq__`` or ``__hash__``, the default implementations here will not
    work.

    .. versionchanged:: 0.24.0

       Added ``_metadata``, ``__hash__``, and changed the default definition
       of ``__eq__``.

    This class does not inherit from 'abc.ABCMeta' for performance reasons.
    Methods and properties required by the interface raise
    ``pandas.errors.AbstractMethodError`` and no ``register`` method is
    provided for registering virtual subclasses.
    """
    _metadata = ()  # type: Tuple[str, ...]

    def __str__(self):
        return self.name

    def __eq__(self, other):
        """Check whether 'other' is equal to self.

        By default, 'other' is considered equal if either

        * it's a string matching 'self.name'.
        * it's an instance of this type and all of the
          the attributes in ``self._metadata`` are equal between
          `self` and `other`.

        Parameters
        ----------
        other : Any

        Returns
        -------
        bool
        """
        if isinstance(other, str):
            try:
                other = self.construct_from_string(other)
            except TypeError:
                return False
        if isinstance(other, type(self)):
            return all(
                getattr(self, attr) == getattr(other, attr)
                for attr in self._metadata
            )
        return False

    def __hash__(self):
        return hash(tuple(getattr(self, attr) for attr in self._metadata))

    def __ne__(self, other):
        return not self.__eq__(other)

    @property
    def na_value(self):
        """
        Default NA value to use for this type.

        This is used in e.g. ExtensionArray.take. This should be the
        user-facing "boxed" version of the NA value, not the physical NA value
        for storage.  e.g. for JSONArray, this is an empty dictionary.
        """
        return np.nan

    @property
    def type(self) -> Type:
        """
        The scalar type for the array, e.g. ``int``

        It's expected ``ExtensionArray[item]`` returns an instance
        of ``ExtensionDtype.type`` for scalar ``item``, assuming
        that value is valid (not NA). NA values do not need to be
        instances of `type`.
        """
        raise AbstractMethodError(self)

    @property
    def kind(self) -> str:
        """
        A character code (one of 'biufcmMOSUV'), default 'O'

        This should match the NumPy dtype used when the array is
        converted to an ndarray, which is probably 'O' for object if
        the extension type cannot be represented as a built-in NumPy
        type.

        See Also
        --------
        numpy.dtype.kind
        """
        return 'O'

    @property
    def name(self) -> str:
        """
        A string identifying the data type.

        Will be used for display in, e.g. ``Series.dtype``
        """
        raise AbstractMethodError(self)

    @property
    def names(self) -> Optional[List[str]]:
        """Ordered list of field names, or None if there are no fields.

        This is for compatibility with NumPy arrays, and may be removed in the
        future.
        """
        return None

    @classmethod
    def construct_array_type(cls):
        """
        Return the array type associated with this dtype

        Returns
        -------
        type
        """
        raise NotImplementedError

    @classmethod
    def construct_from_string(cls, string: str):
        r"""
        Construct this type from a string.

        This is useful mainly for data types that accept parameters.
        For example, a period dtype accepts a frequency parameter that
        can be set as ``period[H]`` (where H means hourly frequency).

        By default, in the abstract class, just the name of the type is
        expected. But subclasses can overwrite this method to accept
        parameters.

        Parameters
        ----------
        string : str
            The name of the type, for example ``category``.

        Returns
        -------
        ExtensionDtype
            Instance of the dtype.

        Raises
        ------
        TypeError
            If a class cannot be constructed from this 'string'.

        Examples
        --------
        For extension dtypes with arguments the following may be an
        adequate implementation.

        >>> @classmethod
        ... def construct_from_string(cls, string):
        ...     pattern = re.compile(r"^my_type\[(?P<arg_name>.+)\]$")
        ...     match = pattern.match(string)
        ...     if match:
        ...         return cls(**match.groupdict())
        ...     else:
        ...         raise TypeError("Cannot construct a '{}' from "
        ...                         "'{}'".format(cls.__name__, string))
        """
        if not isinstance(string, str):
            raise TypeError("Expects a string, got {}".format(type(string)))
        if string != cls.name:
            raise TypeError("Cannot construct a '{}' from '{}'".format(
                cls.__name__, string))
        return cls()

    @classmethod
    def is_dtype(cls, dtype) -> bool:
        """Check if we match 'dtype'.

        Parameters
        ----------
        dtype : object
            The object to check.

        Returns
        -------
        is_dtype : bool

        Notes
        -----
        The default implementation is True if

        1. ``cls.construct_from_string(dtype)`` is an instance
           of ``cls``.
        2. ``dtype`` is an object and is an instance of ``cls``
        3. ``dtype`` has a ``dtype`` attribute, and any of the above
           conditions is true for ``dtype.dtype``.
        """
        dtype = getattr(dtype, 'dtype', dtype)

        if isinstance(dtype, (ABCSeries, ABCIndexClass,
                              ABCDataFrame, np.dtype)):
            # https://github.com/pandas-dev/pandas/issues/22960
            # avoid passing data to `construct_from_string`. This could
            # cause a FutureWarning from numpy about failing elementwise
            # comparison from, e.g., comparing DataFrame == 'category'.
            return False
        elif dtype is None:
            return False
        elif isinstance(dtype, cls):
            return True
        try:
            return cls.construct_from_string(dtype) is not None
        except TypeError:
            return False

    @property
    def _is_numeric(self) -> bool:
        """
        Whether columns with this dtype should be considered numeric.

        By default ExtensionDtypes are assumed to be non-numeric.
        They'll be excluded from operations that exclude non-numeric
        columns, like (groupby) reductions, plotting, etc.
        """
        return False

    @property
    def _is_boolean(self) -> bool:
        """
        Whether this dtype should be considered boolean.

        By default, ExtensionDtypes are assumed to be non-numeric.
        Setting this to True will affect the behavior of several places,
        e.g.

        * is_bool
        * boolean indexing

        Returns
        -------
        bool
        """
        return False


text:
import request from 'request-promise'
import cheerio from 'cheerio'
import _ from 'lodash'
import Promise from 'bluebird'
import path from 'path'
import URL from 'url'
import moment from 'moment'

const knowledge = {
	mobile: {
		indexUrl: "http://hkm.appledaily.com/"
	},
	// TODO Desktop not supported yet
	// desktop: {
	// 	indexUrl: "http://hk.apple.nextmedia.com/",
	// }
}

export default class AppleDaily{

	constructor(params){
		this.config = knowledge[params.site];
	}

	sections(){
		let $this = this;
		let url = this.config.indexUrl;

		return request(url)
		.then(function(content){
			var $ = cheerio.load(content);
			var urlParts = URL.parse(url);

			var menuTags = $("ul.menu li:not([class])");
			var menu = _.map(menuTags, function(item){
				var label = $("a", item).text();
				var link = $("a", item).attr("href");
				var fullUrl = urlParts.protocol + "//" + urlParts.hostname + "/" +link;

				return {
					label: label,
					url: fullUrl,
					articles: $this.articles.bind($this, fullUrl)
				}
			});

			return Promise.resolve(menu);

		});
	}

	articles(url){
		let $this = this;

		return request(url)
		.then(function(content){
			var $ = cheerio.load(content);
			var urlParts = URL.parse(url);

			var articlesTags = $(".content-list ul.list li:not([style])");
			var articles = _.map(articlesTags, function(item){

				var title = $("a > p", item).text().trim();
				var link = $("a", item).attr("href");
				var fullUrl = urlParts.protocol + "//" + urlParts.hostname + "/" +link;
				var image = $("img", item).attr("src");
				var relativeTime = $("label", item).text();//only present if in instant news

				return {
					title: title,
					url: fullUrl,
					image: image,
					relativeTime: relativeTime,
					getArticle: $this.getArticle.bind($this, fullUrl)
				}
			});

			return Promise.resolve(articles);

		});
	}

	getArticle(url){
		var urlParts = URL.parse(url);
		if(urlParts.hostname.startsWith('hkm')){
			return _parseMobileVersion(url);
		}else{
			return _parseDesktopVersion(url);
		}
	}

	getArticlePermalink(url){
		return _getArticlePermalink(url);
	}

}

function _parseDesktopVersion(url){
	return request(url)
	.then(function(content){
		var $ = cheerio.load(content);

		var title = $("meta[property=\"og:title\"]").attr("content");

		var realTitle = $(".LinkTable h1").text().trim();

		var imagesTags = $("meta[property=\"og:image\"]");
		var images = _.map(imagesTags, function(item){
			return $(item).attr("content");
		});

		var paragraphs =  _.map($("div.ArticleContent_Outer"), function(item){
			return $("p", item).text().trim();
		});

		var views = $(".view").text().trim();

		var article = {
			id: getArticleId(url),
			date: getArticleDate(url),
			views: views,
			title: title,
			realTitle: realTitle,
			images: images,
			content: paragraphs.join(''),
			permalink: _getArticlePermalink(url)
		};
		// console.log(article);
		return Promise.resolve(article);

	});
}

function _parseMobileVersion(url){
	return request(url)
	.then(function(content){
		var $ = cheerio.load(content);

		var title = $("meta[property=\"og:title\"]").attr("content");
		var realTitle = $(".content-article h1").text().trim();

		var imagesTags = $("meta[property=\"og:image\"]");
		var images = _.map(imagesTags, function(item){
			return $(item).attr("content");
		});

		var paragraphs =  _.map($(".content-article p:not([class='next'])"), function(item){
			return $(item).text().trim();
		});

		// var views = $(".view").text().trim();
		var lastUpdate = $(".lastupdate").text().trim();
		if(lastUpdate){
			lastUpdate = moment(lastUpdate).toDate();
		}

		var article = {
			id: getArticleId(url),
			date: getArticleDate(url),
			lastUpdate: lastUpdate,
			// views: views,
			title: title,
			realTitle: realTitle,
			images: images,
			content: paragraphs.join(''),
			permalink: _getArticlePermalink(url)
		};
		// console.log(article);
		return Promise.resolve(article);

	});
}

/*
	Utility methods
 */

function getArticleId(url){
	var urlParts = URL.parse(url);
	var pathParts = path.parse(urlParts.pathname);
	return pathParts.name;
}

function getArticleDate(url){
	var urlParts = URL.parse(url, true);
	if(urlParts.hostname.startsWith('hkm')){
		return moment(urlParts.query.issue, "YYYYMMDD").toDate();
	}else{
		var pathParts = path.parse(urlParts.pathname);
		var dirParts = path.parse(pathParts.dir);
		return moment(dirParts.name, "YYYYMMDD").toDate();
	}
}

function getArticleLastUpdateTime(url, $){
	var urlParts = URL.parse(url, true);
	if(urlParts.hostname.startsWith('hkm')){
		return $("text lastupdate").text().trim();
	}else{

	}

}

function _getArticlePermalink(url){
	var permalink;

	var urlParts = URL.parse(url);
	if(urlParts.hostname.startsWith('hkm')){
		permalink = url;
	}else{
		permalink = urlParts.protocol + '//' + urlParts.hostname + urlParts.pathname;
	}
	return permalink;
}


text:
$(document).ready( function() {
    $("#files .file .data pre, #files .file .line-data, #files .file .line-number").css("font-size", "113%");
});


text:
module FakeCargo
  class Fetch
    class Git
      def initialize(git_dir)
        @git_dir = git_dir
      end
      class Inst
        def initialize(git_dir, env, crate, dep)
          @env = env.new_child(
            dep.name, git_dir + '/' + File.basename(dep.description['git'])
          )
          if ! File::directory?(@env.path)
            system("cd #{git_dir} && git clone #{dep.description['git']}")
          end
        end
        attr_reader :env
      end
      def fetch(env, crate, dependency)
        Inst.new(@git_dir, env, crate, dependency)
      end
    end
  end
end


text:
<?php

namespace Brainrepo\SpotifyjukeboxBundle\Document;

use Brainrepo\SpotifyjukeboxBundle\Document\JukeboxInterface;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @MongoDB\Document
 */
class Jukebox implements JukeboxInterface
{
	/**
     * @MongoDB\Id(strategy="auto")
     */
    private $id;
    /**
     * @MongoDB\String
     */
    private $name;
    /**
     * @MongoDB\Boolean
     */
    private $status = FALSE;

    /**
     * @Gedmo\Slug(fields={"name"})
     * @MongoDB\String
     * @MongoDB\UniqueIndex
     */
    private $slug;

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    public function getStatus()
    {
        return $this->status;
    }

    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    public function getSlug()
    {
        return $this->slug;
    }
}