text:
// Copyright 2021-2022, University of Colorado Boulder

/**
 * A listener that manages the visibility of different highlights when switching between mouse/touch and alternative
 * input for a Display.
 *
 * @author Jesse Greenberg (PhET Interactive Simulations)
 */

import Multilink from '../../axon/js/Multilink.js';
import Vector2 from '../../dot/js/Vector2.js';
import { Display, FocusManager, globalKeyStateTracker, TInputListener, KeyboardUtils, SceneryEvent } from '../../scenery/js/imports.js';
import joist from './joist.js';
import PreferencesModel from './preferences/PreferencesModel.js';

// constants
// The amount of Pointer movement required to switch from showing focus highlights to Interactive Highlights if both
// are enabled, in the global coordinate frame.
const HIDE_FOCUS_HIGHLIGHTS_MOVEMENT_THRESHOLD = 100;

class HighlightVisibilityController {
  private readonly display: Display;

  // {null|Vector2} - The initial point of the Pointer when focus highlights are made visible and Interactive
  // highlights are enabled. Pointer movement to determine whether to switch to showing Interactive Highlights
  // instead of focus highlights will be relative to this point. A value of null means we haven't saved a point
  // yet and we need to on the next move event.
  private initialPointerPoint: Vector2 | null = null;

  // {number} - The amount of distance that the Pointer has moved relative to initialPointerPoint, in the global
  // coordinate frame.
  private relativePointerDistance = 0;

  public constructor( display: Display, preferencesModel: PreferencesModel ) {

    // A reference to the Display whose FocusManager we will operate on to control the visibility of various kinds of highlights
    this.display = display;

    // A listener that is added/removed from the display to manage visibility of highlights on move events. We
    // usually don't need this listener so it is only added when we need to listen for move events.
    const moveListener = {
      move: this.handleMove.bind( this )
    };

    const setHighlightsVisible = () => { this.display.focusManager.pdomFocusHighlightsVisibleProperty.value = true; };
    const focusHighlightVisibleListener: TInputListener = {};

    // Restore display of focus highlights if we receive PDOM events. Exclude focus-related events here
    // so that we can support some iOS cases where we want PDOM behavior even though iOS + VO only provided pointer
    // events. See https://github.com/phetsims/scenery/issues/1137 for details.
    ( [ 'click', 'input', 'change', 'keydown', 'keyup' ] as const ).forEach( eventType => {
      focusHighlightVisibleListener[ eventType ] = setHighlightsVisible;
    } );
    this.display.addInputListener( focusHighlightVisibleListener );

    // When tabbing into the sim, make focus highlights visible - on keyup because the keydown is likely to have
    // occurred on an element outside of the DOM scope.
    globalKeyStateTracker.keyupEmitter.addListener( event => {
      if ( KeyboardUtils.isKeyEvent( event, KeyboardUtils.KEY_TAB ) ) {
        setHighlightsVisible();
      }
    } );

    if ( preferencesModel.visualModel.supportsInteractiveHighlights ) {

      preferencesModel.visualModel.interactiveHighlightsEnabledProperty.link( visible => {
        this.display.focusManager.interactiveHighlightsVisibleProperty.value = visible;
      } );

      // When both Interactive Highlights are enabled and the PDOM focus highlights are visible, add a listener that
      // will make focus highlights invisible and interactive highlights visible if we receive a certain amount of
      // mouse movement. The listener is removed as soon as PDOM focus highlights are made invisible or Interactive
      // Highlights are disabled.
      const interactiveHighlightsEnabledProperty = preferencesModel.visualModel.interactiveHighlightsEnabledProperty;
      const pdomFocusHighlightsVisibleProperty = this.display.focusManager.pdomFocusHighlightsVisibleProperty;
      Multilink.multilink(
        [ interactiveHighlightsEnabledProperty, pdomFocusHighlightsVisibleProperty ],
        ( interactiveHighlightsEnabled, pdomHighlightsVisible ) => {
          if ( interactiveHighlightsEnabled && pdomHighlightsVisible ) {
            this.display.addInputListener( moveListener );

            // Setting to null indicates that we should store the Pointer.point as the initialPointerPoint on next move.
            this.initialPointerPoint = null;

            // Reset distance of movement for the mouse pointer since we are looking for changes again.
            this.relativePointerDistance = 0;
          }
          else {
            this.display.hasInputListener( moveListener ) && this.display.removeInputListener( moveListener );
          }
        }
      );
    }

    this.display.addInputListener( {

      // Whenever we receive a down event focus highlights are made invisible. We may also blur the active element in
      // some cases, but not always as is necessary for iOS VoiceOver. See documentation details in the function.
      down: event => {

        // An AT might have sent a down event outside of the display, if this happened we will not do anything
        // to change focus
        if ( this.display.bounds.containsPoint( event.pointer.point ) ) {

          // in response to pointer events, always hide the focus highlight so it isn't distracting
          this.display.focusManager.pdomFocusHighlightsVisibleProperty.value = false;

          // no need to do this work unless some element in the simulation has focus
          if ( FocusManager.pdomFocusedNode ) {

            // if the event trail doesn't include the focusedNode, clear it - otherwise DOM focus is kept on the
            // active element so that it can remain the target for assistive devices using pointer events
            // on behalf of the user, see https://github.com/phetsims/scenery/issues/1137
            if ( !event.trail.nodes.includes( FocusManager.pdomFocusedNode ) ) {
              FocusManager.pdomFocus = null;
            }
          }
        }
      }
    } );
  }

  /**
   * Switches between focus highlights and Interactive Highlights if there is enough mouse movement.
   */
  private handleMove( event: SceneryEvent ): void {

    // A null initialPointerPoint means that we have not set the point yet since we started listening for mouse
    // movements - set it now so that distance of mose movement will be relative to this initial point.
    if ( this.initialPointerPoint === null ) {
      this.initialPointerPoint = event.pointer.point;
    }
    else {
      this.relativePointerDistance = event.pointer.point.distance( this.initialPointerPoint );

      // we have moved enough to switch from focus highlights to Interactive Highlights. Setting the
      // pdomFocusHighlightsVisibleProperty to false will remove this listener for us.
      if ( this.relativePointerDistance > HIDE_FOCUS_HIGHLIGHTS_MOVEMENT_THRESHOLD ) {
        this.display.focusManager.pdomFocusHighlightsVisibleProperty.value = false;
        this.display.focusManager.interactiveHighlightsVisibleProperty.value = true;
      }
    }
  }
}

joist.register( 'HighlightVisibilityController', HighlightVisibilityController );
export default HighlightVisibilityController;


text:
<?xml version="1.0"?>
<REUTERS TOPICS="YES" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET" OLDID="12681" NEWID="498">
 <DATE>2-MAR-1987 11:24:06.09</DATE>
 <TOPICS>
  <D>acq</D>
 </TOPICS>
 <PLACES>
  <D>usa</D>
 </PLACES>
 <PEOPLE/>
 <ORGS/>
 <EXCHANGES/>
 <COMPANIES/>
 <UNKNOWN>F
   f0958 reute
r f BC-UTILICORP-<UCU>-COMPL   03-02 0066</UNKNOWN>
 <TEXT>
  <TITLE>UTILICORP <UCU> COMPLETES ACQUISITION</TITLE>
  <DATELINE>KANSAS CITY, March 2 -</DATELINE>
  <BODY>UtiliCorp United Inc said it
completed the acquisition of West Virginia Power from Dominion
Resources for about 21 mln dlrs.
    The sale was approved by the West Virginia Public Service
Commission in January and became effective March one. West
Virginia's management will continue to be responsible for
operating the utility, it said.
 Reuter</BODY>
 </TEXT>
</REUTERS>

redpajama_set_name: RedPajamaGithub


text:
#include "postgres.h"

#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/tableam.h"
#include "catalog/indexing.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_db_role_setting.h"
#include "utils/fmgroids.h"
#include "utils/rel.h"

#include "catalog/heap.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_database.h"
#include "cdb/cdbdisp_query.h"
#include "cdb/cdbvars.h"
#include "utils/builtins.h"
#include "utils/syscache.h"

