text:
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema prols
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `prols` ;

-- -----------------------------------------------------
-- Schema prols
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `prols` DEFAULT CHARACTER SET utf8 ;
USE `prols` ;

-- -----------------------------------------------------
-- Table `prols`.`emp_acc`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`emp_acc` ;

CREATE TABLE IF NOT EXISTS `prols`.`emp_acc` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(45) NOT NULL,
  `password` VARCHAR(45) NOT NULL,
  `timestamp` DATETIME NOT NULL,
  `ip_add` VARCHAR(45) NOT NULL,
  `status` VARCHAR(45) NOT NULL,
  `email` VARCHAR(45) NOT NULL,
  `role` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `prols`.`emp_profile`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`emp_profile` ;

CREATE TABLE IF NOT EXISTS `prols`.`emp_profile` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `emp_acc_acc_id` INT NOT NULL,
  `fname` VARCHAR(45) NOT NULL,
  `lname` VARCHAR(45) NOT NULL,
  `mname` VARCHAR(45) NOT NULL,
  `bday` DATETIME NOT NULL,
  `address` VARCHAR(45) NOT NULL,
  `gender` CHAR(10) NOT NULL,
  `img_path` VARCHAR(45) NOT NULL,
  `date_joined` DATETIME NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_emp_profile_emp_acc`
    FOREIGN KEY (`emp_acc_acc_id`)
    REFERENCES `prols`.`emp_acc` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `fk_emp_profile_emp_acc_idx` ON `prols`.`emp_profile` (`emp_acc_acc_id` ASC);

-- -----------------------------------------------------
-- Table `prols`.`list_dept`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`list_dept` ;

CREATE TABLE IF NOT EXISTS `prols`.`list_dept` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `dept_names` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `prols`.`list_pos`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`list_pos` ;

CREATE TABLE IF NOT EXISTS `prols`.`list_pos` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `pos_names` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `prols`.`emp_work`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`emp_work` ;

CREATE TABLE IF NOT EXISTS `prols`.`emp_work` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `status` VARCHAR(45) NOT NULL,
  `list_dept_dept_id` INT NOT NULL,
  `list_pos_pos_id` INT NOT NULL,
  `emp_acc_acc_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_emp_work_list_dept1`
    FOREIGN KEY (`list_dept_dept_id`)
    REFERENCES `prols`.`list_dept` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_emp_work_list_pos1`
    FOREIGN KEY (`list_pos_pos_id`)
    REFERENCES `prols`.`list_pos` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_emp_work_emp_acc1`
    FOREIGN KEY (`emp_acc_acc_id`)
    REFERENCES `prols`.`emp_acc` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `fk_emp_work_list_dept1_idx` ON `prols`.`emp_work` (`list_dept_dept_id` ASC);

CREATE INDEX `fk_emp_work_list_pos1_idx` ON `prols`.`emp_work` (`list_pos_pos_id` ASC);

CREATE INDEX `fk_emp_work_emp_acc1_idx` ON `prols`.`emp_work` (`emp_acc_acc_id` ASC);

-- -----------------------------------------------------
-- Table `prols`.`list_cont_types`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`list_cont_types` ;

CREATE TABLE IF NOT EXISTS `prols`.`list_cont_types` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `contact_type` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `prols`.`emp_contact`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`emp_contact` ;

CREATE TABLE IF NOT EXISTS `prols`.`emp_contact` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `contact` VARCHAR(45) NOT NULL,
  `emp_profile_id` INT NOT NULL,
  `list_cont_types_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_emp_contact_emp_profile1`
    FOREIGN KEY (`emp_profile_id`)
    REFERENCES `prols`.`emp_profile` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_emp_contact_list_cont_types1`
    FOREIGN KEY (`list_cont_types_id`)
    REFERENCES `prols`.`list_cont_types` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `fk_emp_contact_emp_profile1_idx` ON `prols`.`emp_contact` (`emp_profile_id` ASC);

CREATE INDEX `fk_emp_contact_list_cont_types1_idx` ON `prols`.`emp_contact` (`list_cont_types_id` ASC);

-- -----------------------------------------------------
-- Table `prols`.`list_leave_type`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`list_leave_type` ;

CREATE TABLE IF NOT EXISTS `prols`.`list_leave_type` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `leave_type` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `prols`.`emp_leave`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`emp_leave` ;