void
AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
{
	char	   *valuestr;
	HeapTuple	tuple;
	Relation	rel;
	ScanKeyData scankey[2];
	SysScanDesc scan;

	valuestr = ExtractSetVariableArgs(setstmt);

	/* Get the old tuple, if any. */

	rel = table_open(DbRoleSettingRelationId, RowExclusiveLock);
	ScanKeyInit(&scankey[0],
				Anum_pg_db_role_setting_setdatabase,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(databaseid));
	ScanKeyInit(&scankey[1],
				Anum_pg_db_role_setting_setrole,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(roleid));
	scan = systable_beginscan(rel, DbRoleSettingDatidRolidIndexId, true,
							  NULL, 2, scankey);
	tuple = systable_getnext(scan);

	/*
	 * There are three cases:
	 *
	 * - in RESET ALL, request GUC to reset the settings array and update the
	 * catalog if there's anything left, delete it otherwise
	 *
	 * - in other commands, if there's a tuple in pg_db_role_setting, update
	 * it; if it ends up empty, delete it
	 *
	 * - otherwise, insert a new pg_db_role_setting tuple, but only if the
	 * command is not RESET
	 */
	if (setstmt->kind == VAR_RESET_ALL)
	{
		if (HeapTupleIsValid(tuple))
		{
			ArrayType  *new = NULL;
			Datum		datum;
			bool		isnull;

			datum = heap_getattr(tuple, Anum_pg_db_role_setting_setconfig,
								 RelationGetDescr(rel), &isnull);

			if (!isnull)
				new = GUCArrayReset(DatumGetArrayTypeP(datum));

			if (new)
			{
				Datum		repl_val[Natts_pg_db_role_setting];
				bool		repl_null[Natts_pg_db_role_setting];
				bool		repl_repl[Natts_pg_db_role_setting];
				HeapTuple	newtuple;

				memset(repl_repl, false, sizeof(repl_repl));

				repl_val[Anum_pg_db_role_setting_setconfig - 1] =
					PointerGetDatum(new);
				repl_repl[Anum_pg_db_role_setting_setconfig - 1] = true;
				repl_null[Anum_pg_db_role_setting_setconfig - 1] = false;

				newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
											 repl_val, repl_null, repl_repl);
				CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
			}
			else
				CatalogTupleDelete(rel, &tuple->t_self);
		}
	}
	else if (HeapTupleIsValid(tuple))
	{
		Datum		repl_val[Natts_pg_db_role_setting];
		bool		repl_null[Natts_pg_db_role_setting];
		bool		repl_repl[Natts_pg_db_role_setting];
		HeapTuple	newtuple;
		Datum		datum;
		bool		isnull;
		ArrayType  *a;

		memset(repl_repl, false, sizeof(repl_repl));
		repl_repl[Anum_pg_db_role_setting_setconfig - 1] = true;
		repl_null[Anum_pg_db_role_setting_setconfig - 1] = false;

		/* Extract old value of setconfig */
		datum = heap_getattr(tuple, Anum_pg_db_role_setting_setconfig,
							 RelationGetDescr(rel), &isnull);
		a = isnull ? NULL : DatumGetArrayTypeP(datum);

		/* Update (valuestr is NULL in RESET cases) */
		if (valuestr)
			a = GUCArrayAdd(a, setstmt->name, valuestr);
		else
			a = GUCArrayDelete(a, setstmt->name);

		if (a)
		{
			repl_val[Anum_pg_db_role_setting_setconfig - 1] =
				PointerGetDatum(a);

			newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
										 repl_val, repl_null, repl_repl);
			CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
		}
		else
			CatalogTupleDelete(rel, &tuple->t_self);
	}
	else if (valuestr)
	{
		/* non-null valuestr means it's not RESET, so insert a new tuple */
		HeapTuple	newtuple;
		Datum		values[Natts_pg_db_role_setting];
		bool		nulls[Natts_pg_db_role_setting];
		ArrayType  *a;

		memset(nulls, false, sizeof(nulls));

		a = GUCArrayAdd(NULL, setstmt->name, valuestr);

		values[Anum_pg_db_role_setting_setdatabase - 1] =
			ObjectIdGetDatum(databaseid);
		values[Anum_pg_db_role_setting_setrole - 1] = ObjectIdGetDatum(roleid);
		values[Anum_pg_db_role_setting_setconfig - 1] = PointerGetDatum(a);
		newtuple = heap_form_tuple(RelationGetDescr(rel), values, nulls);

		CatalogTupleInsert(rel, newtuple);
	}

	InvokeObjectPostAlterHookArg(DbRoleSettingRelationId,
								 databaseid, 0, roleid, false);

	systable_endscan(scan);

	/* update pg_stat_last_shoperation for metadata tracking */
	if (Gp_role == GP_ROLE_DISPATCH)
	{
		char	   *alter_subtype;

		if (setstmt->kind == VAR_RESET_ALL)
			alter_subtype = "RESET ALL";
		else if (setstmt->kind == VAR_RESET)
			alter_subtype = "RESET";
		else
			alter_subtype = "SET";

		/* roleoid is only valid for ALTER ROLE */
		MetaTrackUpdObject(DatabaseRelationId,
						   OidIsValid(roleid) ? roleid : databaseid,
						   GetUserId(),
						   "ALTER", alter_subtype);
	}

	if (Gp_role == GP_ROLE_DISPATCH)
	{
		StringInfoData buffer;
		char	   *rolename;
		char	   *dbname;
		HeapTuple	htup;

		if (roleid)
		{
			htup = SearchSysCache1(AUTHOID, roleid);
			if (!HeapTupleIsValid(htup))
				elog(ERROR, "cache lookup failed for role %u", roleid);
			rolename = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(htup))->rolname));
			ReleaseSysCache(htup);
		}
		else
			rolename = NULL;

		if (databaseid)
		{
			htup = SearchSysCache1(DATABASEOID, databaseid);
			if (!htup)
				elog(ERROR, "cache lookup failed for database %u", databaseid);
			dbname = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(htup))->datname));
			ReleaseSysCache(htup);
		}
		else
			dbname = NULL;

		initStringInfo(&buffer);

		if (databaseid && roleid)
			appendStringInfo(&buffer, "ALTER ROLE %s IN DATABASE %s ",
							 quote_identifier(rolename), quote_identifier(dbname));
		else if (roleid)
			appendStringInfo(&buffer, "ALTER ROLE %s ",
							 quote_identifier(rolename));
		else if (databaseid)
			appendStringInfo(&buffer, "ALTER DATABASE %s ",
							 quote_identifier(dbname));
		else
			appendStringInfo(&buffer, "ALTER ROLE ALL ");

		if (setstmt->kind ==  VAR_RESET_ALL)
			appendStringInfo(&buffer, "RESET ALL");
		else if (valuestr == NULL)
			appendStringInfo(&buffer, "RESET %s", quote_identifier(setstmt->name));
		else if (setstmt->kind ==  VAR_SET_CURRENT)
			appendStringInfo(&buffer, "SET %s TO %s", quote_identifier(setstmt->name), quote_literal_cstr(valuestr));
		else
		{
			ListCell   *l;
			bool		first;

			appendStringInfo(&buffer, "SET %s TO ", quote_identifier(setstmt->name));

			/* Parse string into list of identifiers */
			first = true;
			foreach(l, setstmt->args)
			{
				A_Const	   *arg = (A_Const *) lfirst(l);

				if (!first)
					appendStringInfo(&buffer, ",");
				first = false;

				switch (nodeTag(&arg->val))
				{
					case T_Integer:
						appendStringInfo(&buffer, "%d", intVal(&arg->val));
						break;
					case T_Float:
						/* represented as a string, so just copy it */
						appendStringInfoString(&buffer, strVal(&arg->val));
						break;
					case T_String:
						appendStringInfoString(&buffer, quote_literal_cstr(strVal(&arg->val)));
						break;
					default:
						elog(ERROR, "unexpected constant type: %d", nodeTag(&arg->val));
				}
			}
		}

		CdbDispatchCommand(buffer.data,
						   DF_CANCEL_ON_ERROR|
						   DF_NEED_TWO_PHASE|
						   DF_WITH_SNAPSHOT,
						   NULL);

		pfree(buffer.data);
	}

	/* Close pg_db_role_setting, but keep lock till commit */
	table_close(rel, NoLock);
}

/*
 * Drop some settings from the catalog.  These can be for a particular
 * database, or for a particular role.  (It is of course possible to do both
 * too, but it doesn't make sense for current uses.)
 */
void
DropSetting(Oid databaseid, Oid roleid)
{
	Relation	relsetting;
	TableScanDesc scan;
	ScanKeyData keys[2];
	HeapTuple	tup;
	int			numkeys = 0;

	relsetting = table_open(DbRoleSettingRelationId, RowExclusiveLock);

	if (OidIsValid(databaseid))
	{
		ScanKeyInit(&keys[numkeys],
					Anum_pg_db_role_setting_setdatabase,
					BTEqualStrategyNumber,
					F_OIDEQ,
					ObjectIdGetDatum(databaseid));
		numkeys++;
	}
	if (OidIsValid(roleid))
	{
		ScanKeyInit(&keys[numkeys],
					Anum_pg_db_role_setting_setrole,
					BTEqualStrategyNumber,
					F_OIDEQ,
					ObjectIdGetDatum(roleid));
		numkeys++;
	}

	scan = table_beginscan_catalog(relsetting, numkeys, keys);
	while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
	{
		CatalogTupleDelete(relsetting, &tup->t_self);
	}
	table_endscan(scan);

	table_close(relsetting, RowExclusiveLock);
}

/*
 * Scan pg_db_role_setting looking for applicable settings, and load them on
 * the current process.
 *
 * relsetting is pg_db_role_setting, already opened and locked.
 *
 * Note: we only consider setting for the exact databaseid/roleid combination.
 * This probably needs to be called more than once, with InvalidOid passed as
 * databaseid/roleid.
 */
void
ApplySetting(Snapshot snapshot, Oid databaseid, Oid roleid,
			 Relation relsetting, GucSource source)
{
	SysScanDesc scan;
	ScanKeyData keys[2];
	HeapTuple	tup;

	ScanKeyInit(&keys[0],
				Anum_pg_db_role_setting_setdatabase,
				BTEqualStrategyNumber,
				F_OIDEQ,
				ObjectIdGetDatum(databaseid));
	ScanKeyInit(&keys[1],
				Anum_pg_db_role_setting_setrole,
				BTEqualStrategyNumber,
				F_OIDEQ,
				ObjectIdGetDatum(roleid));

	scan = systable_beginscan(relsetting, DbRoleSettingDatidRolidIndexId, true,
							  snapshot, 2, keys);
	while (HeapTupleIsValid(tup = systable_getnext(scan)))
	{
		bool		isnull;
		Datum		datum;

		datum = heap_getattr(tup, Anum_pg_db_role_setting_setconfig,
							 RelationGetDescr(relsetting), &isnull);
		if (!isnull)
		{
			ArrayType  *a = DatumGetArrayTypeP(datum);

			/*
			 * We process all the options at SUSET level.  We assume that the
			 * right to insert an option into pg_db_role_setting was checked
			 * when it was inserted.
			 */
			ProcessGUCArray(a, PGC_SUSET, source, GUC_ACTION_SET);
		}
	}

	systable_endscan(scan);
}


text:
   #include "Flexmotn.h"
#endif

#ifdef __cplusplus
	extern "C"{
#endif

//Configure Inhibit Outputs
FLEXFUNC flex_configure_inhibit_output(BOARD, u16 axisMap, u16 polarityMap);

//Configure Step Mode & Polarity
FLEXFUNC flex_config_step_mode_pol(BOARD, u8 axisOrStepperOutput, u16 modeAndPolarityMap);

// Retired due to 8 axis support.
// Enable axes
FLEXFUNC flex_enable_axes(BOARD, u8 reserved, u8 PIDRate, u8 axisMap);

// Configure inhibit output
FLEXFUNC flex_configure_inhibits(BOARD, u8 axisMap, u8 polarityMap);

// Enable limit
FLEXFUNC flex_enable_limits(BOARD, u16 limitType, u8 forwardLimitMap, u8 reverseLimitMap);

// Read limit status
FLEXFUNC flex_read_limit_status(BOARD, u16 limitType, u8 returnVector);
FLEXFUNC flex_read_limit_status_rtn(BOARD, u16 limitType, u8 *forwardLimitStatus, u8 *reverseLimitStatus);

// Set limit input polarity
FLEXFUNC flex_set_limit_polarity(BOARD, u8 forwardPolarityMap, u8 reversePolarityMap);

// Read DAC limit status
FLEXFUNC flex_read_dac_limit_status(BOARD, u8 returnVector);
FLEXFUNC flex_read_dac_limit_status_rtn(BOARD, u8 *positiveStatus, u8 *negativeStatus);

// Set breakpoint momo
FLEXFUNC flex_set_breakpoint_momo(BOARD, u8 axisOrEncoder, u8 mustOn, u8 mustOff, u8 inputVector);

// Set inhibit output momo
FLEXFUNC flex_set_inhibit_momo(BOARD, u8 mustOn, u8 mustOff);

// Wait on condition (On Brd program)
FLEXFUNC flex_wait_on_condition(BOARD, u8 resource, u16 waitType, u16 condition, u8 mustOn,
										  u8 mustOff, u16 matchType, u16 timeOut, u8 returnVector);

//Jump to Label on Condition
FLEXFUNC flex_jump_label_on_condition (BOARD, u8 resource, u16 condition, u8 mustOn,
                                       u8 mustOff, u16 matchType, u16 labelNumber);

// Read ADC
FLEXFUNC flex_read_adc (BOARD, u8 ADC, u8 returnVector);
FLEXFUNC flex_read_adc_rtn (BOARD, u8 ADC, i16 *ADCValue);

//ENB_ENC_CMD, Enable the encoders
FLEXFUNC flex_enable_encs(BOARD, u8 device, u16 encmap);

//Load Circular Arc
FLEXFUNC flex_load_2d_arc(BOARD, u8 device, u32 radius, i32 startangle,
							i32 travelangle, u8 inpvect);

//Load Spherical Arc
FLEXFUNC flex_load_3d_arc(BOARD, u8 device, u32 radius, u32 planepitch,
				i32 planeyaw, i32 startangle, i32 travelangle, u8 inpvect);

//Load Helical Arc
FLEXFUNC flex_load_helix(BOARD, u8 device, u32 radius, i32 startangle,
					i32 travelangle, i32 lineartravel, u8 inpvect);

//ENB_GEAR_CMD, Enable Gearing
FLEXFUNC flex_enable_gear(BOARD, u8 device, u16 axismap);

//ACQ_SAMPLES_CMD, Acquire Samples Command
FLEXFUNC flex_acq_traj_data(BOARD, u8 device, u16 axismap, u16 numsamps, u16 timeperiod);

//READ_SAMPLE_CMD, Read Sample From Acquire Samples to RDB
FLEXFUNC flex_read_traj_data(BOARD, u8 device, u8 retvect);

//READ_SAMPLE_CMD, Read Sample From Acquire Samples
FLEXFUNC flex_read_traj_data_rtn(BOARD, u8 device, long *retdata);

//OBSOLETE
//READ_RUNST_CMD, Read Run/Stop Status
FLEXFUNC flex_read_rs_status(BOARD, u8 device, u8 retvect);

//OBSOLETE
//READ_RUNST_CMD, Read Run/Stop Status
FLEXFUNC flex_read_rs_status_rtn(BOARD, u8 device, u16 *status);

//READ_MOFF_CMD, Read Motor Off Status
FLEXFUNC flex_read_motoff_status(BOARD, u8 device, u8 retvect);

//READ_MOFF_CMD, Read Motor Off Status
FLEXFUNC flex_read_motoff_status_rtn(BOARD, u8 device, u16 *status);

//OBSOLETE
//READ_DACLIM_CMD, Read DAC Limit Status
FLEXFUNC flex_read_dac_status(BOARD, u8 device, u8 retvect);

//OBSOLETE
//READ_DACLIM_CMD, Read DAC Limit Status
FLEXFUNC flex_read_dac_status_rtn(BOARD, u8 device, u16 *status);

//Load all Control Loop Parameters
FLEXFUNC flex_load_loop_params(BOARD, u8 axis, PID *PIDValues, u8 inputVector);

//Load Proportional Gain
FLEXFUNC flex_load_kp(BOARD, u8 axis, u16 kp, u8 inpvect);

//Load Integral Gain
FLEXFUNC flex_load_ki(BOARD, u8 axis, u16 ki, u8 inpvect);

//Load Integration Limit
FLEXFUNC flex_load_ilim(BOARD, u8 axis, u16 ilim, u8 inpvect);

//Load Derivative Gain
FLEXFUNC flex_load_kd(BOARD, u8 axis, u16 kd, u8 inpvect);

//Load Derivative Sample Period Multiplier
FLEXFUNC flex_load_td(BOARD, u8 axis, u16 td, u8 inpvect);

//Load Velocity Feedback Gain
FLEXFUNC flex_load_kv(BOARD, u8 axis, u16 kv, u8 inpvect);

//Load Acceleration Feedforward Gain
FLEXFUNC flex_load_aff(BOARD, u8 axis, u16 aff, u8 inpvect);

//Load Velocity Feedforward Gain
FLEXFUNC flex_load_vff(BOARD, u8 axis, u16 vff, u8 inpvect);

//Load Acceleration
FLEXFUNC flex_load_accel(BOARD, u8 axisorvectorspace, u32 accel, u8 inpvect);

//Load Deceleration
FLEXFUNC flex_load_decel(BOARD, u8 axisorvectorspace, u32 decel, u8 inpvect);

//Load Acceleration in RPS/sec
FLEXFUNC flex_load_accel_rpsps(BOARD, u8 axisorvectorspace, f64 rpsps, u8 inpvect);

//Load Deceleration in RPS/sec
FLEXFUNC flex_load_decel_rpsps(BOARD, u8 axisorvectorspace, f64 rpsps, u8 inpvect);

//Load Velocity Override
FLEXFUNC flex_load_vel_override(BOARD, u8 axisorvectorspace, u16 overridescale, u8 inpvect);

//Stop Motion
FLEXFUNC flex_stop(BOARD, u8 axisorvectorspace, u16 axismap);

//Halt Motion
FLEXFUNC flex_halt(BOARD, u8 axisorvectorspace, u16 axismap);

//Kill Motion
FLEXFUNC flex_kill(BOARD, u8 axisorvectorspace, u16 axismap);

//Enable Limit Inputs
FLEXFUNC flex_enable_lims(BOARD, u8 device, u16 limmap);

//Enable Software Limits
FLEXFUNC flex_enable_sw_lims(BOARD, u8 device, u16 swlimmap);

//Read Limit Input Status
FLEXFUNC flex_read_lim_status(BOARD, u8 device, u8 retvect);
//Read Limit Input Status
FLEXFUNC flex_read_lim_status_rtn(BOARD, u8 device, u16 *limstatus);

//Read Software Limit Status
FLEXFUNC flex_read_sw_lim_status(BOARD, u8 device, u8 retvect);
//Read Software Limit Status
FLEXFUNC flex_read_sw_lim_status_rtn(BOARD, u8 device, u16 *swlimstatus);

//Read Position Breakpoint Status
FLEXFUNC flex_read_pos_bp_status(BOARD, u8 device, u8 retvect);
//Read Position Breakpoint Status
FLEXFUNC flex_read_pos_bp_status_rtn(BOARD, u8 device, u16 *bpstatus);

//Read Anticipation Time Breakpoint Status
FLEXFUNC flex_read_at_bp_status(BOARD, u8 device, u8 retvect);
//Read Anticipation Time Breakpoint Status
FLEXFUNC flex_read_at_bp_status_rtn(BOARD, u8 device, u16 *status);

//Save Memory Object
FLEXFUNC flex_save_object(BOARD, u8 device);

//Delete Memory Object
FLEXFUNC flex_delete_object(BOARD, u8 device);

//Free Memory Object
FLEXFUNC flex_free_object(BOARD, u8 device);

//Wait on Condition
FLEXFUNC flex_wait(BOARD, u8 device, u16 cc, u8 muston, u8 mustoff, u16 timeout, u8 retvect);

//Wait on Condition
FLEXFUNC flex_wait_or(BOARD, u8 device, u16 cc, u8 muston, u8 mustoff, u16 timeout, u8 retvect);

//Jump to Label on Condition
FLEXFUNC flex_jump_label(BOARD, u8 resource, u16 condition, u8 mustOn, u8 mustOff, u16 labelNumber);

//Read Boot Version Number
FLEXFUNC flex_read_boot_ver_rtn(BOARD, u32 *bootver);

//Read Firmware Version Number
FLEXFUNC flex_read_firm_ver_rtn(BOARD, u32 *firmver);

//Read DSP Version Number
FLEXFUNC flex_read_dsp_ver_rtn(BOARD, u32 *dspver);

//Read FPGA Version Number
FLEXFUNC flex_read_fpga_ver_rtn(BOARD, u32 *fpgaver);

//Set Home Input Polarity
FLEXFUNC flex_set_home_pol(BOARD, u8 device, u16 homepol);

//Enable Home Inputs
FLEXFUNC flex_enable_homes(BOARD, u8 device, u16 homemap);

//Set Limit Input Polarity
FLEXFUNC flex_set_lim_pol(BOARD, u8 device, u16 polarity);

//Set Inhibit MOMO
FLEXFUNC flex_set_inhib_momo(BOARD, u8 device, u8 muston, u8 mustoff);

//Configure Inhibit Outputs
FLEXFUNC flex_config_inhibs(BOARD, u8 device, u8 axismap, u8 polmap);

//Read Home Input Status
FLEXFUNC flex_read_home_status(BOARD, u8 device, u8 retvect);
//Read Home Input Status
FLEXFUNC flex_read_home_status_rtn(BOARD, u8 device, u16 *homestatus);

//Read Velocity Threshold Status
FLEXFUNC flex_read_vel_status(BOARD, u8 device, u8 retvect);
//Read Velocity Threshold Status
FLEXFUNC flex_read_vel_status_rtn(BOARD, u8 device, u16 *status);

//Insert Label
FLEXFUNC flex_insert_label(BOARD, u8 device, u16 labelnum);

// Load Velocity
FLEXFUNC flex_load_vel(BOARD, u8 axisOrVectorSpace, i32 velocity, u8 inputVector);

//Read Velocity
FLEXFUNC flex_read_vel(BOARD, u8 axisOrVectorSpace, u8 returnVector);
//Read Velocity
FLEXFUNC flex_read_vel_rtn(BOARD, u8 axisOrVectorSpace, i32 *velocity);

//Load Velocity Threshold
FLEXFUNC flex_load_vel_thresh(BOARD, u8 axis, u32 threshold, u8 inputVector);

// Set I/O Port Direction
FLEXFUNC flex_set_port_dir (BOARD, u8 port, u16 direction);

//Load Counts per Revolution
FLEXFUNC flex_load_counts_rev(BOARD, u8 axis, u16 counts);

//Load Steps per Revolution
FLEXFUNC flex_load_steps_rev(BOARD, u8 axis, u16 steps);

//Set Breakpoint Output MOMO (replaced by flex_set_breakpoint_momo)
FLEXFUNC flex_set_bp_momo(BOARD, u8 axisOrEncoder, u8 mustOn, u8 mustOff);

//Set High-Speed Capture Polarity (replaced by flex_configure_hs_capture)
FLEXFUNC flex_set_hs_cap_pol(BOARD, u8 axisOrEncoder, u16 highSpeedCapturePolarity);

//Enable High-Speed Position Capture (replaced by flex_enable_hs_capture)
FLEXFUNC flex_enable_hs_caps(BOARD, u8 axisOrEncoder, u16 captureMap);

//Enable Breakpoint
FLEXFUNC flex_enable_bp(BOARD, u8 axisOrEncoder, u8 enableMode, u8 actionOnBreakpoint);

//Set Port MOMO (replaced by flex_set_port)
FLEXFUNC flex_set_port_momo(BOARD, u8 port, u8 mustOn, u8 mustOff);

//Read Error Message
FLEXFUNC flex_read_err_msg_rtn(BOARD, u16 *commandID, u16 *resourceID, u16 *errorCode);

//Load Velocity Filter Time Constant & Run/Stop Threshold
FLEXFUNC flex_load_vel_tc_rs(BOARD, u8 axis, u16 filterTime, u16 runStopThreshold, u8 inputVector);

///////////////////////////////////////////////////////////////////////////////////////////////////
/////////////  THESE FUNCTIONS ARE COMPATABILITY, BUT NOT REPLACED BY A NEW FUNCTION //////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

//Read Unfiltered Velocity
FLEXFUNC flex_read_raw_vel(BOARD, u8 axisorvectorspace, u8 retvect);
//Read Unfiltered Velocity
FLEXFUNC flex_read_raw_vel_rtn(BOARD, u8 axisorvectorspace, i32 *rawvel);

//Set Axis Mode
FLEXFUNC flex_set_axis_mode(BOARD, u8 axis, u16 axismode);

#ifdef __cplusplus
	}