CREATE TABLE IF NOT EXISTS `prols`.`emp_leave` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `request` VARCHAR(100) NOT NULL,
  `status` VARCHAR(45) NOT NULL,
  `date_started` DATETIME NOT NULL,
  `date_ended` DATETIME NOT NULL,
  `emp_acc_id` INT NOT NULL,
  `list_leave_type_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_emp_leave_emp_acc1`
    FOREIGN KEY (`emp_acc_id`)
    REFERENCES `prols`.`emp_acc` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_emp_leave_list_leave_type1`
    FOREIGN KEY (`list_leave_type_id`)
    REFERENCES `prols`.`list_leave_type` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `fk_emp_leave_emp_acc1_idx` ON `prols`.`emp_leave` (`emp_acc_id` ASC);

CREATE INDEX `fk_emp_leave_list_leave_type1_idx` ON `prols`.`emp_leave` (`list_leave_type_id` ASC);

-- -----------------------------------------------------
-- Table `prols`.`emp_time`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`emp_time` ;

CREATE TABLE IF NOT EXISTS `prols`.`emp_time` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `time_in` DATETIME NOT NULL,
  `time_out` DATETIME NOT NULL,
  `ip_add` VARCHAR(45) NOT NULL,
  `date` DATETIME NOT NULL,
  `emp_acc_acc_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_emp_time_emp_acc1`
    FOREIGN KEY (`emp_acc_acc_id`)
    REFERENCES `prols`.`emp_acc` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `fk_emp_time_emp_acc1_idx` ON `prols`.`emp_time` (`emp_acc_acc_id` ASC);

-- -----------------------------------------------------
-- Table `prols`.`emp_approval`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`emp_approval` ;

CREATE TABLE IF NOT EXISTS `prols`.`emp_approval` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `request` VARCHAR(45) NOT NULL,
  `status` VARCHAR(45) NOT NULL,
  `date` DATETIME NOT NULL,
  `ip_add` VARCHAR(45) NOT NULL,
  `emp_time_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_emp_approval_emp_time1`
    FOREIGN KEY (`emp_time_id`)
    REFERENCES `prols`.`emp_time` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `fk_emp_approval_emp_time1_idx` ON `prols`.`emp_approval` (`emp_time_id` ASC);

-- -----------------------------------------------------
-- Table `prols`.`list_holidays`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`list_holidays` ;

CREATE TABLE IF NOT EXISTS `prols`.`list_holidays` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `date` DATETIME NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  `type` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `prols`.`list_ip`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `prols`.`list_ip` ;

CREATE TABLE IF NOT EXISTS `prols`.`list_ip` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `allowed_ip` VARCHAR(45) NOT NULL,
  `status` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.Styling;

#nullable enable

namespace Avalonia.Controls
{
    public class MaskedTextBox : TextBox, IStyleable
    {
        public static readonly StyledProperty<bool> AsciiOnlyProperty =
             AvaloniaProperty.Register<MaskedTextBox, bool>(nameof(AsciiOnly));

        public static readonly DirectProperty<MaskedTextBox, CultureInfo?> CultureProperty =
             AvaloniaProperty.RegisterDirect<MaskedTextBox, CultureInfo?>(nameof(Culture), o => o.Culture,
                (o, v) => o.Culture = v, CultureInfo.CurrentCulture);

        public static readonly StyledProperty<bool> HidePromptOnLeaveProperty =
             AvaloniaProperty.Register<MaskedTextBox, bool>(nameof(HidePromptOnLeave));

        public static readonly DirectProperty<MaskedTextBox, bool?> MaskCompletedProperty =
             AvaloniaProperty.RegisterDirect<MaskedTextBox, bool?>(nameof(MaskCompleted), o => o.MaskCompleted);

        public static readonly DirectProperty<MaskedTextBox, bool?> MaskFullProperty =
             AvaloniaProperty.RegisterDirect<MaskedTextBox, bool?>(nameof(MaskFull), o => o.MaskFull);

        public static readonly StyledProperty<string?> MaskProperty =
             AvaloniaProperty.Register<MaskedTextBox, string?>(nameof(Mask), string.Empty);

        public static new readonly StyledProperty<char> PasswordCharProperty =
             AvaloniaProperty.Register<TextBox, char>(nameof(PasswordChar), '\0');

        public static readonly StyledProperty<char> PromptCharProperty =
             AvaloniaProperty.Register<MaskedTextBox, char>(nameof(PromptChar), '_');

        public static readonly DirectProperty<MaskedTextBox, bool> ResetOnPromptProperty =
             AvaloniaProperty.RegisterDirect<MaskedTextBox, bool>(nameof(ResetOnPrompt), o => o.ResetOnPrompt, (o, v) => o.ResetOnPrompt = v);

        public static readonly DirectProperty<MaskedTextBox, bool> ResetOnSpaceProperty =
             AvaloniaProperty.RegisterDirect<MaskedTextBox, bool>(nameof(ResetOnSpace), o => o.ResetOnSpace, (o, v) => o.ResetOnSpace = v);

        private CultureInfo? _culture;

        private bool _resetOnPrompt = true;

        private bool _ignoreTextChanges;

        private bool _resetOnSpace = true;

        public MaskedTextBox() { }

        /// <summary>
        ///  Constructs the MaskedTextBox with the specified MaskedTextProvider object.
        /// </summary>
        public MaskedTextBox(MaskedTextProvider maskedTextProvider)
        {
            if (maskedTextProvider == null)
            {
                throw new ArgumentNullException(nameof(maskedTextProvider));
            }
            AsciiOnly = maskedTextProvider.AsciiOnly;
            Culture = maskedTextProvider.Culture;
            Mask = maskedTextProvider.Mask;
            PasswordChar = maskedTextProvider.PasswordChar;
            PromptChar = maskedTextProvider.PromptChar;
        }

        /// <summary>
        /// Gets or sets a value indicating if the masked text box is restricted to accept only ASCII characters.
        /// Default value is false.
        /// </summary>
        public bool AsciiOnly
        {
            get => GetValue(AsciiOnlyProperty);
            set => SetValue(AsciiOnlyProperty, value);
        }

        /// <summary>
        /// Gets or sets the culture information associated with the masked text box.
        /// </summary>
        public CultureInfo? Culture
        {
            get => _culture;
            set => SetAndRaise(CultureProperty, ref _culture, value);
        }

        /// <summary>
        /// Gets or sets a value indicating if the prompt character is hidden when the masked text box loses focus.
        /// </summary>
        public bool HidePromptOnLeave
        {
            get => GetValue(HidePromptOnLeaveProperty);
            set => SetValue(HidePromptOnLeaveProperty, value);
        }

        /// <summary>
        /// Gets or sets the mask to apply to the TextBox.
        /// </summary>
        public string? Mask
        {
            get => GetValue(MaskProperty);
            set => SetValue(MaskProperty, value);
        }

        /// <summary>
        ///  Specifies whether the test string required input positions, as specified by the mask, have
        ///  all been assigned.
        /// </summary>
        public bool? MaskCompleted
        {
            get => MaskProvider?.MaskCompleted;
        }

        /// <summary>
        ///  Specifies whether all inputs (required and optional) have been provided into the mask successfully.
        /// </summary>
        public bool? MaskFull
        {
            get => MaskProvider?.MaskFull;
        }

        /// <summary>
        /// Gets the MaskTextProvider for the specified Mask.
        /// </summary>
        public MaskedTextProvider? MaskProvider { get; private set; }

        /// <summary>
        /// Gets or sets the character to be displayed in substitute for user input.
        /// </summary>
        public new char PasswordChar
        {
            get => GetValue(PasswordCharProperty);
            set => SetValue(PasswordCharProperty, value);
        }

        /// <summary>
        /// Gets or sets the character used to represent the absence of user input in MaskedTextBox.
        /// </summary>
        public char PromptChar
        {
            get => GetValue(PromptCharProperty);
            set => SetValue(PromptCharProperty, value);
        }

        /// <summary>
        /// Gets or sets a value indicating if selected characters should be reset when the prompt character is pressed.
        /// </summary>
        public bool ResetOnPrompt
        {
            get => _resetOnPrompt;
            set
            {
                SetAndRaise(ResetOnPromptProperty, ref _resetOnPrompt, value);
                if (MaskProvider != null)
                {
                    MaskProvider.ResetOnPrompt = value;
                }

            }
        }

        /// <summary>
        /// Gets or sets a value indicating if selected characters should be reset when the space character is pressed.
        /// </summary>
        public bool ResetOnSpace
        {
            get => _resetOnSpace;
            set
            {
                SetAndRaise(ResetOnSpaceProperty, ref _resetOnSpace, value);
                if (MaskProvider != null)
                {
                    MaskProvider.ResetOnSpace = value;
                }

            }

        }

        Type IStyleable.StyleKey => typeof(TextBox);

        protected override void OnGotFocus(GotFocusEventArgs e)
        {
            if (HidePromptOnLeave == true && MaskProvider != null)
            {
                Text = MaskProvider.ToDisplayString();
            }
            base.OnGotFocus(e);
        }

        protected override async void OnKeyDown(KeyEventArgs e)
        {
            if (MaskProvider == null)
            {
                base.OnKeyDown(e);
                return;
            }

            var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();

            bool Match(List<KeyGesture> gestures) => gestures.Any(g => g.Matches(e));

            if (Match(keymap.Paste))
            {
                var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync();

                if (text == null)
                    return;

                foreach (var item in text)
                {
                    var index = GetNextCharacterPosition(CaretIndex);
                    if (MaskProvider.InsertAt(item, index))
                    {
                        CaretIndex = ++index;
                    }
                }

                Text = MaskProvider.ToDisplayString();
                e.Handled = true;
                return;
            }

            if (e.Key != Key.Back)
            {
                base.OnKeyDown(e);
            }

            switch (e.Key)
            {
                case Key.Delete:
                    if (CaretIndex < Text.Length)
                    {
                        if (MaskProvider.RemoveAt(CaretIndex))
                        {
                            RefreshText(MaskProvider, CaretIndex);
                        }

                        e.Handled = true;
                    }
                    break;
                case Key.Space:
                    if (!MaskProvider.ResetOnSpace || string.IsNullOrEmpty(SelectedText))
                    {
                        if (MaskProvider.InsertAt(" ", CaretIndex))
                        {
                            RefreshText(MaskProvider, CaretIndex);
                        }
                    }

                    e.Handled = true;
                    break;
                case Key.Back:
                    if (CaretIndex > 0)
                    {
                        MaskProvider.RemoveAt(CaretIndex - 1);
                    }
                    RefreshText(MaskProvider, CaretIndex - 1);
                    e.Handled = true;
                    break;
            }
        }

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            if (HidePromptOnLeave == true && MaskProvider != null)
            {
                Text = MaskProvider.ToString(!HidePromptOnLeave, true);
            }
            base.OnLostFocus(e);
        }

        protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
        {
            void UpdateMaskProvider()
            {
                MaskProvider = new MaskedTextProvider(Mask, Culture, true, PromptChar, PasswordChar, AsciiOnly) { ResetOnSpace = ResetOnSpace, ResetOnPrompt = ResetOnPrompt };
                if (Text != null)
                {
                    MaskProvider.Set(Text);
                }
                RefreshText(MaskProvider, 0);
            }
            if (change.Property == TextProperty && MaskProvider != null && _ignoreTextChanges == false)
            {
                if (string.IsNullOrEmpty(Text))
                {
                    MaskProvider.Clear();
                    RefreshText(MaskProvider, CaretIndex);
                    base.OnPropertyChanged(change);
                    return;
                }

                MaskProvider.Set(Text);
                RefreshText(MaskProvider, CaretIndex);
            }
            else if (change.Property == MaskProperty)
            {
                UpdateMaskProvider();

                if (!string.IsNullOrEmpty(Mask))
                {
                    foreach (var c in Mask!)
                    {
                        if (!MaskedTextProvider.IsValidMaskChar(c))
                        {
                            throw new ArgumentException("Specified mask contains characters that are not valid.");
                        }
                    }
                }
            }
            else if (change.Property == PasswordCharProperty)
            {
                if (!MaskedTextProvider.IsValidPasswordChar(PasswordChar))
                {
                    throw new ArgumentException("Specified character value is not allowed for this property.", nameof(PasswordChar));
                }
                if (MaskProvider != null && PasswordChar == MaskProvider.PromptChar)
                {
                    // Prompt and password chars must be different.
                    throw new InvalidOperationException("PasswordChar and PromptChar values cannot be the same.");
                }
                if (MaskProvider != null && MaskProvider.PasswordChar != PasswordChar)
                {
                    UpdateMaskProvider();
                }
            }
            else if (change.Property == PromptCharProperty)
            {
                if (!MaskedTextProvider.IsValidInputChar(PromptChar))
                {
                    throw new ArgumentException("Specified character value is not allowed for this property.");
                }
                if (PromptChar == PasswordChar)
                {
                    throw new InvalidOperationException("PasswordChar and PromptChar values cannot be the same.");
                }
                if (MaskProvider != null && MaskProvider.PromptChar != PromptChar)
                {
                    UpdateMaskProvider();
                }
            }
            else if (change.Property == AsciiOnlyProperty && MaskProvider != null && MaskProvider.AsciiOnly != AsciiOnly
                 || change.Property == CultureProperty && MaskProvider != null && !MaskProvider.Culture.Equals(Culture))
            {
                UpdateMaskProvider();
            }
            base.OnPropertyChanged(change);
        }
        protected override void OnTextInput(TextInputEventArgs e)
        {
            _ignoreTextChanges = true;
            try
            {
                if (IsReadOnly)
                {
                    e.Handled = true;
                    base.OnTextInput(e);
                    return;
                }
                if (MaskProvider == null)
                {
                    base.OnTextInput(e);
                    return;
                }
                if ((MaskProvider.ResetOnSpace && e.Text == " " || MaskProvider.ResetOnPrompt && e.Text == MaskProvider.PromptChar.ToString()) && !string.IsNullOrEmpty(SelectedText))
                {
                    if (SelectionStart > SelectionEnd ? MaskProvider.RemoveAt(SelectionEnd, SelectionStart - 1) : MaskProvider.RemoveAt(SelectionStart, SelectionEnd - 1))
                    {
                        SelectedText = string.Empty;
                    }
                }

                if (CaretIndex < Text.Length)
                {
                    CaretIndex = GetNextCharacterPosition(CaretIndex);

                    if (MaskProvider.InsertAt(e.Text, CaretIndex))
                    {
                        CaretIndex++;
                    }
                    var nextPos = GetNextCharacterPosition(CaretIndex);
                    if (nextPos != 0 && CaretIndex != Text.Length)
                    {
                        CaretIndex = nextPos;
                    }
                }

                RefreshText(MaskProvider, CaretIndex);

                e.Handled = true;

                base.OnTextInput(e);
            }
            finally
            {
                _ignoreTextChanges = false;
            }

        }

        private int GetNextCharacterPosition(int startPosition)
        {
            if (MaskProvider != null)
            {
                var position = MaskProvider.FindEditPositionFrom(startPosition, true);
                if (CaretIndex != -1)
                {
                    return position;
                }
            }
            return startPosition;
        }

        private void RefreshText(MaskedTextProvider provider, int position)
        {
            if (provider != null)
            {
                Text = provider.ToDisplayString();
                CaretIndex = position;
            }
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Ubigeo ;
use yii\web\JsExpression;
use yii\widgets\Pjax;

$this->title="Ideas en acción";
?>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.8.24/themes/base/jquery-ui.css">

    <img src="<?= \Yii::$app->request->BaseUrl ?>/img/icon_team_big.jpg" alt=""> Ideas en acción

    <?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data','class' => 'form_login']]); ?>

                         <input  type="file" id="registrar-foto" class="form-control  file" name="Registrar[foto]" onchange="Imagen(this)"/>
                         <?= Html::img('../foto_personal/'.$registrar->avatar.'',['id'=>'img_destino','class'=>'text-center', 'alt'=>'Responsive image','style'=>"height: 150px;width: 120px;align:center;cursor: pointer"]) ?>

                    Nombres*
                    <input style="padding-bottom: 0px;padding-top: 0px;height: 30px" type="text" onpaste="return false;" onCopy="return false" id="registrar-nombres" class="form-control texto" name="Registrar[nombres]" value="<?= $registrar->nombres ?>" required/>

                        Apellido paterno*
                        <input style="padding-bottom: 0px;padding-top: 0px;height: 30px;" type="text" onpaste="return false;" onCopy="return false" id="registrar-apellido_paterno" class="form-control texto" name="Registrar[apellido_paterno]" value="<?= $registrar->apellido_paterno ?>" required/>

                        Apellido materno*
                        <input style="padding-bottom: 0px;padding-top: 0px;height: 30px;" type="text" onpaste="return false;" onCopy="return false" id="registrar-apellido_materno" class="form-control texto" name="Registrar[apellido_materno]" value="<?= $registrar->apellido_materno ?>" required/>

                        Sexo*
                        <select style="padding-bottom: 0px;padding-top: 0px;height: 30px;" id="registrar-sexo" class="form-control" name="Registrar[sexo]" required/>
                            <option value=""></option>
                            <option value="F" <?= ($registrar->sexo=="F")?'selected':'';?> >Femenino</option>
                            <option value="M" <?= ($registrar->sexo=="M")?'selected':'';?> >Masculino</option>
                        </select>

                        Celular
                        <input style="padding-bottom: 0px;padding-top: 0px;height: 30px;" type="text" onpaste="return false;" onCopy="return false" id="registrar-celular" class="form-control numerico" name="Registrar[celular]" maxlength="9" value="<?= $registrar->celular ?>">

                        <input style="padding-bottom: 0px;padding-top: 0px;height: 30px;" type="text" id="registrar-fecha_nac" class="form-control"  name="Registrar[fecha_nac]" maxlength="10" placeholder="Fecha nacimiento*" value="<?= $registrar->fecha_nac ?>">

                        Región*
                        <select disabled style="padding-bottom: 0px;padding-top: 0px;height: 30px;" id="registrar-departamento" class="form-control" name="Registrar[departamento]" onchange='departamento($(this).val())'>
                        <option value=""></option>
                        <option value="<?= $ubigeo->department_id ?>" selected><?= $ubigeo->department ?></option>
                        </select>

                        Provincia*
                        <select disabled style="padding-bottom: 0px;padding-top: 0px;height: 30px;" id="registrar-provincia" class="form-control" name="Registrar[provincia]" onchange='provincia($(this).val())'>
                        <option value=""></option>
                        <option value="<?= $ubigeo->province_id ?>" selected ><?= $ubigeo->province ?></option>
                        </select>

                        Distrito*
                        <select disabled style="padding-bottom: 0px;padding-top: 0px;height: 30px;" id="registrar-distrito" class="form-control" name="Registrar[distrito]" onchange='distrito($(this).val())'>
                        <option value=""></option>
                        <option value="<?= $ubigeo->district_id ?>" selected ><?= $ubigeo->district ?></option>
                        </select>

                        Institución*
                        <select disabled style="padding-bottom: 0px;padding-top: 0px;height: 30px;" id="registrar-institucion" class="form-control" name="Registrar[institucion]">
                            <option value=""></option>
                            <option value="<?= $institucion->id ?>" selected ><?= $institucion->denominacion ?></option>

                        </select>

                        Grado de estudios*
                        <select disabled style="padding-bottom: 0px;padding-top: 0px;height: 30px;" id="registrar-grado" class="form-control" name="Registrar[grado]">
                            <option value=""></option>
                            <option value="1" <?= ($registrar->grado=="1")?'selected':'';?>>Primero</option>
                            <option value="2" <?= ($registrar->grado=="2")?'selected':'';?>>Segundo</option>
                            <option value="3" <?= ($registrar->grado=="3")?'selected':'';?>>Tercero</option>
                            <option value="4" <?= ($registrar->grado=="4")?'selected':'';?>>Cuarto</option>
                            <option value="5" <?= ($registrar->grado=="5")?'selected':'';?>>Quinto</option>
                            <option value="6" <?= ($registrar->grado=="6")?'selected':'';?>>Docente</option>
                        </select>

                <button type="submit" id="registrar"  class="btn  btn-default" >
                    Guardar
                </button>

                    Si deseas modificar tu correo, grado u otros datos envía un mensaje al correo electrónico ideasenaccion@minedu.gob.pe

    <?php ActiveForm::end(); ?>

<?php
    $validardni= Yii::$app->getUrlManager()->createUrl('registrar/validardni');
    $validaremail= Yii::$app->getUrlManager()->createUrl('registrar/validaremail');
    $provincias= Yii::$app->getUrlManager()->createUrl('ubigeo/provincias');
    $distritos= Yii::$app->getUrlManager()->createUrl('ubigeo/distritos');
    $instituciones= Yii::$app->getUrlManager()->createUrl('ubigeo/instituciones');
?>

<?php if (Yii::$app->session->hasFlash('emailexistente')): ?>

<?php endif; ?>
<?php if (Yii::$app->session->hasFlash('dniexistente')): ?>

<?php endif; ?>


text:
/**
 * Autogenerated by Thrift Compiler (0.17.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.accumulo.core.tabletserver.thrift;

public enum TCompactionKind implements org.apache.thrift.TEnum {
  CHOP(0),
  SELECTOR(1),
  SYSTEM(2),
  USER(3);

  private final int value;

  private TCompactionKind(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  @Override
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  @org.apache.thrift.annotation.Nullable
  public static TCompactionKind findByValue(int value) {
    switch (value) {
      case 0:
        return CHOP;
      case 1:
        return SELECTOR;
      case 2:
        return SYSTEM;
      case 3:
        return USER;
      default:
        return null;
    }
  }
}


text:
'use strict';

// Setting up route
angular.module('users').config(['$stateProvider',
  function ($stateProvider) {
    // Users state routing
    $stateProvider
      .state('users', {
        url: '/users',
        templateUrl: 'modules/users/client/views/admin/list-users.client.view.html',
        controller: 'UserListController'
      })
      .state('settings', {
        abstract: true,
        url: '/settings',
        templateUrl: 'modules/users/client/views/settings/settings.client.view.html',
        data: {
          roles: ['user', 'admin']
        }
      })
      .state('settings.profile', {
        url: '/profile',
        templateUrl: 'modules/users/client/views/settings/edit-profile.client.view.html'
      })
      .state('settings.password', {
        url: '/password',
        templateUrl: 'modules/users/client/views/settings/change-password.client.view.html'
      })
      .state('settings.picture', {
        url: '/picture',
        templateUrl: 'modules/users/client/views/settings/change-profile-picture.client.view.html'
      })
      .state('signup', {
        url: '/signup',
        templateUrl: 'modules/users/client/views/authentication/signup.client.view.html'
      })
      .state('signin', {
        url: '/signin?err',
        templateUrl: 'modules/users/client/views/authentication/signin.client.view.html'
      })
      .state('password', {
        abstract: true,
        url: '/password',
        template: '<ui-view/>'
      })
      .state('password.forgot', {
        url: '/forgot',
        templateUrl: 'modules/users/client/views/password/forgot-password.client.view.html'
      })
      .state('password.reset', {
        abstract: true,
        url: '/reset',
        template: '<ui-view/>'
      })
      .state('password.reset.invalid', {
        url: '/invalid',
        templateUrl: 'modules/users/client/views/password/reset-password-invalid.client.view.html'
      })
      .state('password.reset.success', {
        url: '/success',
        templateUrl: 'modules/users/client/views/password/reset-password-success.client.view.html'
      })
      .state('password.reset.form', {
        url: '/:token',
        templateUrl: 'modules/users/client/views/password/reset-password.client.view.html'
      })
      .state('profile', {
        abstract: true,
        url: '/profile',
        template: '<ui-view/>'
      })
      .state('profile.view', {
        url: '/:userId',
        templateUrl: 'modules/users/client/views/profile/user-profile.client.view.html',
        data: {
          roles: ['user', 'admin']
        }
      });
  }
]);


text:
/**
 * @provides phabricator-nav-view-css
 */

.jx-drag-col {
  cursor: col-resize;
}

.phabricator-nav {
  /* Force top margins in page content not to collapse with the top margin of
     the navigation container by giving it padding. Then put it in the right
     position by undoing the padding with a margin. */
  padding-top: 1px;
  margin-top: -1px;
}

.phabricator-nav-column-background {
  position: fixed;
  top: 0;
  left: 0;
  /* On the iPhone, scrolling down causes the revealed area to fill with white,
     then draw with the texture after the action completes. Just make the
     element extend off the bottom of the screen to prevent this. */
  bottom: -480px;
  width: 205px;
  background: #33383b;
  box-shadow: inset -3px 0 4px rgba(0, 0, 0, 0.05);
  background-image: url(/rsrc/image/menu_texture.png);
}

.phabricator-nav-column-background,
.phabricator-nav-local,
.phabricator-nav-drag {
  display: none;
}

.device-desktop .has-local-nav .phabricator-nav-column-background,
.device-desktop .has-local-nav .phabricator-nav-local,
.device-desktop .has-local-nav .phabricator-nav-drag {
  display: block;
}

.device .phabricator-side-menu-home .phabricator-nav-column-background,
.device .phabricator-side-menu-home .phabricator-nav-local {
  display: block;
}

.phabricator-nav-local {
  width: 205px;
  position: absolute;
  left: 0;
  white-space: nowrap;

  overflow-x: hidden;
  overflow-y: auto;
}

.phabricator-nav-drag {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 205px;
  width: 7px;

  cursor: col-resize;
  background: #f5f5f5;
  border-style: solid;
  border-width: 0 1px 0 1px;
  border-color: #fff #999c9e #fff #999c9e;

  box-shadow: inset -1px 0px 1px rgba(0, 0, 0, 0.15);

  background-image: url(/rsrc/image/divot.png);
  background-position: center;
  background-repeat: no-repeat;
}

.device-desktop .phabricator-standard-page-body .has-drag-nav .phabricator-nav-content {
  margin-left: 212px;
}

.device-desktop .has-local-nav .phabricator-nav-content {
  margin-left: 205px;
}

.phabricator-side-menu-home .phabricator-nav-column-background,
.phabricator-side-menu-home .phabricator-nav-local {
  width: 240px;
}

.device-desktop .phabricator-side-menu-home .phabricator-nav-content,
.device-tablet .phabricator-side-menu-home .phabricator-nav-content {
  margin-left: 240px;
}

.device-phone .phabricator-side-menu-home .phabricator-nav-content {
  display: none;
}

.device-phone .phabricator-side-menu-home .phabricator-nav-column-background,
.device-phone .phabricator-side-menu-home .phabricator-nav-local {
  width: 100%;
}


text:
package org.apache.servicecomb.foundation.vertx;

import javax.ws.rs.core.Response.Status;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import io.vertx.core.MultiMap;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;

public class TestSimpleBodyHandler {

  private SimpleBodyHandler instance;

  private RoutingContext context;

  @Before
  public void setUp() throws Exception {
    context = Mockito.mock(RoutingContext.class);
    HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
    Mockito.when(context.request()).thenReturn(request);
    MultiMap multiMap = Mockito.mock(MultiMap.class);
    Mockito.when(request.headers()).thenReturn(multiMap);
    HttpServerResponse response = Mockito.mock(HttpServerResponse.class);
    Mockito.when(response.setStatusCode(Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode())).thenReturn(response);
    Mockito.when(context.response()).thenReturn(response);
  }

  @After
  public void tearDown() throws Exception {
    instance = null;
    context = null;
  }

  @Test
  public void testValidContentType() {
    instance = new SimpleBodyHandler() {
      @Override
      protected boolean contentTypeSupported(String contentType) {
        return true;
      }
    };
    instance.handle(context);
    Assert.assertTrue(instance.checkContentType(context));
  }

  @Test
  public void testInvalidContentType() {
    instance = new SimpleBodyHandler() {
      @Override
      protected boolean contentTypeSupported(String contentType) {
        return false;
      }
    };
    instance.handle(context);
    Assert.assertFalse(instance.checkContentType(context));
  }
}


text:
package com.amazonaws.services.shield.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.shield.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ContributorMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ContributorMarshaller {

    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Name").build();
    private static final MarshallingInfo<Long> VALUE_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Value").build();

    private static final ContributorMarshaller instance = new ContributorMarshaller();

    public static ContributorMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Contributor contributor, ProtocolMarshaller protocolMarshaller) {

        if (contributor == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(contributor.getName(), NAME_BINDING);
            protocolMarshaller.marshall(contributor.getValue(), VALUE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
import React from 'react';
import Layout from '../../components/Layout';
import Link from '../../components/Link'
import s from './styles.css';

class AboutPage extends React.Component {
  render() {
    return (
      <Layout className={s.content}>

Test Page

          The content of the page goes here.
          Here is a <Link to="/">link to the home page</Link>

      </Layout>
    );
  }

}

export default AboutPage;


text:
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class CoinbaseExample {

    static String API_KEY = "FSDgDrPrhUous5p4";

    static String API_SECRET = "NfGzjzNy6zfCpeLG41pR0pbmN9AuoxQA";

    public static String getHttp(String url, String body)
            throws InvalidKeyException, NoSuchAlgorithmException,
            ClientProtocolException, IOException {

        String nonce = String.valueOf(System.currentTimeMillis());
        String message = nonce + url + (body != null ? body : "");

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(API_SECRET.getBytes(), "HmacSHA256"));
        String signature = new String(Hex.encodeHex(mac.doFinal(message.getBytes())));

        HttpRequestBase request;
        if (body == null || body.length() == 0)
            request = new HttpGet(url);
        else {
            HttpPost post = new HttpPost(url);
            post.setEntity(new StringEntity(body));
            request = post;
        }
        request.setHeader("ACCESS_KEY", API_KEY);
        request.setHeader("ACCESS_SIGNATURE", signature);
        request.setHeader("ACCESS_NONCE", nonce);

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response = httpClient.execute(request);

        HttpEntity entity = response.getEntity();
        if (entity != null)
            return EntityUtils.toString(entity);
        return null;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(getHttp("https://api.coinbase.com/v1/account/balance", null));
    }
}


text:
package com.spike.jena.util;

import org.apache.commons.lang3.StringUtils;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.tdb.TDBFactory;

/**
 * RDF data set utilities
 *
 * @author zhoujiagen<br/>
 *         Jul 5, 2015 5:52:54 PM
 */
public class DatasetUtils {

	/**
	 * get default model of dataset
	 *
	 * @param dataset
	 * @return
	 */
	public static final Model getDefaultModel(Dataset dataset) {
		if (dataset == null) {
			return null;
		}

		return dataset.getDefaultModel();
	}

	/**
	 * get default model from dataset specified by a assembler file
	 *
	 * @param assembleFilePath
	 * @return
	 */
	public static final Model getDefaultModelFromAssembler(String assembleFilePath) {
		if (StringUtils.isBlank(assembleFilePath)) {
			return null;
		}

		// create dataset using assembler file
		Dataset dataset = TDBFactory.assembleDataset(assembleFilePath);
		if (dataset == null) {
			return null;
		}

		return getDefaultModel(dataset);
	}

	/**
	 * get default model from dataset specified by directory path
	 *
	 * @param directory
	 * @return
	 */
	public static final Model getDefaultModelFromDirectory(String directory) {
		if (StringUtils.isBlank(directory)) {
			return null;
		}

		// create dataset using directory path
		Dataset dataset = TDBFactory.createDataset(directory);
		if (dataset == null) {
			return null;
		}

		return getDefaultModel(dataset);
	}

}


text:
'use strict';

/**
 * Additional parameters for listByResourceGroup operation.
 *
 */
class ClustersListByResourceGroupOptions {
  /**
   * Create a ClustersListByResourceGroupOptions.
   * @member {string} [filter] An OData $filter clause.. Used to filter results
   * that are returned in the GET respnose.
   * @member {string} [select] An OData $select clause. Used to select the
   * properties to be returned in the GET respnose.
   * @member {number} [maxResults] The maximum number of items to return in the
   * response. A maximum of 1000 files can be returned. Default value: 1000 .
   */
  constructor() {
  }

  /**
   * Defines the metadata of ClustersListByResourceGroupOptions
   *
   * @returns {object} metadata of ClustersListByResourceGroupOptions
   *
   */
  mapper() {
    return {
      required: false,
      type: {
        name: 'Composite',
        className: 'ClustersListByResourceGroupOptions',
        modelProperties: {
          filter: {
            required: false,
            type: {
              name: 'String'
            }
          },
          select: {
            required: false,
            type: {
              name: 'String'
            }
          },
          maxResults: {
            required: false,
            defaultValue: 1000,
            type: {
              name: 'Number'
            }
          }
        }
      }
    };
  }
}

module.exports = ClustersListByResourceGroupOptions;


text:
package execpath

// Look searches for an executable named file, using getenv to look up
// environment variables. If getenv is nil, os.Getenv will be used. If file
// contains a slash, it is tried directly and getenv will not be called.  The
// result may be an absolute path or a path relative to the current directory.
func Look(file string, getenv func(string) string) (string, error) {
	// Wasm can not execute processes, so act as if there are no executables at all.
	return "", &Error{file, ErrNotFound}
}


text:
const Data = function(magoInstance) {

    const _ui = function() {
        const ON_CLASS_NAME = 'actived';
        const cssName = {
            menuClass : {
                'tab' : '.data-menu'
            },
            targetClass : {
                'tab' : '.data-contents'
            },
            getMenuClassName : function(type) {
                return this.menuClass[type];
            },
            getTargetClassName : function(type) {
                return this.targetClass[type];
            }
        };
        const hide = (type) => {
            $(cssName.getTargetClassName(type)).hide();
            $(cssName.getMenuClassName(type)).removeClass(ON_CLASS_NAME);
        }
        const addOnClassTarget = ($target) => {$target.addClass(ON_CLASS_NAME)};
        const toggleContents = ($menu) => {

            if(!$menu.hasClass(ON_CLASS_NAME)) {
                const convertId = $obj => {
                    const id = $obj.get(0).id;
                    return '#' + id.replace('tab', 'content');
                }

                if ('#address-content' === convertId($menu)) {
                    alert('서비스 준비중 입니다.');
                    return false;
                }

                hide('tab');
                addOnClassTarget($menu);
                $(convertId($menu)).toggle();
            }
        }
        const clickTab = (event) => {
            toggleContents($(event.delegateTarget));
            return false;
        }
        //탭메뉴 클릭
        $('.data-menu').click(clickTab);
    }

    const _run = function () {

        const datas = {
            'layer-tab': new Data2D(magoInstance),
            'data-tab': new Data3D(magoInstance)
        }

        const _init = function(targetId) {
            let data = datas[targetId];
            if (data && data.load === false) {
                data.load = true;
            }
        }

        const dataObserverTarget = document.getElementById('data-menu');
        const dataObserverConfig = {attributes: true, attributeFilter: ['class']};
        const dataMenuObserver = new MutationObserver(function (mutations) {
            for (const mutation of mutations) {
                const isVisible = mutation.target.classList.contains('actived');
                if (isVisible) {
                    _init(mutation.target.id);
                }
            }
        });
        const dataTabObserver = new MutationObserver(function (mutations) {
            for (const mutation of mutations) {
                const isVisible = mutation.target.classList.contains('on');
                if (isVisible) {
                    const targetId = $('#data-wrap-content').find('.data-menu.actived').attr('id');
                    _init(targetId);
                    for (const targetId in datas) {
                        dataMenuObserver.observe(document.getElementById(targetId), dataObserverConfig);
                    }
                } else {
                    dataMenuObserver.disconnect();
                }
            }
        });
        dataTabObserver.observe(dataObserverTarget, dataObserverConfig);

    }

    // 버튼 클릭같은거
    _ui();

    // 프로그램 실행
    _run();

}


text:
@interface MingSDK_MGMT_Safe : NSObject

void hook_func_attachRegisterSuccessFlag(Class cls);

@end


text:
template<template<typename number> class ParticleType, typename number>
class MCIntegrator
{
public:
    MCIntegrator();

    number ExcludedIntegrator(number);

    InteractionFactory<ParticleType<number>, number> IManager;

    ArrayX<number> Q_grid;
    ArrayX<number> Eta_grid;

    void MCInit(int, int, int);
    void VirialIntegrator(ArrayXX<number>*, ArrayXX<number>*, ArrayX<number>*, ArrayX<number>*);
    void LegendreIntegrator(ArrayXX<number>*, number);
    void FrankIntegrator(const ArrayXX<number>&,
                         ArrayX<number>*, ArrayX<number>*, ArrayX<number>*, ArrayX<number>*);

private:
    ParticleType<number> Particle1_;
    ParticleType<number> Particle2_;

    ullint N_PER_PROC_;

    ullint ctr_mc_;
    ullint ctr_ov_;

    number mayer_interaction_;

    double t_start_;
    double t_end_;
    double t_elapsed_;

    Vector3<number> R_cm_;

    ArrayX<number> X_grid_;
    ArrayX<number> Y_grid_;
    ArrayX<number> Z_grid_;

    ArrayX<uint> Exc_grid_;

    ArrayX<uint> Bootstrap_map1_;
    ArrayX<uint> Bootstrap_map2_;

    std::mt19937_64 rng_engine_;
    std::uniform_real_distribution<number> rng_distrib_{0., 1.};

    void MCReset();
    void SyncCheck(bool);
    void PruneGrid(number);
    void ConfigGenerator();
};

#endif


text:
#include "tensorflow/core/common_runtime/colocation_graph.h"

#include <memory>
#include <set>
#include <utility>
#include <vector>

#include "absl/strings/str_join.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_set.h"
#include "tensorflow/core/framework/attr_value_util.h"
#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/util/device_name_utils.h"
#include "tensorflow/core/util/dump_graph.h"
#include "tensorflow/core/util/port.h"

namespace tensorflow {

namespace {

// We hoist the conversion from C-style string literal to StringPiece here,
// so that we can avoid the many repeated calls to strlen().
const StringPiece kColocationAttrNameStringPiece(kColocationAttrName);
const StringPiece kColocationGroupPrefixStringPiece(kColocationGroupPrefix);

// Returns a list of devices having type in supported_device_types.  The
// returned list is sorted by preferred type (higher numeric type is preferred).
std::vector<Device*> FilterSupportedDevices(
    const std::vector<Device*>& devices,
    const PrioritizedDeviceTypeVector& supported_device_types,
    const Device* default_device) {
  Device* filtered_default_device = nullptr;
  std::vector<std::pair<Device*, int32>> prioritized_filtered_devices;
  for (const auto& supported_device_type : supported_device_types) {
    for (Device* device : devices) {
      if (DeviceType(device->attributes().device_type()) ==
          supported_device_type.first) {
        if (device == default_device) {
          filtered_default_device = device;
        } else {
          prioritized_filtered_devices.emplace_back(
              device, supported_device_type.second);
        }
      }
    }
  }

  auto device_sort = [](const std::pair<Device*, int32>& a,
                        const std::pair<Device*, int32>& b) {
    if (a.second != b.second) {
      return a.second > b.second;
    }

    auto a_priority =
        DeviceSet::DeviceTypeOrder(DeviceType(a.first->device_type()));
    auto b_priority =
        DeviceSet::DeviceTypeOrder(DeviceType(b.first->device_type()));
    // First sort by prioritized device type (higher is preferred) and
    // then by device name (lexicographically).
    if (a_priority != b_priority) {
      return a_priority > b_priority;
    }
    return StringPiece(a.first->name()) < StringPiece(b.first->name());
  };
  std::sort(prioritized_filtered_devices.begin(),
            prioritized_filtered_devices.end(), device_sort);

  std::vector<Device*> filtered_devices;
  if (filtered_default_device != nullptr) {
    filtered_devices.emplace_back(filtered_default_device);
  }
  for (const auto& prioritized_filtered_device : prioritized_filtered_devices) {
    filtered_devices.push_back(prioritized_filtered_device.first);
  }
  return filtered_devices;
}

// Using absl::StrJoin with lambda does not work in tf-lite builds.
std::vector<string> DevicesToString(const std::vector<Device*> devices) {
  std::vector<string> v;
  v.reserve(devices.size());
  for (Device* d : devices) {
    v.push_back(d->name());
  }
  return v;
}

// Using absl::StrJoin with lambda does not work in tf-lite builds.
std::vector<string> DeviceTypeAndPriorityToString(
    const PrioritizedDeviceTypeVector& devices) {
  std::vector<string> v;
  v.reserve(devices.size());
  for (const std::pair<DeviceType, int32>& device_and_type : devices) {
    v.push_back(DeviceTypeString(device_and_type.first));
  }
  return v;
}

// While Placer can override requested device on ops processing
// resources, i.e. node that take (and potentially return) a resource,
// it must not override requested device on ops generating a resource,
// e.g. VarHandleOp, _Arg. Such ops are currently no-input, single resource/ref
// output nodes.
bool IsResourceGeneratorNode(const Node& node) {
  return node.num_inputs() == 0 && node.num_outputs() == 1 &&
         (IsRefType(node.output_type(0)) || node.output_type(0) == DT_RESOURCE);
}

bool IsExemptFromResourceInputColocation(const Node* node) {
  // Note: Partitioned function calls, which place and partition their
  // function bodies, are exempt from this check: they forward resource and
  // ref inputs to operations that are appropriately placed, instead of
  // dereferencing them.
  const string& op_type = node->op_def().name();
  return op_type == "PartitionedCall" || op_type == "StatefulPartitionedCall";
}

bool HasPriorities(const PrioritizedDeviceTypeVector& device_types) {
  for (const auto& prioritized_device_type : device_types) {
    if (prioritized_device_type.second != 0) return true;
  }
  return false;
}

bool ArePrioritiesSame(const PrioritizedDeviceTypeVector& a_types,
                       const PrioritizedDeviceTypeVector& b_types) {
  if (a_types.size() != b_types.size()) {
    return false;
  }
  for (int i = 0; i < a_types.size(); ++i) {
    if (a_types[i].first != b_types[i].first) {
      return false;
    }
  }
  return true;
}

}  // namespace

Status Member::SetParentAndSupportedDevices(
    const Node& node, const std::vector<DeviceType>& types) {
  int id = node.id();
  if (id < 0) {
    return errors::Internal("Placer should not be creating a Member for node: ",
                            node.DebugString());
  }
  parent_ = id;
  return SupportedDeviceTypesForNode(types, node.def(),
                                     &supported_device_types_);
}

Status Member::SetAssignedDeviceName(const string& device_name) {
  if (DeviceNameUtils::HasSomeDetails(requested_device_name_)) {
    return errors::Internal(
        "Setting assigned device name when there is a requested device set "
        "is unsupported");
  }
  if (!DeviceNameUtils::ParseFullName(device_name, &assigned_device_name_)) {
    return errors::Internal("Malformed assigned device '", device_name, "'");
  }
  // Set requested device to assigned_device to maintain the invariant that
  // requested is a specialization of assigned.
  requested_device_name_ = assigned_device_name_;
  return Status::OK();
}

Status Member::SetRequestedDeviceName(const Node& node) {
  if (!DeviceNameUtils::ParseFullName(node.requested_device(),
                                      &requested_device_name_)) {
    return errors::InvalidArgument("Malformed device specification '",
                                   node.requested_device(),
                                   "' in node: ", node.DebugString());
  }
  if (DeviceNameUtils::HasSomeDetails(assigned_device_name_)) {
    return errors::Internal(
        "Setting requested device name when there is an assigned device set "
        "is unsupported");
  }
  return Status::OK();
}

Status Member::EnsureCompatibilityAcrossResourceEdge(
    const Node& src, const Member& src_root,
    const Node& dst, /*dst_root is this*/
    bool log_device_placement) {
  if (!DeviceNameUtils::AreCompatibleDevNames(src_root.assigned_device_name_,
                                              assigned_device_name_)) {
    return errors::InvalidArgument(
        "Cannot place the graph because a reference or resource edge "
        "connects colocation groups with incompatible assigned devices: ",
        DeviceNameUtils::ParsedNameToString(src_root.assigned_device_name_),
        " vs ", DeviceNameUtils::ParsedNameToString(assigned_device_name_));
  }

  if (DeviceNameUtils::AreCompatibleDevNames(src_root.requested_device_name_,
                                             requested_device_name_)) {
    return Status::OK();
  }

  // If we are here, assigned devices are compatible but requested ones are
  // not. We will be overriding the requested device for destination node, but
  // need to preserve the invariant that it will be a specialization of
  // the assigned device.
  if (log_device_placement) {
    LOG(INFO) << "Ignoring device specification "
              << DeviceNameUtils::ParsedNameToString(requested_device_name_)
              << " for node '" << dst.name()
              << "' because the input edge from '" << src.name()
              << "' is a reference connection and already has a device "
                 "field set to "
              << DeviceNameUtils::ParsedNameToString(
                     src_root.requested_device_name_);
  }
  requested_device_name_ = src_root.requested_device_name_;
  DeviceNameUtils::EnsureSpecification(&requested_device_name_,
                                       assigned_device_name_);
  return Status::OK();
}

void Member::Merge(std::vector<Member>* tree, int x_root, int y_root,
                   Member** new_root, Member** old_root, bool dry_run) {
  Member& x_root_member = (*tree)[x_root];
  Member& y_root_member = (*tree)[y_root];

  // Merge the sets by setting the parent pointer of the smaller tree's root
  // node to point to the root of the larger tree. Together with path
  // compression in ColocationGraph::FindRoot, this ensures that we do not
  // experience pathological performance on graphs such as chains.
  int new_root_id, old_root_id;
  if (x_root_member.rank_ < y_root_member.rank_) {
    // The tree rooted at x_root is shallower, so connect it to
    // y_root. The rank of y_root is unchanged because its new
    // child has strictly less rank.
    if (!dry_run) {
      x_root_member.parent_ = y_root;
    }
    new_root_id = y_root;
    old_root_id = x_root;
  } else if (x_root_member.rank_ > y_root_member.rank_) {
    // The tree rooted at y_root is shallower, so connect it to
    // x_root. The rank of x_root is unchanged because its new
    // child has strictly less rank.
    if (!dry_run) {
      y_root_member.parent_ = x_root;
    }
    new_root_id = x_root;
    old_root_id = y_root;
  } else {
    if (!dry_run) {
      // Both trees have the same rank, so break the tie by choosing
      // x_root as the new root.
      y_root_member.parent_ = x_root;
      // Increment the rank of the tree rooted at x_root, because it
      // is now strictly deeper than before.
      ++x_root_member.rank_;
    }
    new_root_id = x_root;
    old_root_id = y_root;
  }

  *new_root = &(*tree)[new_root_id];
  *old_root = &(*tree)[old_root_id];
}

// tree is non-const because we can change some `parent` pointers in some
// members for more efficient future lookups. The vector itself is not
// changed.
int Member::FindRoot(std::vector<Member>* tree, int node_id) {
  Member& member = (*tree)[node_id];
  if (member.parent_ == node_id) {
    // member.parent is the root of this disjoint tree.  Do nothing.
  } else {
    member.parent_ = FindRoot(tree, member.parent_);
  }
  // Now it is guaranteed that member.parent is the root of this disjoint
  // tree.
  return member.parent_;
}

Status Member::MergeDeviceNames(const Member& other,
                                bool allow_soft_placement) {
  // Assuming the "requested is a specialization of assigned" invariant holds
  // for this and `other`, it will hold after the two merges below.
  DeviceNameUtils::ParsedName assigned_device_name_copy = assigned_device_name_;
  TF_RETURN_IF_ERROR(DeviceNameUtils::MergeDevNames(
      &assigned_device_name_copy, other.assigned_device_name_));

  DeviceNameUtils::ParsedName requested_device_name_copy =
      requested_device_name_;
  TF_RETURN_IF_ERROR(DeviceNameUtils::MergeDevNames(
      &requested_device_name_copy, other.requested_device_name_,
      allow_soft_placement));

  // We checked for all errors, now change the devices.
  assigned_device_name_ = assigned_device_name_copy;
  requested_device_name_ = requested_device_name_copy;
  return Status::OK();
}

// Updates this to contain the intersection of the device types in
// this and "other".
bool Member::MergeSupportedDevices(const Member& other) {
  // Generate intersection with priorities.
  // Each vector contains the same device types but with different priorities.
  // The priorities are taken from the corresponding source vector.
  PrioritizedDeviceTypeVector target_intersection;
  PrioritizedDeviceTypeVector other_intersection;
  for (const auto& prioritized_device_type : supported_device_types_) {
    bool found = false;
    for (const auto& other_prioritized_device_type :
         other.supported_device_types_) {
      if (prioritized_device_type.first ==
          other_prioritized_device_type.first) {
        found = true;
        other_intersection.push_back(other_prioritized_device_type);
        break;
      }
    }
    if (found) {
      target_intersection.push_back(prioritized_device_type);
    }
  }

  // Sort the devices by priority order.
  auto device_sort = [](const std::pair<DeviceType, int32>& a,
                        const std::pair<DeviceType, int32>& b) {
    // First look at set priorities.
    if (a.second != b.second) {
      return a.second > b.second;
    }
    // Then fallback to default priorities.
    auto a_priority = DeviceSet::DeviceTypeOrder(a.first);
    auto b_priority = DeviceSet::DeviceTypeOrder(b.first);
    if (a_priority != b_priority) {
      return a_priority > b_priority;
    }
    // Finally just look at the Device type strings.
    return a.first.type_string() < b.first.type_string();
  };

  std::sort(target_intersection.begin(), target_intersection.end(),
            device_sort);
  std::sort(other_intersection.begin(), other_intersection.end(), device_sort);

  PrioritizedDeviceTypeVector result;

  bool is_target_prioritized = HasPriorities(target_intersection);
  bool is_other_prioritized = HasPriorities(other_intersection);
  if (!is_target_prioritized && !is_other_prioritized) {
    // If neither are prioritized then we just return the original i.e. target
    // prioritization.
    result = target_intersection;
  } else if (is_target_prioritized && !is_other_prioritized) {
    // If only one is prioritized, then we respect priorities of that in the
    // intersection.
    result = target_intersection;
  } else if (!is_target_prioritized && is_other_prioritized) {
    result = other_intersection;
  } else {
    // If both have priorities and agree then we go with that. If the
    // prioritization order is different, then we just fallback to the default
    // i.e. what the DeviceTypeOrder suggests. In that case, we also set the
    // merged priorities to 0, so that downstream merges work correctly as well.
    if (ArePrioritiesSame(target_intersection, other_intersection)) {
      result = target_intersection;
    } else {
      for (const auto& prioritized_device : target_intersection) {
        result.push_back(std::make_pair(prioritized_device.first, 0));
      }
      std::sort(result.begin(), result.end(), device_sort);
    }
  }

  if (result.empty()) {
    return false;
  }
  supported_device_types_ = result;
  return true;
}

Status Member::AssignDevice(const Node& node, bool allow_soft_placement) {
  if (node.assigned_device_name_index() == assigned_device_name_index_) {
    return Status::OK();
  }

  DeviceNameUtils::ParsedName parsed;
  DeviceNameUtils::ParseFullName(node.assigned_device_name(), &parsed);
  Status s = DeviceNameUtils::MergeDevNames(&assigned_device_name_, parsed,
                                            allow_soft_placement);
  if (!s.ok()) {
    return errors::Internal(
        "Constraining by assigned device should not cause an error. Original "
        "root's assigned device name: ",
        DeviceNameUtils::ParsedNameToString(assigned_device_name_),
        " node's assigned device name \"", node.assigned_device_name(),
        ". Error: ", s.error_message());
  }
  s = DeviceNameUtils::MergeDevNames(&requested_device_name_, parsed,
                                     allow_soft_placement);
  if (!s.ok()) {
    return errors::Internal(
        "Constraining by assigned device should not cause an error. Original "
        "root's requested device name: \"",
        DeviceNameUtils::ParsedNameToString(requested_device_name_),
        "\", node's assigned device name \"", node.assigned_device_name(),
        "\". Error: ", s.error_message());
  }

  assigned_device_name_index_ = node.assigned_device_name_index();
  // Clear cached possible_devices, if any.
  possible_devices_.clear();
  return Status::OK();
}
string Member::DebugString() {
  return absl::StrCat(
      "Member(assigned_device_name_index_=", assigned_device_name_index_,
      " requested_device_name_=",
      DeviceNameUtils::ParsedNameToString(requested_device_name_),
      " assigned_device_name_=",
      DeviceNameUtils::ParsedNameToString(assigned_device_name_),
      " supported_device_types_=[",
      absl::StrJoin(DeviceTypeAndPriorityToString(supported_device_types_),
                    ", "),
      "] possible_devices_=[",
      absl::StrJoin(DevicesToString(possible_devices_), ", "), "]");
}
ColocationGraph::ColocationGraph(const Graph* graph,
                                 const DeviceSet* device_set,
                                 const Device* default_device,
                                 bool allow_soft_placement,
                                 bool log_device_placement)
    : graph_(graph),
      device_set_(device_set),
      device_types_(device_set->PrioritizedDeviceTypeList()),
      default_device_(default_device),
      allow_soft_placement_(allow_soft_placement),
      log_device_placement_(log_device_placement) {
  members_.resize(graph->num_node_ids());
}

// Adds each node of the Graph to this ColocationGraph as a singleton.
//
// NOTE: The implementation assumes that the ids of nodes passed to
// this method are dense and zero-based; the memory used will be linear in
// the largest node ID.
// NOTE: If this method returns an error, *this is left in an undefined
// state.
Status ColocationGraph::ColocateAllNodes() {
  // This maps from a colocation group identifier to the 'root' of that
  // colocation group.  Note that the keys in this map are StringPiece; the
  // actual strings are stored under the NodeDef.  The lifetime of this map
  // is limited to this ColocateAllNodes() method, and no part of the
  // NodeDef trees are changed during the lifetime of this method, so using
  // StringPiece as a key is safe.
  //
  // Also, as a further optimization, we remove the "loc:@" prefix from
  // "class" attribute values, when they are used as keys in this table.
  // This allows us to use StringPiece values that refer to substrings of
  // 'string' values stored in NodeDef attribute lists, as well as StringPiece
  // values that refer to 'string' values from NodeDef::name(), without
  // performing any string allocations.
  std::unordered_map<StringPiece, const Node*, StringPieceHasher>
      colocation_group_root;

  for (const Node* node : graph_->op_nodes()) {
    // When adding the node, identify whether it is part of a colocation
    // group.

    // This code is effectively the equivalent of GetNodeAttr() for a string
    // array, but it avoids all internal allocations (the allocation of the
    // backing store of the std::vector<string> as well as the copies of the
    // strings within it).  Instead, we combine the query of the colocation
    // attribute with the calls to ColocateNodeToGroup.
    bool found_spec = false;
    const AttrValue* attr_value =
        node->attrs().Find(kColocationAttrNameStringPiece);
    if (attr_value != nullptr && attr_value->has_list()) {
      for (const string& class_spec : attr_value->list().s()) {
        StringPiece spec(class_spec);
        if (str_util::ConsumePrefix(&spec, kColocationGroupPrefixStringPiece)) {
          found_spec = true;
          TF_RETURN_IF_ERROR(
              ColocateNodeToGroup(&colocation_group_root, node, spec));
        }
      }
    }

    // TODO(iga): Even when the node has a spec, we need to colocate the
    // node to its "name group" because other nodes can still use
    // "loc:@<this_node_name>" in their colocation specs.
    if (!found_spec) {
      // If the node does not specify a colocation group, then use the
      // name of this node as the colocation group.
      TF_RETURN_IF_ERROR(
          ColocateNodeToGroup(&colocation_group_root, node, node->name()));
    }
  }

  return Status::OK();
}

Status ColocationGraph::ColocateResourceOrRefEdge(Node* src, Node* dst) {
  // Colocate `src` and `dst` to maintain the invariant that nodes
  // connected by reference edges are colocated.
  int src_root_id = FindRoot(src->id());
  int dst_root_id = FindRoot(dst->id());
  auto& src_root = members_[src_root_id];
  auto& dst_root = members_[dst_root_id];

  TF_RETURN_IF_ERROR(dst_root.EnsureCompatibilityAcrossResourceEdge(
      *src, src_root, *dst, log_device_placement_));
  Status status = ColocateNodes(*src, src_root_id, *dst, dst_root_id);
  if (!status.ok()) {
    return AttachDef(
        errors::InvalidArgument("Nodes were connected by a "
                                "reference connection (requiring them to "
                                "be on the same device), but the two nodes "
                                "were assigned two different devices: ",
                                status.error_message()),
        *dst);
  }
  return Status::OK();
}

Status ColocationGraph::ColocateResourceAndRefEdges() {
  // Enumerate the constraint edges, and use them to update the disjoint
  // node set.
  // If `node` has an input edge with reference type, add an edge from the
  // source of that edge to `node`.
  for (const Edge* edge : graph_->edges()) {
    if (edge->IsControlEdge()) {
      continue;
    }
    Node* src = edge->src();
    Node* dst = edge->dst();
    DataType input_type = dst->input_type(edge->dst_input());
    if ((input_type == DT_RESOURCE || IsRefType(input_type)) &&
        !IsExemptFromResourceInputColocation(dst)) {
      TF_RETURN_IF_ERROR(ColocateResourceOrRefEdge(src, dst));
    }
  }
  return Status::OK();
}

Status ColocationGraph::Initialize() {
  TF_RETURN_IF_ERROR(InitializeMembers());
  TF_RETURN_IF_ERROR(ColocateResourceAndRefEdges());
  TF_RETURN_IF_ERROR(ColocateAllNodes());
  return Status::OK();
}

Status ColocationGraph::ColocateNodeToGroup(
    std::unordered_map<StringPiece, const Node*, StringPieceHasher>*
        colocation_group_root,
    const Node* node, StringPiece colocation_group) {
  const Node*& root_node = (*colocation_group_root)[colocation_group];
  if (root_node == nullptr) {
    // This is the first node of the colocation group, so
    // designate this node as the 'root' of that colocation group.
    root_node = node;
  } else {
    // Try to colocate the node with the root.  If there is an
    // error, return it.
    Status s = ColocateNodes(*node, *root_node);
    if (!s.ok()) {
      if (!allow_soft_placement_) {
        return AttachDef(s, *node);
      }
      if (log_device_placement_) {
        LOG(INFO) << "Ignoring request to colocate node '" << node->name()
                  << "' with nodes in colocation group '" << colocation_group
                  << "' because soft placement is on and an attempt at doing "
                     "so resulted in the following error: "
                  << AttachDef(s, *node).ToString();
      }
    }
  }
  return Status::OK();
}

// Merge the (possibly disjoint) sets containing nodes "x" and
// "y". Returns OK if the all nodes in the union of these sets can
// be placed on the same device type.
//
// NOTE: If this method returns an error, *this is left in an undefined
// state.
Status ColocationGraph::ColocateNodes(const Node& x, const Node& y) {
  int x_root = FindRoot(x.id());
  int y_root = FindRoot(y.id());
  return ColocateNodes(x, x_root, y, y_root);
}

// This overload of ColocateNodes() allows a caller to provide the root node
// ids for the two nodes. For large graphs, this noticeably reduces the
// graph load time.
Status ColocationGraph::ColocateNodes(const Node& x, int x_root, const Node& y,
                                      int y_root) {
  if (x_root == y_root) {
    return Status::OK();
  }

  Member* new_root_member;
  Member* old_root_member;
  Member::Merge(&members_, x_root, y_root, &new_root_member, &old_root_member,
                /*dry_run=*/true);

  // Merge the partial device specifications, and ensure that they are
  // compatible. NULL options_ is treated as allowing soft placement.
  // If there is an error, nothing is modified.
  // TODO(mrry): Consider enriching the error message by pointing
  // out which nodes have the explicit partial device
  // specifications that caused this conflict.
  Status s = new_root_member->MergeDeviceNames(*old_root_member,
                                               allow_soft_placement_);
  if (!s.ok()) {
    return errors::InvalidArgument(
        "Cannot colocate nodes ",
        errors::FormatColocationNodeForError(x.name()), " and ",
        errors::FormatColocationNodeForError(y.name()), ": ",
        s.error_message());
  }

  // Ensure that the common root has at least one supported device
  // type, by computing the intersection of
  // new_root_member.supported_device_types and
  // old_root_member.supported_device_types.
  if (!new_root_member->MergeSupportedDevices(*old_root_member)) {
    return errors::InvalidArgument(
        "Cannot colocate nodes ",
        errors::FormatColocationNodeForError(x.name()), " and ",
        errors::FormatColocationNodeForError(y.name()),
        " because no device type supports both of those nodes and the "
        "other nodes colocated with them.",
        DebugInfo(x_root), DebugInfo(y_root));
  }

  // All error checks are done, merge the colocation graphs.
  Member::Merge(&members_, x_root, y_root, &new_root_member, &old_root_member,
                /*dry_run=*/false);
  return Status::OK();
}

// Limits the possible devices of `node`'s colocation group to the device
// to which `node` is assigned. This makes sure that all nodes in this
// colocation group will be assigned to the same device. Without this
// explicit restriction, heuristics can choose a different possible device
// for other nodes in the group.
Status ColocationGraph::LimitToAssignedDevice(const Node& node) {
  if (node.assigned_device_name_index() < 0) {
    return errors::Internal(
        "Expected an assigned node as argument to LimitToAssignedDevice but "
        "got: ",
        node.DebugString());
  }
  int root = FindRoot(node.id());
  Member& root_member = members_[root];
  return root_member.AssignDevice(node, allow_soft_placement_);
}

// For the given node, subject to the constraints previously given
// to this ColocationGraph, set its assigned_device_name. Returns OK
// if a satisfying device can be found, otherwise an error.
//
// Note: This method returns a pointer to a field within members_.
// The caller must not use the returned pointer after there is any possibility
// that the members_[i].possible_devices field has been modified.
Status ColocationGraph::GetDevicesForNode(
    Node* node, const std::vector<Device*>** possible_devices) {
  *possible_devices = nullptr;
  const int node_root = FindRoot(node->id());
  if (!members_[node_root].possible_devices().empty()) {
    *possible_devices = &members_[node_root].possible_devices();
    return Status::OK();
  }

  // We have not yet computed the possible devices for the
  // colocated node set containing 'node', so we do so now using the
  // constraints on the root node.

  // "devices" will contain the set of feasible placements for the
  // colocated node set containing 'node'.
  std::vector<Device*> devices;
  if (DeviceNameUtils::HasSomeDetails(
          members_[node_root].requested_device_name())) {
    // The root node has a (possibly partial) device
    // specification, so enumerate the physical devices that
    // conform to it.
    device_set_->FindMatchingDevices(
        members_[node_root].requested_device_name(), &devices);

    if (!devices.empty()) {
      // Filter devices into those that are compatible with the root
      // node (and its children).
      devices = FilterSupportedDevices(
          devices, members_[node_root].supported_device_types(),
          default_device_);
    }

    // Perform soft placement if allow_soft_placement_ is set.
    if (devices.empty() && allow_soft_placement_) {
      // The soft_device_name is the same as the node's device name
      // without specifying the device type or ID.
      DeviceNameUtils::ParsedName soft_device_name =
          members_[node_root].requested_device_name();
      soft_device_name.type.clear();
      soft_device_name.has_type = false;
      soft_device_name.has_id = false;
      device_set_->FindMatchingDevices(soft_device_name, &devices);
      if (!devices.empty()) {
        devices = FilterSupportedDevices(
            devices, members_[node_root].supported_device_types(),
            default_device_);
      }
    }

    if (devices.empty()) {
      // Return an error when a physical device that matches an explicit
      // device specification is not found. This ensures that we don't
      // assign a node to GPU when the user wanted to force it on CPU.
      string debug_info = DebugInfo(node_root);

      DeviceNameUtils::ParsedName specified_device_name;
      if (DeviceNameUtils::ParseFullName(node->requested_device(),
                                         &specified_device_name) &&
          specified_device_name ==
              members_[node_root].requested_device_name()) {
        // The specified device and merged set device match, and
        // will appear in the GraphDef (for debugging), so just
        // print the specified device.
        std::vector<Device*> devices_matching_nodedef;
        device_set_->FindMatchingDevices(specified_device_name,
                                         &devices_matching_nodedef);
        if (devices_matching_nodedef.empty()) {
          // Sometimes it is almost impossible to understand the problem
          // without a list of available devices.
          std::vector<string> device_names;
          for (const Device* device : device_set_->devices()) {
            device_names.push_back(device->name());
          }
          std::sort(device_names.begin(), device_names.end());

          string gpu_msg = "";
          if (!IsGoogleCudaEnabled() &&
              str_util::Lowercase(specified_device_name.type) == "gpu") {
            gpu_msg =
                " The requested device appears to be a GPU, but CUDA is not "
                "enabled.";
          }

          return errors::InvalidArgument(
              errors::FormatNodeNameForError(node->name()),
              "was explicitly assigned to ", node->requested_device(),
              " but available devices are [ ",
              str_util::Join(device_names, ", "), " ]. Make sure ",
              "the device specification refers to a valid device.", gpu_msg);
        } else if (specified_device_name.has_type) {
          return errors::InvalidArgument(
              "Could not satisfy explicit device specification '",
              node->requested_device(), "' because no supported kernel for ",
              specified_device_name.type, " devices is available.", debug_info,
              "\nRegistered kernels:\n",
              KernelsRegisteredForOp(node->type_string()));
        } else {
          return errors::InvalidArgument(
              "Could not satisfy explicit device specification '",
              node->requested_device(), debug_info);
        }
      } else {
        // The specified device may be a valid device but the
        // merged set device is different, so print both.
        return errors::InvalidArgument(
            "Could not satisfy explicit device specification '",
            node->requested_device(), "' because the node ",
            errors::FormatColocationNodeForError(node->name()),
            " was colocated with a group of nodes that ",
            "required incompatible device '",
            DeviceNameUtils::ParsedNameToString(
                members_[node_root].requested_device_name()),
            "'", debug_info);
      }
    }
  } else {
    // The device is completely unspecified, so enumerate the devices that
    // support all of the nodes in the set.
    if (device_set_->devices().empty()) {
      return errors::Internal("No devices are registered");
    }
    devices = FilterSupportedDevices(
        device_set_->devices(), members_[node_root].supported_device_types(),
        default_device_);

    if (devices.empty()) {
      return errors::InvalidArgument(
          "Node had no OpKernel registered to support this operation: ",
          "Operation was ", node->type_string(), " and inputs were ",
          DataTypeVectorString(node->input_types()), DebugInfo(node_root));
    }
  }

  // Cache the result of the possible devices for this node group.
  members_[node_root].set_possible_devices(std::move(devices));
  *possible_devices = &members_[node_root].possible_devices();
  return Status::OK();
}

Status ColocationGraph::InitializeMembers() {
  for (Node* node : graph_->op_nodes()) {
    Status status = InitializeMember(*node, &members_[node->id()]);
    if (!status.ok()) {
      return AttachDef(status, *node);
    }
  }
  return Status::OK();
}

string ColocationGraph::DebugString() {
  std::unordered_set<int> roots;
  std::vector<string> root_strings;
  for (const Node* node : graph_->nodes()) {
    if (!node->IsOp()) {
      continue;
    }
    int node_root = FindRoot(node->id());
    if (roots.count(node_root) == 0) {
      root_strings.push_back(DebugInfo(node_root));
      roots.insert(node_root);
    }
  }
  return absl::StrJoin(root_strings, "\n");
}

// Returns debugging info for the node referred to by 'node_root'.
string ColocationGraph::DebugInfo(const int node_root) {
  string text(
      "\nColocation Debug Info:\n"
      "Colocation group had the following types and devices: ");

  // If this node is part of a colocation group, then we want to
  // collect the mapping of ops to supported devices, so that
  // the user can see why an unsatisfiable placement occurred.

  std::unordered_map<string, string> type_to_devices;
  std::vector<const Node*> colocation_nodes;
  int num_nodes_found = 0;

  for (const Node* node : graph_->nodes()) {
    if (!node->IsOp()) {
      continue;
    }
    int id = node->id();
    if (FindRoot(id) != node_root) {
      continue;
    }
    ++num_nodes_found;
    colocation_nodes.push_back(node);
    const string& op_type = node->type_string();
    string devices_registered;
    for (const auto& device_type : members_[id].supported_device_types()) {
      strings::StrAppend(&devices_registered,
                         DeviceTypeString(device_type.first), " ");
    }

    type_to_devices[op_type] = std::move(devices_registered);
  }

  for (const auto& td : type_to_devices) {
    strings::StrAppend(&text, "\n", td.first, ": ", td.second);
  }
  strings::StrAppend(&text,
                     "\n\nColocation members and user-requested devices:");
  for (const Node* node : colocation_nodes) {
    strings::StrAppend(&text, "\n  ", node->name(), " (", node->type_string(),
                       ") ", node->requested_device());
  }
  strings::StrAppend(&text, "\n");

  if (num_nodes_found <= 0) {
    text.clear();
  }
  return text;
}

Status ColocationGraph::InitializeMemberWithAssignedDevice(
    const string& assigned_device_name, const string& node_type,
    bool must_be_full_name, Member* member) {
  // This node has already been assigned to a device, so we
  // respect this placement, after sanity-checking it.
  // NOTE: Since any assignment must have been performed by
  // the TensorFlow runtime, we consider errors in this branch to
  // be INTERNAL.
  TF_RETURN_IF_ERROR(member->SetAssignedDeviceName(assigned_device_name));
  if (!must_be_full_name) {
    return Status::OK();
  }
  // Since assigned device must be a full specification, do extra checks.
  const Device* assigned_device =
      device_set_->FindDeviceByName(assigned_device_name);
  if (assigned_device == nullptr) {
    return errors::Internal("Assigned device '", assigned_device_name,
                            "' does not match any device");
  }

  for (const auto& d : member->supported_device_types()) {
    if (DeviceType(assigned_device->attributes().device_type()) == d.first) {
      return Status::OK();
    }
  }

  return errors::Internal("Assigned device '", assigned_device_name,
                          "' does not have registered OpKernel support "
                          "for ",
                          node_type);
}

Status ColocationGraph::InitializeMember(const Node& node, Member* member) {
  TF_RETURN_IF_ERROR(member->SetParentAndSupportedDevices(node, device_types_));

  if (node.has_assigned_device_name()) {
    TF_RETURN_IF_ERROR(InitializeMemberWithAssignedDevice(
        node.assigned_device_name(), node.type_string(), true, member));
  } else {
    // This node has not yet been assigned to a device, so we
    // calculate any constraints due to the set of registered
    // kernels and any (partial) user-provided device specification
    // in the NodeDef.

    // If no kernels are registered for this op type, fail with an error.
    if (member->supported_device_types().empty()) {
      std::set<string> registered_device_types;
      for (Device* d : device_set_->devices()) {
        registered_device_types.insert(d->device_type());
      }
      std::vector<string> attr_key_vals;
      for (const auto& it : node.attrs()) {
        const string& name = it.first;
        const AttrValue& attr_value = it.second;
        attr_key_vals.push_back(
            strings::StrCat(name, "=", SummarizeAttrValue(attr_value)));
      }
      return errors::InvalidArgument(
          "No OpKernel was registered to support Op '", node.type_string(),
          "' used by ", errors::FormatNodeNameForError(node.name()),
          "with these attrs: [", str_util::Join(attr_key_vals, ", "),
          "]\n"
          "Registered devices: [",
          str_util::Join(registered_device_types, ", "), "]\n",
          "Registered kernels:\n", KernelsRegisteredForOp(node.type_string()));
    }

    // If the NodeDef contains a device, then we interpret it as a
    // (partial) device specification.
    if (!node.requested_device().empty()) {
      if (IsResourceGeneratorNode(node)) {
        // Treat requested device on resource generating nodes as assigned
        // device so that we don't override it.
        TF_RETURN_IF_ERROR(InitializeMemberWithAssignedDevice(
            node.requested_device(), node.type_string(), false, member));
      } else {
        // The user has specified a device in the NodeDef, try to find a
        // valid device matching their specification in the set of
        // devices.
        // NOTE: The full name may specify a device that is not in
        // n.supported_device_types(), but we check that in AssignDevice().
        TF_RETURN_IF_ERROR(member->SetRequestedDeviceName(node));
      }
    }
  }
  return Status::OK();
}

}  // namespace tensorflow


text:
using System.Web.Mvc;
using MVCForum.Domain.Constants;
using MVCForum.Domain.Interfaces.Services;
using MVCForum.Domain.Interfaces.UnitOfWork;
using MVCForum.Website.ViewModels;

namespace MVCForum.Website.Controllers
{
    public class PointController : BaseController
    {
        private readonly IMembershipUserPointsService _membershipUserPointsService;

        public PointController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IMembershipService membershipService,
            ILocalizationService localizationService, IRoleService roleService, ISettingsService settingsService,
            IMembershipUserPointsService membershipUserPointsService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _membershipUserPointsService = membershipUserPointsService;
        }

        [ChildActionOnly]
        [OutputCache(Duration = AppConstants.DefaultCacheLengthInSeconds)]
        public PartialViewResult CurrentWeekHighPointUsers()
        {
            using (UnitOfWorkManager.NewUnitOfWork())
            {
                var highEarners = _membershipUserPointsService.GetCurrentWeeksPoints(20);
                var viewModel = new HighEarnersPointViewModel { HighEarners = highEarners };
                return PartialView(viewModel);
            }
        }
    }
}