#endif

#endif


text:
I'm a page that click a regular link.

Regular link


text:
package com.saasovation.common.domain;

/**
 * @author : huanghy
 * @create : 2016/4/19 0019 ÏÂÎç 4:11
 * @since : ${VERSION}
 */
public abstract class AbstractStateTracker implements  StateTracker{

    private long beginTrackMills;
    private long id;
    private volatile boolean isCompleted;
    private long timeout;

    public AbstractStateTracker(long id) {
        this(id,0);
    }

    public AbstractStateTracker(long id,long timeout) {
        this.beginTrackMills = System.currentTimeMillis();
        this.id = id;
        this.timeout = timeout;
    }

    public long id() {
        return this.id;
    }

    public long beginTrackMills() {
        return this.beginTrackMills;
    }

    public boolean isCompleted() {
        return this.isCompleted;
    }

    public void setCompleted(){
        this.isCompleted = true;
    }

    public boolean hasTimedOut() {
        return timeout==0 ? false:System.currentTimeMillis() > beginTrackMills+timeout;
    }
}


text:
! Test that sendget with strides on either side (of the assignment) works
! as expected.
!
! This test needs at least three images, because sendget has the potential
! to check whether on image used in the communication is the current one.
! More than three images do not pay, because there is no general code in
! this test.
!
! Written by Andre Vehreschild

program stridedsendgettest

  implicit none

  integer, parameter :: src_image = 2, dst_image = 3, master_image = 1
  integer, save, dimension(4,6) :: srcmat[*], dstmat[*]
  integer, save, dimension(6) :: srcvec[*], dstvec[*]
  integer :: i
  logical :: test_passed = .true.

  ! Make sure that enough images are available for this test.
  ! Everything less than dst_image == 3 may make sendget use an
  ! optimized version saving a part of the communication, which is
  ! not what the test should test.
  if (num_images() < dst_image) then
     print*, "Pretend that the test was run and passed, even though there are too few images to perform test:"
     print*, "Test passed"
     error stop "Need at least three images."
  end if

  ! On the src_image, set some defined values, to be able to distinguish
  ! strides going wrong.
  if (this_image() == src_image) then
    srcvec = [(2 * i, i = 1, 6)]
    srcmat = reshape([(i * 2, i = 1, 4*6)], [4,6])
  ! On the dst_image set values that enable to recognize unset values.
  elseif (this_image() == dst_image) then
    dstmat = -1
    dstvec = -2
  end if

  ! Make sure data is valid on all images.
  sync all

  ! master_image is the controller in this communication and therefore needs
  ! to initiate the communication.
  if (this_image() == master_image) then
    ! Transfer data from the src-vector to the dst-vector on image
    ! dst_image.  This is a transfer of a contingous block of data and here for
    ! completeness only.
    dstvec(:)[dst_image] = srcvec(:)[src_image]
    ! This statement uses a stride in the send phase of the communication.
    dstmat(3,:)[dst_image] = srcvec(:)[src_image]
  end if

  ! Make sure the communication has completed.
  sync all

  ! Check the result of communication on the dst_image.
  if (this_image() == dst_image) then
    ! Check that transfering to the vector has succeeded.
    if (any(dstvec /= [2, 4, 6, 8, 10, 12])) error stop "SendGet vec/vec does not match."

    ! Check that transfering a vector into a matrix changes only the
    ! values desired.
    if (any(dstmat /= reshape([-1, -1,  2, -1, &
                               -1, -1,  4, -1, &
                               -1, -1,  6, -1, &
                               -1, -1,  8, -1, &
                               -1, -1, 10, -1, &
                               -1, -1, 12, -1], [4, 6]))) then
      error stop "SendGet matrow/vec does not match."
    end if
    ! Reset the dst-buffers to enable new test.
    dstvec = -2
    dstmat = -1
  end if

  ! Wait for dst having done its tests.
  sync all
  if (this_image() == master_image) then
    ! Execute strided get in sendget and store in a vector to just
    ! test the get.
    dstvec(:)[dst_image] = srcmat(2,:)[src_image]
    ! Test both strided get and strided send at once.
    dstmat(3,:)[dst_image] = srcmat(2,:)[src_image]
  end if

  ! Ensure that the communication is all done.
  sync all
  if (this_image() == dst_image) then
    ! Check, that the strided get has the expected result.
    if (any(dstvec /= [4, 12, 20, 28, 36, 44])) error stop "SendGet vec/matrow does not match."

    ! And that both communications with stride work as expected.
    if (any(dstmat /= reshape([-1, -1,  4, -1, &
                               -1, -1, 12, -1, &
                               -1, -1, 20, -1, &
                               -1, -1, 28, -1, &
                               -1, -1, 36, -1, &
                               -1, -1, 44, -1], [4, 6]))) then
      error stop "SendGet matrow/matrow does not match."
    end if

    ! Above checks would stop with an error on failure, so its save
    ! to unguardedly print here, when all tests pass.
    print *, "Test passed"
  end if
end program


text:
import { apolloClient } from '../'

import storyCommentsQuery from '../queries/storyComments'

// constants ========
export const LOADING_COMMENTS_KIDS = 'LOADING_COMMENTS_KIDS'

export const FETCH_COMMENTS_KIDS_SUCCESS = 'FETCH_COMMENTS_KIDS_SUCCESS'
export const FETCH_COMMENTS_KIDS_FAIL = 'FETCH_COMMENTS_KIDS_FAIL'

// ==================
export default id => async dispatch => {
  dispatch({ type: LOADING_COMMENTS_KIDS, payload: { id } })

  try {
    const res = await apolloClient.query({
      query: storyCommentsQuery,
      variables: { id },
    })

    dispatch({
      type: FETCH_COMMENTS_KIDS_SUCCESS,
      payload: { id, data: res.data.storyComments },
    })
  } catch (error) {
    dispatch({ type: FETCH_COMMENTS_KIDS_FAIL, payload: { id } })
  }
}


text:
"""
Create, roll and manipulate sets and bags of dices.

The DiceSet class describes one set of dices, while DiceBag wraps this into a
more general thing (actually, its just creating a list of DiceSets and adding
some functionality).

E.g., to describe 3 dices of 6 faces each,
    d = DiceSet(3,6)
but, to describe that and 2 dices of 4 faces,
    b = DiceBag((3,6), (2,4))
and so on.

Also, some checks are made, so no negative number of quantity or faces are
allowed (seems obvious, but no one knows) and any set with zero or less dices are
automagically removed from the set.
"""

import random

class DiceSet:
    """
    Describe a number of dices with the same number of faces.
    """

    def __init__(self, n, f):
        """
        Initialize a set of n dices of f faces.

        Keyword arguments:
            n (int, >=1) => number of dices
            f (int, >=1) => number of faces
        """
        # on invalid input, just return and do nothing
        if (n <= 0) or (f <= 0): return

        self.faces = f
        self.qnt = n
        self.__roll = self.qnt*[0]

    def __repr__(self):
        """
        String to represent the same object when eval()ed.
        """
        return("DiceSet(%d, %d)" % (self.qnt, self.faces))

    def __str__(self):
        """
        Human-readble string to represent the object.
        """
        return("Set of %d dices with %d faces." % (self.qnt, self.faces))

    def __eq__(self, other):
        """
        Tests for equality of two objects.
        """
        return( (self.qnt == other.qnt) and (self.faces == other.faces) )

    def __ne__(self, other):
        """
        Tests for inequality of two objects.
        """
        return(not self.__eq__(other))

    def add(self, n):
        """
        Add some dices to the current set.

        If n is negative, self.remove is called instead.

        Keyword arguments:
            n (int, >=0) => number of dices to be added
        """
        if n >= 0:
            self.qnt += n
        else:
            self.remove(abs(n))

    def remove(self, n):
        """
        Remove some dices from the set. If you try to remove more then current
        qnt, value will be set to 0 instead.

        If n is negative, self.add is called instead.

        Keyword arguments:
            n (int, >=0) => number of dices to be removed
        """
        if n >= 0:
            if (self.qnt - n) >= 0:
                self.qnt -= n
            else:
                self.qnt = 0
        else:
            self.add(abs(n))

    def check_roll(self):
        """
        Checks the existence/compatibility of the stored roll.
        """
        # if the list of rolls does not contain zeros and its len is compatible
        # with qnt, then the current roll is valid for the current set
        return( all(i != 0 for i in self.__roll) and len(self.__roll) == \
                self.qnt )

    def current_roll(self):
        """
        Returns the current roll, existing or not.
        """
        return(self.__roll)

    def roll(self):
        """
        Rolls the current set of dice, returning the list of rolls.
        """
        self.__roll = self.qnt*[0]

        for i in range(0,self.qnt):
            self.__roll[i] = random.randint(1,self.faces)

    def roll_ifnot(self):
        """
        Rolls the current set, but only if it is not yet rolled.
        """
        if not self.check_roll():
            self.roll()

    def sum_roll(self):
        """
        Sum of the current roll.
        """
        return(sum(self.__roll))

class DiceBag:
    """
    Describes a set of dices with diferent face numbers.
    """
    def __init__(self, *list_of_adds):
        """
        Initializes the object with some sets of dices.

        E.g. to initialize a bag containing 3 dices with 6 faces and 1 dice of 4
        faces:
             d = DiceBag((3,6), (1,4))
        will do the trick.

        Keyword arguments:
            list_of_adds (list of tuples) => tuples to represent the sets to be
                added
        """
        self.bag = [] # start as an empty bag

        # and add each set listed
        for tpl in list_of_adds:
            self.add_to_bag(tpl[0], tpl[1])

    def __repr__(self):
        """
        String to represent the same object when eval()ed.
        """
        r = "DiceBag("

        for idx,dice in enumerate(self.bag):
            r += "(" + str(dice.qnt) + "," + str(dice.faces) + ")"
            if idx != (len(self.bag) - 1): r += ", "

        r += ")"

        return(r)

    def __str__(self):
        """
        Human-readble string to represent the current object.
        """
        # if the bag is empty
        if self.bag == []: return("Bag does not contain dices.")

        # prints the total number of dices
        message = "Bag contains %d dices:\n" % (self.total_dices())
        # and print each set of dices
        for dice in self.bag:
            message += "\t%d of %d faces\n" % (dice.qnt, dice.faces)

        return(message)

    def __eq__(self, other):
        """
        Tests for equality of two objects.

        Keyword arguments:
            other (DiceBag) => object to be compared
        """
        if len(self.bag) != len(other.bag): return False

        return( any([this_dice == other_dice for other_dice in other.bag \
                                             for this_dice in self.bag]) )

    def __ne__(self, other):
        """
        Tests for inequality of two objects.

        Keyword arguments:
            other (DiceBag) => object to be compared
        """
        return(not self.__eq__(other))

    def add_to_bag(self, n, f):
        """
        Add n dices of f faces to current bag.

        E.g. if m dices of f faces are already in the bag, then the current
        number of f-faced dices will change to (n+m).

        Also, if n is zero, nothing will be done.

        Keyword arguments:
            n (int, >1) => number of dices to be added
            f (int, >1) => number of faces of the dice
        """

        # if the user tries to add something idiot, do nothing
        if (n <= 0) or (f <= 0): return

        new_dice = DiceSet(n, f)

        # list of dice faces already in the bag
        facelist = [dice.faces for dice in self.bag]

        if new_dice.faces in facelist:
            # if the dice is already in the bag, find its index in it
            # and add the new amount
            self.bag[facelist.index(new_dice.faces)].qnt += new_dice.qnt
        else:
            self.bag.append(new_dice)

    def remove_from_bag(self, *list_of_rms):
        """
        Removes some dices from the bag. Arguments are supposed to be tuples of
        (qnt,faces).

        Keyword arguments:
            list_of_rms (list) => tuples of (num, faces) to be removed
        """
        # nested loop of the list_of_rms and self.bag
        for tpl,dice in [(t,d) for t in list_of_rms for d in self.bag]:
            # if we find a match in the number of faces
            if dice.faces == tpl[1]:
                dice.remove(tpl[0]) # remove tpl[0] dices from the set

        # clean the bag (removes sets with no dices in)
        self.clean_bag()

    def total_dices(self):
        """
        Counts the number of dices currently stored in bag.
        """
        n = 0

        for dice in self.bag: n += dice.qnt

        return(n)

    def clean_bag(self):
        """
        Removes any dices with 0 qnt from the bag.
        """

        # build a list of qnts
        dices_qnt = [dice.qnt for dice in self.bag]

        # build list of indices to be removed
        rm_list = []

        # search for sets with 0 dices
        for idx,qnt in enumerate(dices_qnt):
            if qnt == 0:
                rm_list.append(idx)

        rm_list.sort() # just to be safe, sort the list, because below

        for idx in reversed(rm_list):
            # yup, rm_list NEEDS to be reversed, so it deletes from the highest
            # indexes first (else the wrong items would be deleted, or will try
            # an out-of-range deletion)
            self.bag.pop(idx)

    def show_bag(self):
        """
        Shows the current dices added to bag.
        """
        return( {dice.faces:dice.qnt for dice in self.bag} )

    def current_roll(self):
        """
        Shows the stored roll.
        """
        return( {dice.faces:dice.current_roll() for dice in self.bag} )

    def check_rolls(self):
        """
        Check if the current roll is valid for the current bag of dices.
        """
        return( all([dice.check_roll() for dice in self.bag]) )

    def roll(self):
        """
        Roll the current bag.
        """
        for dice in self.bag:
            dice.roll()

    def roll_ifnot(self):
        """
        Rolls the current bag of dices, but only when (and those) not yet
        rolled.

        Basically, it uses the same function from DiceSet, but checking every
        set in the bag. So, if the set is not rolled, only this will roll again.
        """
        for dice in self.bag:
            dice.roll_ifnot()

    def sum_roll(self):
        """
        Sums the current roll, existing or not.
        """
        return(sum([dice.sum_roll() for dice in self.bag]))


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

namespace Code.ConvertingForToLinq
{
    public static class LinqReplacer
    {
        public static IEnumerable<T> Replace<T>(
            this IEnumerable<T> elements,
            Func<T, bool> match,
            Func<T, IEnumerable<T>> replacer)
        {
            bool hasReplaced = false;
            foreach (var element in elements)
            {
                if (!hasReplaced && match(element))
                {
                    hasReplaced = true;
                    foreach (var replaced in replacer(element))
                    {
                        yield return replaced;
                    }
                }
                else
                {
                    yield return element;
                }
            }
        }
    }
}


text:
require 'cgi'
require 'net/https'
require 'uri'

class Prowl
  class MissingAPIKey < RuntimeError; end
  class TooManyAPIKeys < RuntimeError; end
  class PriorityOutOfRange < RuntimeError; end

  API_URL = "https://prowl.weks.net:443/publicapi"
  MAX_API_KEYS = 5
  PRIORITY_RANGE = -2..2

  def initialize(defaults = {})
    @defaults = defaults
  end

  def add(params = {})
    perform("add", params)
  end

  # Modify this instance's defaults
  def defaults(params)
    @defaults = @defaults.merge(params)
  end

  def valid?
    @valid ||= (perform("verify") == 200)
  end

  # Utility function that creates an instance and sends a prowl
  def self.add(params = {})
    new(params).add
  end

  # Utility function to verify API keys
  def self.verify(apikey)
    new({:apikey => apikey}).valid?
  end

  private

  def perform(action, params = {})
    # Merge the default params with any custom ones
    unless !@defaults
      params = @defaults.merge(params)
    end

    if !params[:apikey] || (params[:apikey].is_a?(Array) && params[:apikey].size < 1)
      raise MissingAPIKey
    end

    # Raise an exception if we're trying to use more API keys than allowed for this action
    if params[:apikey].is_a?(Array) && ((action == "verify" && params[:apikey].size > 1) || params[:apikey].size > MAX_API_KEYS)
      raise TooManyAPIKeys
    end

    if params[:priority] && !PRIORITY_RANGE.include?(params[:priority])
      raise PriorityOutOfRange
    end

    # If there are multiple API Keys in an array, merge them into a comma-delimited string
    if params[:apikey].is_a?(Array)
      params[:apikey] = params[:apikey].collect{|v| v + ","}.to_s.chop
    end

    uri = URI.parse("#{API_URL}/#{action}")
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE

    request = Net::HTTP::Get.new(uri.request_uri + "?" + params.map {|k, v| "#{k}=#{CGI.escape(v.to_s)}"}.join("&"))
    response = http.request(request)
    return response.code.to_i
  end
end

# For me and my good friend friend Textmate.
if __FILE__ == $0
  api_key = "change me"

  p Prowl.add(:apikey => api_key, :application => "Fishes", :event => "silly", :description => "Awwawaw.", :priority => 1)
  p Prowl.verify(api_key)
end


text:
/*!
    \file wolfssl/wolfcrypt/compress.h
*/

#ifndef WOLF_CRYPT_COMPRESS_H
#define WOLF_CRYPT_COMPRESS_H

#include <wolfssl/wolfcrypt/types.h>

#ifdef HAVE_LIBZ

#ifdef __cplusplus
    extern "C" {
#endif

#define COMPRESS_FIXED 1

WOLFSSL_API int wc_Compress(byte*, word32, const byte*, word32, word32);
WOLFSSL_API int wc_DeCompress(byte*, word32, const byte*, word32);

#ifdef __cplusplus
    } /* extern "C" */
#endif

#endif /* HAVE_LIBZ */
#endif /* WOLF_CRYPT_COMPRESS_H */


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

namespace Altus.Suffūz.Messages
{
    public class CapacityRequest<TRequest, TResponse>
    {
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Accord.Math;
using Accord.Statistics.Distributions.Multivariate;
using Newtonsoft.Json;
using QuantSA.Shared.Dates;
using QuantSA.Shared.Exceptions;
using QuantSA.Shared.MarketData;
using QuantSA.Shared.MarketObservables;
using QuantSA.Shared.Primitives;

namespace QuantSA.Valuation.Models.Equity
{
    /// <summary>
    /// A <see cref="Simulator"/> that can provide realizations of several share prices in a single currency.
    /// </summary>
    public class EquitySimulator : NumeraireSimulator
    {
        private readonly IDiscountingSource _discountCurve;
        private readonly double[] _divYields;
        private readonly double[] _prices;
        private readonly Dictionary<string, IFloatingRateSource> _rateForecastCurves;
        private readonly Share[] _shares;
        private readonly double[] _vols;
        private readonly double[,] _correlations;

        [JsonIgnore] private MultivariateNormalDistribution _normal;
        [JsonIgnore] private Date _anchorDate;
        [JsonIgnore] private Dictionary<int, double[]> _acculatedDivi;
        [JsonIgnore] private List<Date> _allRequiredDates;
        [JsonIgnore] private Dictionary<int, double[]> _simulation;

        /// <summary>
        /// Initializes a new instance of the <see cref="EquitySimulator"/> class.
        /// </summary>
        /// <param name="shares">An array of shares that will be simulated.</param>
        /// <param name="prices">The prices of the supplied shares.</param>
        /// <param name="vols">The annualized volatilities of the supplied shares.</param>
        /// <param name="divYields">The continuous dividend yields.</param>
        /// <param name="correlations">The correlation matrix for all the shares.</param>
        /// <param name="discountCurve">The discount curve that will be also be used to determine the drift on the shares.</param>
        /// <param name="rateForecastCurves">Deterministic rate forecast curves, used for example when a
        /// structure includes a loan whose interest needs to be calculated during the simulation.</param>
        public EquitySimulator(Share[] shares, double[] prices, double[] vols, double[] divYields,
            double[,] correlations, IDiscountingSource discountCurve, IFloatingRateSource[] rateForecastCurves)
        {
            _shares = shares;
            _prices = prices;
            _vols = vols;
            _divYields = divYields;
            _discountCurve = discountCurve;
            _correlations = correlations;
            _rateForecastCurves = new Dictionary<string, IFloatingRateSource>();
            if (rateForecastCurves == null) return;
            foreach (var floatingRateSource in rateForecastCurves)
            {
                if (floatingRateSource == null) continue;
                _rateForecastCurves.Add(floatingRateSource.GetFloatingIndex().ToString(), floatingRateSource);
            }
        }

        public override double[] GetIndices(MarketObservable index, List<Date> requiredTimes)
        {
            if (index is FloatRateIndex)
            {
                var result = new double[requiredTimes.Count];
                for (var i = 0; i < requiredTimes.Count; i++)
                    result[i] = _rateForecastCurves[index.ToString()].GetForwardRate(requiredTimes[i]);
                return result;
            }

            if (index is Dividend)
            {
                var result = Vector.Zeros(requiredTimes.Count);
                var shareIndex = _shares.IndexOf(((Dividend) index).Underlying);
                var divCounter = 0;
                foreach (int dateInt in _allRequiredDates)
                {
                    if (dateInt > requiredTimes[divCounter])
                    {
                        divCounter++;
                        if (divCounter >= requiredTimes.Count)
                            break;
                    }

                    result[divCounter] += _acculatedDivi[dateInt][shareIndex];
                }

                return result;
            }
            if (index is Share share)
            {
                var shareIndex = _shares.IndexOf(share);
                var result = new double[requiredTimes.Count];
                for (var i = 0; i < requiredTimes.Count; i++)
                    if (requiredTimes[i] == _anchorDate)
                        result[i] = _prices[shareIndex];
                    else
                        result[i] = _simulation[requiredTimes[i]][shareIndex];
                return result;
            }

            throw new MarketObservableNotSupportedException(
                $"{index} is not supported by this {nameof(EquitySimulator)}");
        }

        /// <summary>
        /// Indicate whether the required share price is simulated by this model
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public override bool ProvidesIndex(MarketObservable index)
        {
            if (_shares.Contains(index)) return true;

            if (_rateForecastCurves.ContainsKey(index.ToString())) return true;

            var divIndex = index as Dividend;
            if (divIndex != null)
                return _shares.Contains(divIndex.Underlying);
            return false;
        }

        /// <summary>
        /// Clear the dates that have been set
        /// </summary>
        public override void Reset()
        {
            _allRequiredDates = new List<Date>();
        }

        /// <summary>
        /// Remove duplicate dates and sort the list
        /// </summary>
        public override void Prepare(Date anchorDate)
        {
            _anchorDate = anchorDate;
            _allRequiredDates = _allRequiredDates.Distinct().ToList();
            _allRequiredDates.Sort();
            _normal = new MultivariateNormalDistribution(Vector.Zeros(_prices.Length), _correlations);
        }

        /// <summary>
        /// Run a simulation and store the results for later use by <see cref="GetIndices(MarketObservable, List{Date})"/>
        /// </summary>
        /// <param name="simNumber"></param>
        public override void RunSimulation(int simNumber)
        {
            _simulation = new Dictionary<int, double[]>();
            _acculatedDivi = new Dictionary<int, double[]>();
            var simPrices = _prices.Copy();
            double oldDF = 1;
            double newDF;

            for (var timeCounter = 0; timeCounter < _allRequiredDates.Count; timeCounter++)
            {
                double dt = timeCounter > 0
                    ? _allRequiredDates[timeCounter] - _allRequiredDates[timeCounter - 1]
                    : _allRequiredDates[timeCounter] - _anchorDate.value;
                newDF = _discountCurve.GetDF(_allRequiredDates[timeCounter]);
                var rateDrift = oldDF / newDF;
                oldDF = newDF;
                dt = dt / 365.0;
                var sdt = Math.Sqrt(dt);
                var dW = _normal.Generate();
                _acculatedDivi[_allRequiredDates[timeCounter]] = Vector.Zeros(_shares.Length);
                for (var s = 0; s < _shares.Length; s++)
                {
                    _acculatedDivi[_allRequiredDates[timeCounter]][s] = simPrices[s] * _divYields[s] * dt;
                    simPrices[s] = simPrices[s] * rateDrift *
                                   Math.Exp((-_divYields[s] - 0.5 * _vols[s] * _vols[s]) * dt + _vols[s] * sdt * dW[s]);
                }

                _simulation[_allRequiredDates[timeCounter]] = simPrices.Copy();
            }
        }

        public override void SetRequiredDates(MarketObservable index, List<Date> requiredDates)
        {
            _allRequiredDates.AddRange(requiredDates);
        }

        public override Currency GetNumeraireCurrency()
        {
            return _discountCurve.GetCurrency();
        }

        public override double Numeraire(Date valueDate)
        {
            return 1.0 / _discountCurve.GetDF(valueDate);
        }

        public override void SetNumeraireDates(List<Date> requiredDates)
        {
            // Nothing needs to be done since we are using a deterministic curve.
        }

        public override double[] GetUnderlyingFactors(Date date)
        {
            var sharePrices = new double[_shares.Length];
            for (var i = 0; i < _shares.Length; i++) sharePrices[i] = GetIndices(_shares[i], new List<Date> {date})[0];
            return sharePrices;
        }
    }
}


text:
package com.asakusafw.windgate.core.resource;

import java.io.Closeable;
import java.io.IOException;

import com.asakusafw.windgate.file.resource.Preparable;

/**
 * An abstract super interface of data source driver.
 * @param <T> the type of source data models
 * @since 0.2.2
 */
public interface SourceDriver<T> extends Preparable, Closeable {

    /**
     * Prepares this driver to invoke {@link #next()} method.
     * This method will be invoked before {@link #next()} only once.
     * This operation can execute only on the same thread as created this object.
     * @throws IOException if failed to begi
     */
    @Override
    void prepare() throws IOException;

    /**
     * Returns true iff the next data model object exists,
     * and then the {@link #get()} method returns its object.
     * This operation can execute only on the same thread as created this object.
     * @return {@code true} if the next data model object exists, otherwise {@code false}
     * @throws IOException if failed to prepare the next data
     */
    boolean next() throws IOException;

    /**
     * Gets the current data model object prepared by the {@link #next()} method.
     * This operation can execute only on the same thread as created this object.
     * @return the next data model object
     * @throws IOException if failed to prepare the next data
     * @throws IllegalStateException if the next data model object does not exist
     * @see #next()
     */
    T get() throws IOException;

    /**
     * Disposes this object.
     * This operation can execute only on the same thread as created this object.
     * @throws IOException if failed to connect
     */
    @Override
    void close() throws IOException;
}


text:
namespace Nager.PublicSuffix.Website.Model
{
    public class DomainReport
    {
        public bool Valid { get; set; }
        public string Domain { get; set; }
        public string TLD { get; set; }
        public string SubDomain { get; set; }
        public string RegistrableDomain { get; set; }
        public string Hostname { get; set; }
    }
}


text:
package com.kirby.runanjing.adapter;
import android.support.v7.widget.*;
import android.view.*;
import android.widget.*;
import com.kirby.runanjing.*;
import com.kirby.runanjing.untils.*;
import java.util.*;
import android.content.*;
import com.kirby.runanjing.activity.*;
import com.bumptech.glide.*;
import com.kirby.runanjing.fragment.*;
import com.kirby.runanjing.bean.*;

public class JszGameAdapter extends RecyclerView.Adapter<JszGameAdapter.ViewHolder>
{

	private List<Console> mJszGameList;
	private Context mContext;
	static class ViewHolder extends RecyclerView.ViewHolder
	{
        LinearLayout LinearLayout;
		CardView cardView;
        ImageView gameImage;
        TextView gameName;
        public ViewHolder(View view)
		{
            super(view);
			LinearLayout = (LinearLayout)view.findViewById(R.id.LinearLayout);
            cardView = (CardView) view.findViewById(R.id.cardview);
			gameImage = (ImageView) view.findViewById(R.id.console_image);
            gameName = (TextView) view.findViewById(R.id.console_text);
        }
    }

    public JszGameAdapter(List<Console> jszgamelist)
	{
        mJszGameList = jszgamelist;
    }
	@Override
	public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
	{
		if (mContext == null)
		{
            mContext = parent.getContext();
        }
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_console, parent, false);
		final ViewHolder holder=new ViewHolder(view);
		holder.LinearLayout.setOnClickListener(new View.OnClickListener(){
				@Override
				public void onClick(View v)
				{
					int position=holder.getAdapterPosition();
					Console console=mJszGameList.get(position);
					Intent in=new Intent(mContext, JszActivity.class);
					String  input=console.getName().toString();
					MainActivity m=new MainActivity();
					//m.otherReplaceFragment(new JszFragment());
					mContext.startActivity(in);
					SharedPreferences.Editor t=mContext.getSharedPreferences("string", 0).edit();
					t.putString("金手指_游戏", input);
					t.apply();
				}
			}
		);
		return holder;
	}

	@Override
	public void onBindViewHolder(ViewHolder holder, int position)
	{
		Console co = mJszGameList.get(position);
        holder.gameName.setText(co.getName());
        Glide.with(mContext).load(co.getImageUrl()).into(holder.gameImage);
	}

	@Override
	public int getItemCount()
	{
		return mJszGameList.size();
	}

}


text:
require 'rails_helper'

describe EmergencyContact, type: :model do
  context '#responsive_methods' do
    it { should respond_to :name }
    it { should respond_to :phone }
    it { should respond_to :kinship }
    it { should respond_to :account }
    it { should respond_to :father? }
    it { should respond_to :mother? }
    it { should respond_to :sibling? }
    it { should respond_to :other? }
  end

  context '#relationships' do
    it { should belong_to :account }
  end

  context '#validations' do
    it { should validate_presence_of(:name).with_message('não pode ficar em branco') }
    it { should validate_presence_of(:phone).with_message('não pode ficar em branco') }
    it { should validate_presence_of(:kinship).with_message('não pode ficar em branco') }
    it { should validate_presence_of(:account).with_message('não pode ficar em branco').on(:save) }
  end
end


text:
package jp.sourceforge.ea2ddl.dao.exbhv;

import jp.sourceforge.ea2ddl.dao.cbean.TOperationparamsCB;
import jp.sourceforge.ea2ddl.dao.exentity.TOperation;
import jp.sourceforge.ea2ddl.dao.exentity.TOperationparams;

import org.seasar.dbflute.cbean.ListResultBean;

/**
 * The behavior of t_operationparams.
 * <p>
 * You can implement your original methods here.
 * This class is NOT overrided when re-generating.
 * </p>
 * @author DBFlute(AutoGenerator)
 */
public class TOperationparamsBhv extends jp.sourceforge.ea2ddl.dao.bsbhv.BsTOperationparamsBhv {
	public ListResultBean<TOperationparams> selectOperationParams(TOperation operation) {
		final TOperationparamsCB cb = new TOperationparamsCB();
		cb.query().setOperationid_Equal(operation.getOperationid());
		cb.query().addOrderBy_Pos_Asc();
		return selectList(cb);
	}
}


text:
package software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform;

import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;

/**
 * A pairing of {@link SdkMetric} and {@link Dimension}s that can be used as a key in a map. This uniquely identifies a specific
 * {@link MetricAggregator}.
 */
@SdkInternalApi
class MetricAggregatorKey {
    private final SdkMetric<?> metric;
    private final List<Dimension> dimensions;

    MetricAggregatorKey(SdkMetric<?> metric, List<Dimension> dimensions) {
        this.metric = metric;
        this.dimensions = dimensions;
    }

    public final SdkMetric<?> metric() {
        return this.metric;
    }

    public final List<Dimension> dimensions() {
        return this.dimensions;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        MetricAggregatorKey that = (MetricAggregatorKey) o;

        if (!metric.equals(that.metric)) {
            return false;
        }
        return dimensions.equals(that.dimensions);
    }

    @Override
    public int hashCode() {
        int result = metric.hashCode();
        result = 31 * result + dimensions.hashCode();
        return result;
    }
}


text:
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
-->

<form class="form" [formGroup]="form" (ngSubmit)="login()">
  <mat-form-field class="form__input">
    <input matInput placeholder="Email Address" type="email" formControlName="email">
  </mat-form-field>

  <mat-form-field class="form__input">
    <input matInput placeholder="Password" type="password" formControlName="password">
  </mat-form-field>

  <div class="form-actions">
    <button class="form-actions__login" mat-raised-button color="primary" type="submit">Login</button>
  </div>
</form>


text:
/**
 * @fileOverview The builtin Date object.
 */
define(['exports',
        'bes/record',
        'atum/compute',
        'atum/fun',
        'atum/compute/io',
        'atum/builtin/date',
        'atum/builtin/object',
        'atum/builtin/meta/date',
        'atum/builtin/meta/object',
        'atum/builtin/operations/builtin_constructor',
        'atum/builtin/operations/builtin_function',
        'atum/operations/construct',
        'atum/operations/func',
        'atum/operations/number',
        'atum/operations/string',
        'atum/operations/object',
        'atum/operations/type_conversion',
        'atum/operations/value_reference',
        'atum/value/property'],
function(exports,
        record,
        compute,
        fun,
        io,
        date_builtin,
        object_builtin,
        meta_date,
        meta_object,
        builtin_constructor,
        builtin_function,
        construct,
        func,
        number,
        string,
        object,
        type_conversion,
        value_reference,
        property){
"use strict";

/* DateInstance
 ******************************************************************************/
var DateInstance = record.extend(meta_date.Date,
    [],
    function(primitiveValue) {
        meta_date.Date.call(this, this.proto, this.properties, true, primitiveValue);
    });

DateInstance.prototype.proto = date_builtin.DatePrototype;

DateInstance.prototype.properties = {};

/* Date
 ******************************************************************************/
/**
 * `Date(...)`
 */
var DateCall = function(ref, thisObj, args) {
    return compute.bind(
        construct.construct(date_builtin.Date, []),
        function(t) {
            return func.call(date_builtin.DatePrototypeValueOf, t, []);
        });
};

/**
 * `new Date(...)`.
 */
var DateConstruct = function(ref, args) {
    if (args.length === 0)
        return compute.bind(
            compute.liftIO(io.now),
            fun.compose(
                value_reference.create,
                DateInstance.create));

    // @TODO
    throw null;
};

var DateProperties = {
    'isDate':  property.createValuePropertyFlags(
        date_builtin.DateIsDate),

    'prototype': property.createValuePropertyFlags(
        date_builtin.DatePrototype)
};

/* DatePrototype
 ******************************************************************************/
/**
 * `Date.prototype`
 */
var DatePrototype = new meta_object.Object(
    object_builtin.ObjectPrototype, {
        'constructor': property.createValuePropertyFlags(
            date_builtin.Date),

        'getTime': property.createValuePropertyFlags(
            date_builtin.DatePrototypeGetTime,
            property.WRITABLE | property.CONFIGURABLE),

        'valueOf': property.createValuePropertyFlags(
            date_builtin.DatePrototypeValueOf,
            property.WRITABLE | property.CONFIGURABLE),

        'toString': property.createValuePropertyFlags(
            date_builtin.DatePrototypeToString,
            property.WRITABLE | property.CONFIGURABLE),
    },
    true);

var DatePrototypeGetTime = function(ref, thisObj, args) {
    return value_reference.dereference(thisObj, function(t) {
        if (!(t instanceof meta_date.Date))
            return error.typeError();

        return number.create(t.primitiveValue.getTime());
    });
};

var DatePrototypeToString = function(ref, thisObj, args) {
    return value_reference.dereference(thisObj, function(t) {
        if (!(t instanceof meta_date.Date))
            return error.typeError();

        return string.create(new Date(t.primitiveValue) + '');
    });
};

var DatePrototypeValueOf = function(ref, thisObj, args) {
    return value_reference.dereference(thisObj, function(t) {
        if (!(t instanceof meta_date.Date))
            return error.typeError();

        return number.create(t.primitiveValue.valueOf());
    });
};

/* Initialization
 ******************************************************************************/
var initialize = function() {
    return compute.sequence(
        builtin_constructor.create(date_builtin.Date, 'Date', 0, DateProperties, DateCall, DateConstruct),

        date_builtin.DatePrototype.setValue(DatePrototype),
        builtin_function.create(date_builtin.DatePrototypeGetTime, 'getTime', 0, DatePrototypeGetTime),
        builtin_function.create(date_builtin.DatePrototypeToString, 'toString', 0, DatePrototypeToString),
        builtin_function.create(date_builtin.DatePrototypeValueOf, 'valueOf', 0, DatePrototypeValueOf));
};

var configure = function(mutableBinding, immutableBinding) {
    return compute.sequence(
        mutableBinding('Date', date_builtin.Date));
};

var execute = function() {
    return compute.empty;
};

/* Export
 ******************************************************************************/
exports.initialize = initialize;
exports.configure = configure;
exports.execute = execute;

});


text:
#include <mm/VirtualArea.hpp>
#include <include/constant.h>
#include <algorithm>

#include <mm/PhysicalAllocator.hpp>
#include <fs/vfs/PageCache.hpp>

VirtualArea::VirtualArea(uint64_t* addrStart, uint64_t* addrEnd, uint64_t flags,
						 File* file, uint64_t offset, uint64_t fileSize)
{
	this->addrStart = addrStart;
	this->addrEnd = addrEnd;
	this->flags = flags;
	this->file = file;
	this->offset = offset;
	this->fileSize = fileSize;
	uint64_t nbPages = (((uint64_t)addrEnd) + PAGE_SIZE - 1) / PAGE_SIZE
		- ((uint64_t)addrStart) / PAGE_SIZE;
	if ((flags & FLAGS::VM_WRITE)
		&& !(flags & FLAGS::VM_SHARED)) {
		physicalPages = new PhysicalMapping(nbPages);
	} else {
		physicalPages = nullptr;
	}
}

VirtualArea::VirtualArea(const VirtualArea& virtArea)
{
	addrStart = virtArea.addrStart;
	addrEnd = virtArea.addrEnd;
	flags = virtArea.flags;
	file = virtArea.file;
	offset = virtArea.offset;
	fileSize = virtArea.fileSize;
	if (virtArea.physicalPages != nullptr) {
		physicalPages = new PhysicalMapping(*(virtArea.physicalPages));
	} else {
		physicalPages = nullptr;
	}
}

VirtualArea::~VirtualArea()
{
	delete this->physicalPages;
}

size_t VirtualArea::getNbPages()
{
	return (((uint64_t)addrEnd) + PAGE_SIZE - 1) / PAGE_SIZE
		- ((uint64_t)addrStart) / PAGE_SIZE;
}

Page* VirtualArea::getPage(uint64_t index)
{
	if (physicalPages != nullptr) {
		Page* page = physicalPages->getPage(index);
		if (page == nullptr) {
			page = PhysicalAllocator::allocZeroedPage();
			physicalPages->setPage(index, page);
			// Copy page if it comes from a file
			if (file != nullptr) {
				int64_t startPageOffset = (offset / PAGE_SIZE + index) * PAGE_SIZE;
				int64_t startOffsetLimit = (int64_t)offset - startPageOffset;
				int64_t startCpy = std::max(startOffsetLimit, (int64_t)0);

				int64_t endOffsetLimit = startOffsetLimit + fileSize;
				int64_t endCpy = std::min((int64_t)PAGE_SIZE, endOffsetLimit);

				AddressSpace* mapping = file->getInode()->mapping;
				int fileIndex = offset / PAGE_SIZE + index;
				Page* filePage = PageCache::getPage(mapping, fileIndex);
				mapping->readPage(filePage);
				for (int64_t i = startCpy; i < endCpy; ++i) {
					((char*)(page->kernelMappAddr))[i] = ((char*)(filePage->kernelMappAddr))[i];
				}

			}
		}
		return page;
	} else {
		AddressSpace* mapping = file->getInode()->mapping;
		int fileIndex = offset / PAGE_SIZE + index;
		Page* page = PageCache::getPage(mapping, fileIndex);
		mapping->readPage(page);
		return page;
	}
}

bool VirtualArea::tryMergeArea(VirtualArea* area)
{
	if (this->flags != area->flags) {
		return false;
	}
	if ((this->addrEnd != area->addrStart)
		& (this->file == area->file)) {
		return false;
	}
	if (this->file == nullptr) {
		this->addrEnd = area->addrEnd;
		this->physicalPages->pushBack(area->physicalPages);
		return true;
	}
	if ((offset + (uint64_t)addrEnd - (uint64_t)addrStart) == area->offset) {
		this->addrEnd = area->addrEnd;
		return true;
	}
	return false;
}