text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>NoAutoRun</title>
<meta name="date" content="2012-07-02">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Required |

Optional

Detail:

Element

org.sureassert.uc.annotation

Annotation Type NoAutoRun

@Retention(value=RUNTIME)
@Target(value=TYPE)
public @interface NoAutoRun

Prevents Sureassert UC running any JUnit tests on the annotated class automatically.

Since:

1.0

Author:

Nathan Dolan

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Required |

Optional

Detail:

Element


text:
=head1 LICENSE

   Copyright 2013 EMBL - European Bioinformatics Institute

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

=cut

=pod

=head1 NAME

    BioSD::Database

=head1 SYNOPSIS

    # fetch a database from a valid Group object
    my ($database) = @{$group->databases()};

    # get some information about the database
    my $id = $database->id();
    my $uri = $database->uri();
    my $name = $database->name();

=head1 Description

    A BioSD::Database object represents an external database associated with a
    group in the BioSamples databases

=cut

package BioSD::Database;
use strict;
use warnings;

=head id

  Arg [1]    : none
  Example    : $id = $database->id()
  Description: Returns the external database id corresponding to the BioSamples
               group
  Returntype : string
  Exceptions : none

=cut

sub id {
  my ($self) = @_;
  return BioSD::XPathContext::findvalue('./SG:ID', $self->_xml_element);
}

=head uri

  Arg [1]    : none
  Example    : $uri = $database->uri()
  Description: Returns a uri for the external database corresponding to the
               BioSamples group
  Returntype : string or undefined
  Exceptions : none

=cut

sub uri {
  my ($self) = @_;
  return BioSD::XPathContext::findvalue('./SG:URI', $self->_xml_element);
}

=head name

  Arg [1]    : none
  Example    : $name = $database->name()
  Description: Returns a name for the external database entry corresponding to
               the BioSamples group
  Returntype : string
  Exceptions : none

=cut

sub name {
  my ($self) = @_;
  return BioSD::XPathContext::findvalue('./SG:Name', $self->_xml_element);
}

sub _new{
  my ($class, $xml_element) = @_;
  my $self = {};
  bless $self, $class;

  $self->_xml_element($xml_element);
  return $self;
}

sub _xml_element {
  my ($self, $xml_element) = @_;
  if ($xml_element) {
    $self->{_xml_element} = $xml_element;
  }
  return $self->{_xml_element};
}

1;

redpajama_set_name: RedPajamaGithub


text:
"""Data utils for cifar."""

import copy
import os
import pickle
import augmentation_transforms
import freq_helpers
import numpy as np
import policies as found_policies
import scipy.io as sio
from six.moves import cPickle
import tensorflow as tf
import tensorflow_datasets as tfds

def load_arr(prefix, filename):
  pathname = os.path.join(prefix, filename)
  assert os.path.exists(pathname)
  with open(pathname, 'r') as f:
    arr = np.loadtxt(f)
  return arr

def load_obj(prefix, filename):
  pathname = os.path.join(prefix, filename)
  assert os.path.exists(pathname)
  with open(pathname, 'rb') as f:
    return pickle.load(f)

def load_cifar(hparams):
  """Load the cifar10/cifar100 dataset according to hparams.

  Args:
    hparams: Dictionary of hyperparameters

  Returns:
    all_data: A tensor of type uint8 of shape [50000, 32, 32, 3] that contains
      all of the training and validation images.
    all_labels: A tensor containing the one hot labels of type int32 of
      shape [50000, num_classes].
    test_images: A tensor of type uint8 of shape [10000, 32, 32, 3] that
      contains all of the test images if `eval_test` is set to 1 else it will
      be an empty matrix.
    test_labels: A tensor containing the one hot labels of type int32 of
      shape [10000, num_classes] if `eval_test` is set to 1 else it will
      be an empty matrix.
    extra_test_images: CIFAR10.1 images, normalized using CIFAR10 stats (or
      None, if `extra_dataset` is not 'cifar10_1').
    extra_test_labels: CIFAR10.1 one-hot labels (or None, if `extra_dataset` is
      not 'cifar10_1').
  """
  all_labels = []

  total_batches_to_load = 5
  assert hparams.train_size + hparams.validation_size <= 50000
  if hparams.eval_test:
    total_batches_to_load += 1
  # Determine how many images we have loaded
  total_dataset_size = 50000
  train_dataset_size = total_dataset_size
  if hparams.eval_test:
    total_dataset_size += 10000

  if hparams.dataset == 'cifar10':
    all_images = []
  elif hparams.dataset == 'cifar100':
    all_images = np.empty((1, 50000, 3072), dtype=np.uint8)
    if hparams.eval_test:
      test_data = np.empty((1, 10000, 3072), dtype=np.uint8)
  if hparams.dataset == 'cifar10':
    datafiles = [
        'data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4',
        'data_batch_5']

    if hparams.eval_test:
      datafiles.append('test_batch')
    num_classes = 10
  elif hparams.dataset == 'cifar100':
    datafiles = ['train']
    if hparams.eval_test:
      datafiles.append('test')
    num_classes = 100
  else:
    raise NotImplementedError('Unimplemented dataset: ', hparams.dataset)
  if hparams.dataset != 'test':
    for file_num, f in enumerate(datafiles):
      d = unpickle(os.path.join(hparams.data_path, f))
      if hparams.dataset == 'cifar10':
        labels = np.array(d['labels'])
      else:
        labels = np.array(d['fine_labels'])
      if f == 'test':
        test_data[0] = copy.deepcopy(d['data'])
        if hparams.dataset == 'cifar10':
          all_images.append(test_data)
        else:
          all_images = np.concatenate([all_images, test_data], axis=1)
      else:
        if hparams.dataset == 'cifar10':
          all_images.append(copy.deepcopy(d['data']))
        else:
          all_images[file_num] = copy.deepcopy(d['data'])
      nsamples = len(labels)
      for idx in range(nsamples):
        all_labels.append(labels[idx])
  if hparams.dataset == 'cifar10':
    all_images = np.concatenate(all_images, axis=0)
  all_images = all_images.reshape(-1, 3072)
  all_images = all_images.reshape(-1, 3, 32, 32)  # pylint: disable=too-many-function-args
  all_images = all_images.transpose(0, 2, 3, 1).copy()
  all_images = all_images / 255.0
  mean = augmentation_transforms.MEANS
  std = augmentation_transforms.STDS
  tf.logging.info('mean:{}    std: {}'.format(mean, std))
  all_images = (all_images - mean) / std
  all_labels = np.eye(num_classes)[np.array(all_labels, dtype=np.int32)]

  assert len(all_images) == len(all_labels)
  tf.logging.info(
      'In CIFAR10 loader, number of images: {}'.format(len(all_images)))

  extra_test_images = None
  extra_test_labels = None
  if hparams.extra_dataset == 'cifar10_1':
    extra_test_ds = tfds.as_numpy(
        tfds.load('cifar10_1', split='test', batch_size=-1))
    extra_test_images = ((extra_test_ds['image'] / 255.0) - mean) / std
    extra_test_labels = np.eye(num_classes)[np.array(
        extra_test_ds['label'], dtype=np.int32)]

  # Break off test data
  if hparams.eval_test:
    test_images = all_images[train_dataset_size:]
    test_labels = all_labels[train_dataset_size:]
  else:
    test_images = []
    test_labels = []
  all_images = all_images[:train_dataset_size]
  all_labels = all_labels[:train_dataset_size]
  return all_images, all_labels, test_images, test_labels, extra_test_images, extra_test_labels

def load_svhn(hparams):
  """Load the svhn dataset according to hparams.

  Args:
    hparams: Dictionary of hyperparameters

  Returns:
    all_data: A tensor of type uint8 of shape [50000, 32, 32, 3] that contains
      all of the training and validation images.
    all_labels: A tensor containing the one hot labels of type int32 of
      shape [50000, num_classes].
    test_images: A tensor of type uint8 of shape [10000, 32, 32, 3] that
      contains all of the test images if `eval_test` is set to 1 else it will
      be an empty matrix.
    test_labels: A tensor containing the one hot labels of type int32 of
      shape [10000, num_classes] if `eval_test` is set to 1 else it will
      be an empty matrix.
  """
  all_labels = []
  all_labels = []
  data_path = hparams.data_path
  train_data = unpickle(os.path.join(data_path, 'train_32x32.mat'),
                        use_sio=True)
  all_images = train_data['X']
  all_labels = train_data['y']

  all_labels = all_labels[:, 0]-1
  all_images = all_images.transpose(3, 0, 1, 2).copy()
  num_classes = 10

  all_labels = np.eye(num_classes)[np.array(all_labels, dtype=np.int32)]
  assert len(all_images) == len(all_labels)
  tf.logging.info(
      'In SVHN loader, number of images: {}'.format(len(all_images)))

  if hparams.eval_test:
    test_data = unpickle(os.path.join(data_path, 'test_32x32.mat'),
                         use_sio=True)
    test_images = test_data['X'].transpose(3, 0, 1, 2).copy()
    test_images = test_images[:26025]
    test_labels = test_data['y'][:, 0]-1
    test_labels = test_labels[:26025]
    test_labels = np.eye(num_classes)[np.array(test_labels, dtype=np.int32)]
  else:
    test_images = []
    test_labels = []
  # Normalize data
  mean = np.reshape([0.4376821, 0.4437697, 0.47280442], [1, 1, 1, 3])
  std = np.reshape([0.19803012, 0.20101562, 0.19703614], [1, 1, 1, 3])
  all_images = all_images / 255.0
  all_images = (all_images - mean) / std
  test_images = test_images / 255.0
  test_images = (test_images - mean) / std
  tf.compat.v1.logging.info('svhn: {} {} {} {}'.format(
      all_images, all_labels, test_images, test_labels))

  return all_images, all_labels, test_images, test_labels

class DataSet(object):
  """Dataset object that produces augmented training and eval data."""

  def __init__(self, hparams):
    self.hparams = hparams
    self.epochs = 0
    self.curr_train_index = 0

    if self.hparams.noise_type == 'fourier':
      i, j = freq_helpers.get_spatial_freqij(self.hparams.spatial_frequency)
      self.direction = freq_helpers.get_fourier_basis_image(i, j)
    elif self.hparams.noise_type == 'random':
      np.random.seed(hparams.noise_seed)
      self.direction = np.random.randn(32*32*3).reshape(32, 32, 3)
    elif self.hparams.noise_type == 'f' or self.hparams.noise_type == '1/f':
      self.direction = freq_helpers.get_fourier_composite_image(
          kind=self.hparams.noise_type)

    self.good_policies = found_policies.good_policies()

    (all_images, all_labels, test_images, test_labels, extra_test_images,
     extra_test_labels) = load_cifar(hparams)
    self.test_images, self.test_labels = test_images, test_labels
    self.extra_test_images, self.extra_test_labels = extra_test_images, extra_test_labels

    # Shuffle the data
    all_images = all_images[:]
    all_labels = all_labels[:]
    tf.logging.info('all_images size: {}'.format(all_images.shape))
    np.random.seed(0)
    perm = np.arange(len(all_images))
    np.random.shuffle(perm)
    all_images = all_images[perm]
    all_labels = all_labels[perm]

    # Break into train and val
    train_size, val_size = hparams.train_size, hparams.validation_size
    assert 50000 >= train_size + val_size
    self.train_images = all_images[:train_size]
    self.train_labels = all_labels[:train_size]
    self.val_images = all_images[train_size:train_size + val_size]
    self.val_labels = all_labels[train_size:train_size + val_size]
    self.num_train = self.train_images.shape[0]

  def next_batch(self):
    """Return the next minibatch of augmented data."""
    next_train_index = self.curr_train_index + self.hparams.batch_size
    if next_train_index > self.num_train:
      # Increase epoch number
      epoch = self.epochs + 1
      self.reset()
      self.epochs = epoch
    batched_data = (
        self.train_images[self.curr_train_index:self.curr_train_index +
                          self.hparams.batch_size],
        self.train_labels[self.curr_train_index:self.curr_train_index +
                          self.hparams.batch_size])
    final_imgs = []
    images, labels = batched_data
    if self.hparams.augment_type == 'mixup':
      images, labels = augmentation_transforms.mixup_batch(
          images, labels, self.hparams.mixup_alpha)
    elif self.hparams.augment_type == 'image_freq':
      images, labels = augmentation_transforms.freq_augment(
          images,
          labels,
          amplitude=self.hparams.freq_augment_amplitude,
          magnitude=self.hparams.augmentation_magnitude,
          proportion_f=self.hparams.freq_augment_ffrac,
          probability=self.hparams.augmentation_probability)
    for data in images:
      if self.hparams.augment_type == 'autoaugment':
        epoch_policy = self.good_policies[np.random.choice(
            len(self.good_policies))]
        final_img = augmentation_transforms.apply_policy(epoch_policy, data)
      elif self.hparams.augment_type == 'random':
        epoch_policy = found_policies.random_policy(
            self.hparams.num_augmentation_layers,
            self.hparams.augmentation_magnitude,
            self.hparams.augmentation_probability)
        final_img = augmentation_transforms.apply_policy(epoch_policy, data)
      else:
        final_img = np.copy(data)
      if self.hparams.apply_flip_crop:
        final_img = augmentation_transforms.random_flip(
            augmentation_transforms.zero_pad_and_crop(data, 4))
      # Apply cutout
      if self.hparams.apply_cutout:
        final_img = augmentation_transforms.cutout_numpy(final_img)

      final_imgs.append(final_img)
    final_imgs = np.array(final_imgs, np.float32)
    if self.hparams.noise_type == 'radial':
      labels = augmentation_transforms.add_radial_noise(
          final_imgs, labels, self.hparams.frequency, self.hparams.amplitude,
          self.hparams.noise_class, self.hparams.normalize_amplitude)
    elif self.hparams.noise_type == 'random' or self.hparams.noise_type == 'fourier' or self.hparams.noise_type == 'f' or self.hparams.noise_type == '1/f':
      labels = augmentation_transforms.add_sinusoidal_noise(
          final_imgs, labels, self.hparams.frequency, self.hparams.amplitude,
          self.direction, self.hparams.noise_class,
          self.hparams.normalize_amplitude)
    elif self.hparams.noise_type == 'uniform':
      labels = augmentation_transforms.add_uniform_noise(
          labels, self.hparams.amplitude, self.hparams.noise_class)

    batched_data = (final_imgs, labels)
    self.curr_train_index += self.hparams.batch_size
    return batched_data

  def reset(self):
    """Reset training data and index into the training data."""
    self.epochs = 0
    # Shuffle the training data
    perm = np.arange(self.num_train)
    np.random.shuffle(perm)
    assert self.num_train == self.train_images.shape[
        0], 'Error incorrect shuffling mask'
    self.train_images = self.train_images[perm]
    self.train_labels = self.train_labels[perm]
    self.curr_train_index = 0

def unpickle(f, use_sio=False):
  tf.logging.info('loading file: {}'.format(f))
  fo = tf.gfile.Open(f, 'rb')
  if use_sio:
    d = sio.loadmat(fo)
  else:
    d = cPickle.load(fo, encoding='latin1')
  fo.close()
  return d


text:
'use strict';

const express = require('express');
const routes = require('./server/routes/index.js');
const mongoose = require('mongoose');
const passport = require('passport');
const session = require('express-session');
const bodyParser = require('body-parser');

const app = express();
require('dotenv').load();
require('./server/config/passport')(passport);

mongoose.connect(process.env.MONGODB_URI);
mongoose.Promise = global.Promise;

app.use(bodyParser.json());
app.use('/controllers', express.static(process.cwd() + '/server/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/server/common'));

app.use(session({
  secret: 'Vote or Die!',
  resave: false,
  saveUninitialized: true,
  // cookie:  {secure: true},
}));

app.use(passport.initialize());
app.use(passport.session());
routes(app, passport);

const port = process.env.PORT || 8080;
app.listen(port, function() {
  console.log('Node.js listening on port ' + port + '...');
});

module.exports = {
  app,
};


text:
package com.lernerbrandon.starterdroid.util;

/**
 * Created by lernerb on 3/26/15.
 */
public class MathUtil {

    public static int addTen(int number)
    {
        return number + 10;
    }

    public static int subtractTen(int number)
    {
        return number - 10 ;
    }
}


text:
using RzDb.CodeGen;

public class Ef6ModelsGenerator : EdmxCodeGenBase
{
    public Ef6ModelsGenerator(string edmxPath, string outputPath) : base(edmxPath, @"Ef6Models\Ef6ModelsTemplate.cshtml", outputPath)
    {

    }
}


text:
title: "Sparky 2021.09 (semi-rolling) is out with the Debian Bookworm foundation"
layout: post
categories: sparky release
tags:
  - sparky
  - release
  - semi rolling distribution
  - debian bookworm foundation
image: /assets/images/post-images/sparky-2021.09.jpg
video: https://www.youtube.com/embed/SVcp8rGKsSQ
---

**The** Sparky Linux team has announced the release of Sparky 2021.09 in the semi-rolling line. The Sparky 2021.09 inherits from the current Debian testing branch - *Bookworm*.

Sparky 2021.09 points its repositories to Debian Bookworm and Sparky Orion lines. All the packages are in sync with both of the repositories as of 17th September 2021.

![Sparky 2021.09 featured image](/assets/images/post-images/sparky-2021.09.jpg)

## What changed in Sparky 2021.09?
Following are the noteworthy highlights of the Sparky 2021.09 release.
> - repositories set to Debian "Bookworm" and Sparky "Orion Belt"
- all packages updated as of September 17, 2021
- new backgrounds: desktop, login manager, Plymouth & boot screen, etc.
- Linux kernel 5.10.46 (5.14.6 & 5.15-rc1 in Sparky unstable repos)
- GCC 10 is still as default, but GCC 11 is also installed
- no more Sparky Advanced Installed GUI; the Advanced installer works in text mode only now; the first window lets you choose the standard version of the installer or DEV version with disk encryption and LVM support;
- 'sparky-upgrade' text-based tool is also preinstalled in CLI iso
- packages removed from iso: mc, GParted
- new package installed: lfm
- Calamares 3.2.43

## How to get Sparky 2021.09?
For the existing users of Sparky using 2019.x, 2020.x, 2021.x or 6.0, there is no reinstallation required. The users can update from the command line or the GUI tool.

If you would like to keep Sparky rolling, change Debian repos to 'bookworm' and Sparky repos to 'Orion: https://sparkylinux.org/new-testing-line-of-sparky-7/ and make a full system upgrade:
```
sparky-upgrade
```
For the new users, [download Sparky 2021.09 images](https://sparkylinux.org/sparky-2021-09/) from the project's website.

For further information, read [Sparky 2021.09 release announcement](https://sparkylinux.org/sparky-2021-09/) in the projects website.


text:
import { connect } from 'react-redux';
import Filter from '../../components/Transaction/Filter';
import {
  changeFilterDate,
  toggleFilterCalendar,
  toggleFilterModal,
  applyFilters
} from '../../actions/ui/transaction/filter';
import { openTransactionInModal } from '../../actions/ui/form/transaction';
import { getDateLabel } from '../../selectors/ui/transaction/filter';
import {
  getAccountsAsOptions,
  getAccountsNameMap
} from '../../selectors/entities/accounts';
import { getAllTagsOptions } from '../../selectors/entities/tags';

const mapStateToProps = state => ({
  isMobile: state.ui.isMobile,
  dateRangeLabel: getDateLabel(state),
  isCalendarOpen: state.ui.transaction.filter.isCalendarOpen,
  isFilterModalOpen: state.ui.transaction.filter.isFilterModalOpen,
  accountOptions: getAccountsAsOptions(state),
  accountNameMap: getAccountsNameMap(state),
  appliedAccounts: state.ui.transaction.filter.applied.accounts || [],
  tagsOptions: getAllTagsOptions(state),
  appliedTags: state.ui.transaction.filter.applied.tags || []
});

export default connect(
  mapStateToProps,
  {
    changeFilterDate,
    toggleFilterCalendar,
    toggleFilterModal,
    applyFilters,
    openTransactionInModal
  }
)(Filter);


text:
/**
 * Validate and submit identifiers.
 *
 * @author Daniel Shaw (dshaw.com)
 */

var hasTouched = new Array();
$.validator.methods.relies = function(value, element, param) {
    var retVal = $(element).val() > 0;
    hasTouched[element.name] = true;
    if (typeof param == 'object'){
        for (i=0; i<param.length; i++){
            if (hasTouched[param[i]]==true) {
                retVal = retVal && ($("#" + param[i]).val() > 0);
            }
        }
    }
    return retVal;
};

$.validator.methods.regexMatch = function(value, element, param) {
        var re = new RegExp(param);
        return value.match(re);
};

var initValidation = function() {

    HEM.log(HEM.page.form.validationRules);

    // fail fast. Require validation messages.
    if (!HEM.validation.msgs && HEM.log) {
        HEM.log('ERROR: HEM.validation.msgs undefined.');
        return;
    }
    if (!HEM.page.form.submitForm && HEM.log) {
        HEM.log('ERROR: HEM.page.form.submitForm undefined.');
        return;
    }

    // Alias validation messages to make them more readable.
    var msgs = HEM.validation.msgs;

    $('#userform').validate({
        beforeSubmit: HEM.page.form.checkUsername,
        submitHandler: HEM.page.form.submitForm,
        rules: HEM.page.form.validationRules,
        messages: {
            firstname: { required : msgs.firstname.required },
            lastname: { required : msgs.lastname.required },
            city: { required : msgs.city.required },
            state: { required : msgs.state.required },
            zip: { required : msgs.zip.required },
            month: { required : msgs.dob.required, relies: msgs.dob.relies },
            day: { required : msgs.dob.required, relies: msgs.dob.relies },
            year: { required : msgs.dob.required, relies: msgs.dob.relies },
            gender: { required : msgs.gender.required },
            username: {
                required : msgs.username.required,
                minlength : msgs.username.minlength,
                regexMatch : msgs.username.regexMatch
            },
            userimage: { accept: msgs.userimage.accept },
            roles: { required : msgs.roles.required }
        },
        errorPlacement: function(error, element) {
            if(error.text().length > 1){
                HEM.page.form.placeError(error.text(), element)
            } else {
                $(element).nextAll().each(function(){
                    if ($(this).hasClass("errorText")) {
                        $(this).remove();
                    }
                });
            }
        },
        success: function(label) {},
        highlight: function(element, errorClass) {
            $(element).parent().addClass(errorClass);
        },
        unhighlight: function(element, errorClass) {
            $(element).parent().removeClass(errorClass);
        },
        onsubmit: true
    });
}


text:
import React from 'react';
import styled from 'styled-components';
import Fixed from './Fixed';
import Paper from './Paper';
import PropTypes from 'prop-types';

const StyledModal = styled(Fixed).attrs({
  left: true,
  top: true
})`
    width: 100%;
    height: 100%;
    z-index: 1500;
    display: flex;
    overflow: auto;
    align-item: center;
    justify-content: center;
    opacity: ${props => (props.open ? 1 : 0)};
    visibility: ${props => (props.open ? '' : 'hidden')};
    transition: all 225ms cubic-bezier(0,0,0.2,1) 0ms;
`;

const StyledModalBackground = styled(Fixed).attrs({
  left: true,
  top: true
})`
    width: 100%;
    height: 100%;
    z-index: -1;
    background-color: rgba(0,0,0,0.54);
`;

const StyledModalContent = styled.div`
  display: flex;
  flex: 0 1 auto;
  position: relative;
  overflow-y: auto;
  margin: 10% auto;
  flex-direction: column;
`;

const Modal = ({ onRequestClose, open, ...props }) =>
  <StyledModal open={open} onClick={onRequestClose}>
    <StyledModalBackground />
    <StyledModalContent {...props} onClick={event => event.stopPropagation()} />
  </StyledModal>;

Modal.propTypes = {
  open: PropTypes.bool,
  onRequestClose: PropTypes.func
};

Modal.defaultProps = {
  open: false,
  onRequestClose: () => {}
};

export default Modal;


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Configuration File — Zephir documentation</title>
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link href="google/g.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="_static/docs.css" type="text/css" />

    <link rel="shortcut icon" href="_static/favicon.ico"/>
    <link rel="top" title="Zephir documentation" href="index.html" />
    <link rel="next" title="Extension Globals" href="globals.html" />
    <link rel="prev" title="Custom optimizers" href="optimizers.html" />

          index

          next |

          previous |

Home »

Zephir documentation »

Table Of Contents

Configuration File

namespace

name

description

author

version

warnings

optimizations

globals

info

Previous topic

< Custom optimizers

Next topic

Extension Globals >

This Page

Show Source

Configuration File¶

Every Zephir extension has a configuration file called config.json. This file is read by Zephir everytime you build or generate the extension and
it allows the developer to modify the extension or compiler behavior.

This file use JSON as configuration format which is very known and friendly:

{
    "namespace": "test",
    "name": "Test Extension",
    "description": "My amazing extension",
    "author": "Tony Hawk",
    "version": "1.2.0"
}

Settings defined in this file override any factory default setting provided by Zephir.

The following settings are supported:

namespace¶

The namespace of the extension, it must be a simple identifier respecting the regular expression: [a-zA-Z0-9_]+:

{
    "namespace": "test"
}

name¶

Extension name, only can contain ascii characters:

{
    "namespace": "test"
}

description¶

Extension description, any text describing your extension:

{
    "description": "My amazing extension"
}

author¶

Company, developer, institution, etc. that have developed the extension:

{
    "author": "Tony Hawk"
}

version¶

Extension version, must follow the regular expression: [0-9]+.[0-9]+.[0-9]+:

{
    "version": "1.2.0"
}

warnings¶

Compiler warnings enabled or disabled in the current project:

{
    "warnings": {
        "unused-variable": true,
        "unused-variable-external": false,
        "possible-wrong-parameter": true,
        "possible-wrong-parameter-undefined": false,
        "nonexistent-function": true,
        "nonexistent-class": true
    }
}

optimizations¶

Compiler optimizations enabled or disabled in the current project:

{
    "optimizations": {
        "static-type-inference": true,
        "static-type-inference-second-pass": true,
        "local-context-pass": false
    }
}

globals¶

Extension globals available. Check the extension globals chapter for more information.

{
    "globals": {
        "my_setting_1": {
            "type": "bool",
            "default": true
        },
        "my_setting_2": {
            "type": "int",
            "default": 10
        }
}

info¶

phpinfo() sections. Check the phpinfo() chapter for more information.

{
    "info": [
        {
            "header": ["Directive", "Value"],
            "rows": [
                ["setting1", "value1"],
                ["setting2", "value2"]
            ]
        }
    ]
}

          index

          next |

          previous |

Zephir Language is an open source project licensed under
            MIT license.

Except where otherwise noted, content on this site is licensed under the
            Creative Commons Attribution 3.0 License.

             Last updated on Apr 27, 2014.
            V0.4.2 GitHub

             © Copyright 2013-2014, Zephir Team.


text:
import { ProvidedFilterModel } from '@ag-grid-community/core';
export interface SetFilterModel extends ProvidedFilterModel {
    values: string[];
}


text:
<?php

namespace Intervention\Image\Commands;

use Closure;

class RectangleCommand extends \Intervention\Image\Commands\AbstractCommand
{
    /**
     * Draws rectangle on given image
     *
     * @param  \Intervention\Image\Image $image
     * @return boolean
     */
    public function execute($image)
    {
        $x1 = $this->argument(0)->type('numeric')->required()->value();
        $y1 = $this->argument(1)->type('numeric')->required()->value();
        $x2 = $this->argument(2)->type('numeric')->required()->value();
        $y2 = $this->argument(3)->type('numeric')->required()->value();
        $callback = $this->argument(4)->type('closure')->value();

        $rectangle_classname = sprintf('\Intervention\Image\%s\Shapes\RectangleShape',
            $image->getDriver()->getDriverName());

        $rectangle = new $rectangle_classname($x1, $y1, $x2, $y2);

        if ($callback instanceof Closure) {
            $callback($rectangle);
        }

        $rectangle->applyToImage($image, $x1, $y1);

        return true;
    }
}


text:
using LocalNotifications.Plugin;
using Petrolhead.Helpers;
using Petrolhead.Services;
using Petrolhead.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Xamarin.Forms;

namespace Petrolhead
{
    public delegate void OnVehicleCreated(ref VehicleViewModel vehicle);
    public class App : Application
    {
        public App()
        {

            // The root page of your application
            MainPage = new Views.LoginPage();
        }

        public OnVehicleCreated OnVehicleCreated
        {
            get;
            set;
        }
        protected override void OnStart()
        {

        }

        protected override async void OnSleep()
        {
            Settings.LastSync = DateTime.Now.AddDays(-4);
            await DataStore.Current.SyncVehiclesAsync();
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}


text:
<?php

namespace Amadeus\Client\Struct\Queue;

/**
 * Structure class for the SelectionDetails message part for Queue_* messages
 *
 * @package Amadeus\Client\Struct\Queue
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class SelectionDetails
{
    const PLACEPNR_OPTION_QUEUE = "QEQ";
    const PLACEPNR_OPTION_DELAYQUEUE = "QED";
    const MOVE_OPTION_COPY_QUEUE_KEEP = "QBB";
    const MOVE_OPTION_COPY_QUEUE_REMOVE = "QBD";
    const LIST_OPTION_SORT_CREATION = "CD";
    const LIST_OPTION_SORT_DEPARTURE = "DD";
    const LIST_OPTION_SORT_TICKETING = "TD";
    const REMOVE_OPTION_SPECIFIC_PNR = "QRP";
    const REMOVE_OPTION_ALL = "QR";

    /* Queue_* options:
     * QBA  copy PNR/msg to specified delay queue and keep existing
     * QBB  copy PNR/msg to specified queue and keep existing
     * QBC  copy PNR/msg to specified delay queue and remove existing
     * QBD  copy PNR/msg to specified queue and remove existing
     * QWD  copy PNR from delay planner and keep existing
     * QWO  copy PNR from option planner and keep existing
     * QWR  copy PNR from planner and remove existing
     * QWS  copy PNR from planner and keep existing
     * QWT  copy PNR from ticketing planner and keep existing
     */

    /**
     * @var string
     */
    public $option;

    /**
     * @param string $optionCode
     */
    public function __construct($optionCode)
    {
        $this->option = $optionCode;
    }
}


text:
namespace {
base::android::RegistrationMethod kContentRegisteredMethods[] = {
  { "CommandLine", RegisterCommandLine },
  { "SurfaceCallback", content::RegisterSurfaceCallback },
  { "SurfaceTextureListener",
        content::SurfaceTextureListener::RegisterSurfaceTextureListener },
  { "TraceEvent", RegisterTraceEvent },
};

}  // namespace

namespace content {
namespace android {

bool RegisterCommonJni(JNIEnv* env) {
  return RegisterNativeMethods(env, kContentRegisteredMethods,
                               arraysize(kContentRegisteredMethods));
}

}  // namespace android
}  // namespace content


text:
require 'spec_helper'

describe Fakery::Registry do
  let :fake do
    Fakery::Fake.from_hash(name: 'foo')
  end

  it 'registers fakes under a name' do
    expect(Fakery).to_not be_registered 'foo'
    expect(Fakery).to_not be_registered :foo
    Fakery.register 'foo', fake
    expect(Fakery).to be_registered 'foo'
    expect(Fakery).to be_registered :foo
  end

  it 'warns iff a fake was registered a second time' do
    expect(Fakery::Registry).to receive(:warn).with(any_args)
    Fakery.register 'foo', fake
    Fakery.register 'foo', fake
  end

  it 'can register files containing json as fakes' do
    expect(File).to receive(:read).with('bar/foo.json').and_return fake.to_json
    Fakery.register_files 'bar/foo.json'
    expect(Fakery.build(:foo).name).to eq 'foo'
  end

  context 'registered fake' do
    before :each do
      Fakery.register :foo, fake
    end

    it 'cannot be built if not registered' do
      expect { Fakery.build(:bar) }.to raise_error ArgumentError
    end

    it 'can be built' do
      foo = Fakery.build(:foo)
      expect(foo.name).to eq 'foo'
      expect(foo.bar).to be_nil
    end

    it 'can be changed and registered again' do
      foo = Fakery.build(:foo, with: { bar: true })
      expect(foo.bar).to eq true
      Fakery.register(:bar, foo)
      expect(Fakery.build(:bar).bar).to eq true
    end

    it 'can be listed' do
      expect(Fakery::Registry.list).to eq %i[ foo ]
    end
  end
end


text:
package software.betamax.message;

import com.google.common.base.Strings;
import com.google.common.net.MediaType;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.net.HttpHeaders.CONTENT_ENCODING;
import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static com.google.common.net.MediaType.OCTET_STREAM;

public abstract class AbstractMessage implements Message {

    public static final String DEFAULT_CONTENT_TYPE = OCTET_STREAM.toString();
    public static final String DEFAULT_CHARSET = UTF_8.toString();
    public static final String DEFAULT_ENCODING = "none";

    @Override
    public String getContentType() {
        String header = getHeader(CONTENT_TYPE);
        if (Strings.isNullOrEmpty(header)) {
            return DEFAULT_CONTENT_TYPE;
        } else {
            return MediaType.parse(header).withoutParameters().toString();
        }
    }

    @Override
    public String getCharset() {
        String header = getHeader(CONTENT_TYPE);
        if (Strings.isNullOrEmpty(header)) {
            // TODO: this isn't valid for non-text data – this method should return Optional<String>
            return DEFAULT_CHARSET;
        } else {
            return MediaType.parse(header).charset().or(UTF_8).toString();
        }
    }

    @Override
    public String getEncoding() {
        String header = getHeader(CONTENT_ENCODING);
        return header == null || header.length() == 0 ? DEFAULT_ENCODING : header;
    }

    @Override
    public String getHeader(String name) {
        return getHeaders().get(name);
    }

    @Override
    public final byte[] getBodyAsBinary() {
        // Credit goes to StackOverflow Post
        // http://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-array-in-java
        try {
            InputStream is = getBodyAsStream();

            try {
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();

                int nRead;
                byte[] data = new byte[8 * 1024]; // 8KB

                while ((nRead = is.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, nRead);
                }

                buffer.flush();

                return buffer.toByteArray();
            } finally {
                is.close();
            }
        } catch (IOException e) {
            return new byte[0];
        }
    }

    @Override
    public final String getBodyAsText() {
        try {
            return new String(getBodyAsBinary(), getCharset());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    protected abstract InputStream getBodyAsStream() throws IOException;
}


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

import javax.annotation.Generated;

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

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

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

    private static final MarshallingInfo<String> WORKFLOWID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("workflowId").build();

    private static final WorkflowExecutionFilterMarshaller instance = new WorkflowExecutionFilterMarshaller();

    public static WorkflowExecutionFilterMarshaller getInstance() {
        return instance;
    }

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

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

        try {
            protocolMarshaller.marshall(workflowExecutionFilter.getWorkflowId(), WORKFLOWID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
#include <aws/network-firewall/model/StatelessRulesAndCustomActions.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace NetworkFirewall
{
namespace Model
{

StatelessRulesAndCustomActions::StatelessRulesAndCustomActions() :
    m_statelessRulesHasBeenSet(false),
    m_customActionsHasBeenSet(false)
{
}

StatelessRulesAndCustomActions::StatelessRulesAndCustomActions(JsonView jsonValue) :
    m_statelessRulesHasBeenSet(false),
    m_customActionsHasBeenSet(false)
{
  *this = jsonValue;
}

StatelessRulesAndCustomActions& StatelessRulesAndCustomActions::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("StatelessRules"))
  {
    Array<JsonView> statelessRulesJsonList = jsonValue.GetArray("StatelessRules");
    for(unsigned statelessRulesIndex = 0; statelessRulesIndex < statelessRulesJsonList.GetLength(); ++statelessRulesIndex)
    {
      m_statelessRules.push_back(statelessRulesJsonList[statelessRulesIndex].AsObject());
    }
    m_statelessRulesHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CustomActions"))
  {
    Array<JsonView> customActionsJsonList = jsonValue.GetArray("CustomActions");
    for(unsigned customActionsIndex = 0; customActionsIndex < customActionsJsonList.GetLength(); ++customActionsIndex)
    {
      m_customActions.push_back(customActionsJsonList[customActionsIndex].AsObject());
    }
    m_customActionsHasBeenSet = true;
  }

  return *this;
}

JsonValue StatelessRulesAndCustomActions::Jsonize() const
{
  JsonValue payload;

  if(m_statelessRulesHasBeenSet)
  {
   Array<JsonValue> statelessRulesJsonList(m_statelessRules.size());
   for(unsigned statelessRulesIndex = 0; statelessRulesIndex < statelessRulesJsonList.GetLength(); ++statelessRulesIndex)
   {
     statelessRulesJsonList[statelessRulesIndex].AsObject(m_statelessRules[statelessRulesIndex].Jsonize());
   }
   payload.WithArray("StatelessRules", std::move(statelessRulesJsonList));

  }

  if(m_customActionsHasBeenSet)
  {
   Array<JsonValue> customActionsJsonList(m_customActions.size());
   for(unsigned customActionsIndex = 0; customActionsIndex < customActionsJsonList.GetLength(); ++customActionsIndex)
   {
     customActionsJsonList[customActionsIndex].AsObject(m_customActions[customActionsIndex].Jsonize());
   }
   payload.WithArray("CustomActions", std::move(customActionsJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace NetworkFirewall
} // namespace Aws


text:
import ctypes as ct
import pandas as pd
import numpy as np
import random, csv, sys, os
import math
import time

np.set_printoptions(suppress=True)

from statistics import median

import classes_water as ENC
import classes_power as ODC
import classes_interconnection as ICC
import grb_solvers

from comtypes import automation
import win32com.client
# from win32com.client import makepy
# sys.argv = ['makepy', 'OpenDSSEngine.DSS']
# makepy.main()

from operator import itemgetter

def main(dss_debug, write_cols, power_df, water_df, a_sens, pipe_fail_id, junc_sens):

	os_username = os.getlogin()

	# --------------
	# READ CSV FILES
	# --------------

	csv_curve = pd.read_csv('./data_water/network-water/2000curve.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_junction = pd.read_csv('./data_water/network-water/2100junction.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_reservoir = pd.read_csv('./data_water/network-water/2101reservoir.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_tank = pd.read_csv('./data_water/network-water/2102tank.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_pipe = pd.read_csv('./data_water/network-water/2200pipe.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_pump = pd.read_csv('./data_water/network-water/2201pump.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_valve = pd.read_csv('./data_water/network-water/2202valve.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_pumpvalve = pd.read_csv('./data_water/network-water/2203pumpvalve.csv', sep=',', header=1, index_col=None, dtype=np.float64)

	csv_xycurve = pd.read_csv('./data_power/network-power/1000xycurve.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_regcontrol = pd.read_csv('./data_power/network-power/1100regcontrol.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_wiredata = pd.read_csv('./data_power/network-power/1200wiredata.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_linecode = pd.read_csv('./data_power/network-power/1201linecode.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_bus = pd.read_csv('./data_power/network-power/1300bus.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_vsource = pd.read_csv('./data_power/network-power/1301vsource.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_generator = pd.read_csv('./data_power/network-power/1302generator.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_load = pd.read_csv('./data_power/network-power/1303load.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_solarpv = pd.read_csv('./data_power/network-power/1304solarpv.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_windturbine = pd.read_csv('./data_power/network-power/1305windturbine.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_directconnection = pd.read_csv('./data_power/network-power/1400directconnection.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_cable = pd.read_csv('./data_power/network-power/1401cable.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_overheadline = pd.read_csv('./data_power/network-power/1402overheadline.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_twowindingtransformer = pd.read_csv('./data_power/network-power/1403twowindingtransformer.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_capacitor = pd.read_csv('./data_power/network-power/1404capacitor.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	csv_reactor = pd.read_csv('./data_power/network-power/1405reactor.csv', sep=',', header=1, index_col=None, dtype=np.float64)
	# csv_allcolumns= pd.read_csv('./data_power/network-power/allcolumns.csv', sep=',', header=1, index_col=None, dtype=np.float64)

	# -----------------
	# CREATE COMPONENTS
	# -----------------

	object_curve = ENC.Curve(csv_curve)
	object_junction = ENC.Junction(csv_junction)
	object_reservoir = ENC.Reservoir(csv_reservoir)
	object_tank = ENC.Tank(csv_tank)
	object_pipe = ENC.Pipe(csv_pipe)
	object_pump = ENC.Pump(csv_pump)
	object_valve = ENC.Valve(csv_valve)
	object_pumpvalve = ENC.PumpValve(csv_pumpvalve)

	object_xycurve = ODC.XYCurve(csv_xycurve)
	object_regcontrol = ODC.RegControl(csv_regcontrol)
	object_wiredata = ODC.WireData(csv_wiredata)
	object_linecode = ODC.LineCode(csv_linecode)
	object_bus = ODC.Bus(csv_bus)
	object_vsource = ODC.VSource(csv_vsource)
	object_generator = ODC.Generator(csv_generator)
	object_load = ODC.Load(csv_load)
	object_solarpv = ODC.SolarPV(csv_solarpv)
	object_windturbine = ODC.WindTurbine(csv_windturbine, object_xycurve)
	object_directconnection = ODC.DirectConnection(csv_directconnection)
	object_cable = ODC.Cable(csv_cable)
	object_overheadline = ODC.OverheadLine(csv_overheadline)
	object_twowindingtransformer = ODC.TwoWindingTransformer(csv_twowindingtransformer)
	object_capacitor = ODC.Capacitor(csv_capacitor)
	object_reactor = ODC.Reactor(csv_reactor)

	total_capacity_reduce = 0.0 # Reduce maximum network load equal to amount of capacity that is reduced from Unit 121
	for generator in object_generator.matrix:
		if generator[ODC.Generator.ID] == 121.0:
			total_capacity_reduce = (1.0 - a_sens) * generator[ODC.Generator.REAL_GENERATION_MAX_RATING]
			generator[ODC.Generator.RAMP_RATE] = a_sens * generator[ODC.Generator.RAMP_RATE]
			generator[ODC.Generator.REAL_GENERATION_MIN_RATING] = a_sens * generator[ODC.Generator.REAL_GENERATION_MIN_RATING]
			generator[ODC.Generator.REAL_GENERATION_MAX_RATING] = a_sens * generator[ODC.Generator.REAL_GENERATION_MAX_RATING]
			generator[ODC.Generator.JUNCTION_ID] = junc_sens
			print('Unit {} new junction ID {}'.format(generator[ODC.Generator.ID], generator[ODC.Generator.JUNCTION_ID]))
	percent_capacity_reduce = total_capacity_reduce / sum(object_load.matrix[:, ODC.Load.REAL_LOAD_MAX])
	object_load.matrix[:, ODC.Load.REAL_LOAD_MAX] = (1.0 - percent_capacity_reduce) * object_load.matrix[:, ODC.Load.REAL_LOAD_MAX]

	# -----------------------
	# ADD COMPONENTS TO LISTS
	# -----------------------

	w_object_list = [object_junction, object_reservoir, object_tank, # Water NODES
	object_pipe, object_pump, object_valve, object_pumpvalve, # Water LINKS
	object_curve] # Water SYSTEM OPS

	object_list = [object_vsource, object_bus, object_generator, object_load, object_solarpv, object_windturbine, #NODES
	object_xycurve, object_wiredata, object_linecode, #OTHERS
	object_directconnection, object_cable, object_overheadline, object_twowindingtransformer, object_capacitor, object_reactor, # CONNECTIONS
	object_regcontrol] # CONTROLS

	interconn_dict = {'generator': object_generator, 'load': object_load, 'pump': object_pump, 'junction': object_junction, 'pumpvalve': object_pumpvalve}

	# ---------
	# RUN EPANET and OPENDSS
	# ---------

	def run_EPANET():
		filedir = 'C:/Users/'+os_username+'/Documents/git/RISE-power-water-ss-1phase/data_water/en-inputs/en-input.inp'
		with open(filedir, 'w', newline='\n') as csvfile:
			writer = csv.writer(csvfile, delimiter=' ')
			templist = ['[TITLE]']
			writer.writerow(templist)
			writer.writerow('')

			for water_object in w_object_list:
				water_object.createAllEN(writer, interconn_dict)

			templist = ['[ENERGY]']
			writer.writerow(templist)
			templist = ['Global', 'Efficiency', 75]
			writer.writerow(templist)
			templist = ['Global', 'Price', 0]
			writer.writerow(templist)
			templist = ['Demand', 'Charge', 0]
			writer.writerow(templist)
			writer.writerow('')

			templist = ['[REACTIONS]']
			writer.writerow(templist)
			templist = ['Order', 'Bulk', 1]
			writer.writerow(templist)
			templist = ['Order', 'Tank', 1]
			writer.writerow(templist)
			templist = ['Order', 'Wall', 1]
			writer.writerow(templist)
			templist = ['Global', 'Bulk', 0]
			writer.writerow(templist)
			templist = ['Global', 'Wall', 0]
			writer.writerow(templist)
			templist = ['Limiting', 'Potential', 0]
			writer.writerow(templist)
			templist = ['Roughness', 'Correlation', 0]
			writer.writerow(templist)
			writer.writerow('')

			templist = ['[TIMES]']
			writer.writerow(templist)
			templist = ['Duration', '0:00:00']
			writer.writerow(templist)
			templist = ['Hydraulic', 'Timestep', '0:00:01']
			writer.writerow(templist)
			templist = ['Quality', 'Timestep', '0:06']
			writer.writerow(templist)
			templist = ['Pattern', 'Timestep', '1:00']
			writer.writerow(templist)
			templist = ['Pattern', 'Start', '0:00']
			writer.writerow(templist)
			templist = ['Report', 'Timestep', '1:00']
			writer.writerow(templist)
			templist = ['Report', 'Start', '0:00']
			writer.writerow(templist)
			templist = ['Start', 'ClockTime', 12, 'am']
			writer.writerow(templist)
			templist = ['Statistic', 'NONE']
			writer.writerow(templist)
			writer.writerow('')

			templist = ['[REPORT]']
			writer.writerow(templist)
			templist = ['Status', 'No']
			writer.writerow(templist)
			templist = ['Summary', 'No']
			writer.writerow(templist)
			templist = ['Page', 0]
			writer.writerow(templist)
			writer.writerow('')

			templist = ['[OPTIONS]']
			writer.writerow(templist)
			templist = ['Units', 'GPM'] #GPM is US Customary units
			writer.writerow(templist)
			templist = ['Headloss', 'C-M']
			writer.writerow(templist)
			templist = ['Specific', 'Gravity', 1]
			writer.writerow(templist)
			templist = ['Viscosity', 1]
			writer.writerow(templist)
			templist = ['Trials', 40]
			writer.writerow(templist)
			templist = ['Accuracy', 0.001]
			writer.writerow(templist)
			templist = ['CHECKFREQ', 2]
			writer.writerow(templist)
			templist = ['MAXCHECK', 10]
			writer.writerow(templist)
			templist = ['DAMPLIMIT', 0]
			writer.writerow(templist)
			templist = ['Unbalanced', 'Continue', 10]
			writer.writerow(templist)
			templist = ['Pattern', 1]
			writer.writerow(templist)
			templist = ['Demand', 'Multiplier', 1.0]
			writer.writerow(templist)
			templist = ['Emitter', 'Exponent', 0.5]
			writer.writerow(templist)
			templist = ['Quality', 'None', 'mg/L']
			writer.writerow(templist)
			templist = ['Diffusivity', 1]
			writer.writerow(templist)
			templist = ['Tolerance', 0.01]
			writer.writerow(templist)
			writer.writerow('')

			templist=['[END]']
			writer.writerow(templist)

		epalib = ct.cdll.LoadLibrary('C:/Users/'+os_username+'/Documents/git/RISE-power-water-ss-1phase/data_water/epanet2mingw64.dll')

		# Byte objects
		en_input_file = ct.c_char_p(filedir.encode('utf-8'))
		en_report_file = ct.c_char_p(str('C:/Users/'+os_username+'/Documents/git/RISE-power-water-ss-1phase/data_water/en-outputs/out.rpt').encode('utf-8'))
		en_byte_file = ct.c_char_p(''.encode('utf-8'))

		# Send strings as char* to the epalib function
		errorcode = epalib.ENopen(en_input_file, en_report_file, en_byte_file)
		if errorcode != 0:
			print(1, 'ERRORCODE is', errorcode)

		errorcode = epalib.ENopenH()
		if errorcode != 0:
			print(2, 'ERRORCODE is', errorcode)

		init_flag = ct.c_int(0)
		errorcode = epalib.ENinitH(init_flag)
		if errorcode != 0:
			print(3, 'ERRORCODE is', errorcode)

		time = ct.pointer(ct.c_long(1))
		timestep = ct.pointer(ct.c_long(1))
		while True:
			errorcode = epalib.ENrunH(time)
			if errorcode != 0:
				pass
				# print(4, 'ERRORCODE is', errorcode)

			errorcode = epalib.ENnextH(timestep)
			if errorcode != 0:
				print(5, 'ERRORCODE is', errorcode)

			if timestep.contents.value == 0:
				break

		for water_object in w_object_list:
			water_object.readAllENoutputs(epalib)

		errorcode = epalib.ENcloseH()
		if errorcode != 0:
			print(6, 'ERRORCODE is', errorcode)

		errorcode = epalib.ENclose()
		if errorcode != 0:
			print(7, 'ERRORCODE is', errorcode)

		input_list_continuous = []
		input_list_categorical = []
		input_tensor_continuous = np.empty([0,0], dtype=np.float64).flatten()
		input_tensor_categorical = np.empty([0,0], dtype=np.float64).flatten()
		for object in w_object_list:
			list_continuous, list_categorical, tensor_continuous, tensor_categorical = object.convertToInputTensor()
			input_list_continuous = input_list_continuous + list_continuous
			input_list_categorical = input_list_categorical + list_categorical
			input_tensor_continuous = np.concatenate((input_tensor_continuous, tensor_continuous), axis=0)
			input_tensor_categorical = np.concatenate((input_tensor_categorical, tensor_categorical), axis=0)

		output_list = []
		output_tensor = np.empty([0,0], dtype=np.float64).flatten()
		for object in w_object_list:
			o_list, o_tensor = object.convertToOutputTensor()
			output_list = output_list + o_list
			output_tensor = np.concatenate((output_tensor, o_tensor), axis=0)

		return input_list_continuous, input_list_categorical, output_list, input_tensor_continuous, input_tensor_categorical, output_tensor

	def run_OpenDSS(dss_debug, solverFlag):
		# SET SOURCEBUS
		# VsourceClass.sourcebus = vsourceobj.id[1]
		dssObj = win32com.client.Dispatch('OpenDSSEngine.DSS') # OPENDSS COMPORT

		dssObj.AllowForms = False
		dssText = dssObj.Text
		dssCkt = dssObj.ActiveCircuit
		dssSolution = dssCkt.Solution
		dssActvElem = dssCkt.ActiveCktElement
		dssActvBus = dssCkt.ActiveBus

		dssText.Command = 'Clear'

		dssText.Command = 'Set DataPath=\'C:\\Users\\'+os_username+'\\Documents\\OpenDSS'
		dssText.Command = 'Set DefaultBaseFrequency=60'

		for object in object_list:
			object.createAllDSS(dssText, interconn_dict, dss_debug)

		set_voltagebase = set()
		for object in object_list:
			set_voltagebase = set_voltagebase | object.voltagesToSets()

		dssText.Command = 'Set VoltageBases={}'.format(list(set_voltagebase))
		dssText.Command = 'CalcVoltageBases'
		dssText.Command = 'Solve BaseFrequency=60 MaxIter=300'

		variant_buses = automation.VARIANT()
		variant_voltages_mag = automation.VARIANT()
		variant_voltages_pu = automation.VARIANT()
		variant_currents = automation.VARIANT()
		variant_powers = automation.VARIANT()

		for object in object_list:
			object.readAllDSSOutputs(dssCkt, dssActvElem, dssActvBus, variant_buses, variant_voltages_mag, variant_voltages_pu, variant_currents, variant_powers)

		if solverFlag == False:
			# dssText.Command = 'Save Circuit'
			# dssText.Command = 'Export Summary (summary.csv)'
			# dssText.Command = 'Export Currents (currents.csv)'
			# dssText.Command = 'Export Voltages (voltages.csv)'
			# dssText.Command = 'Export Overloads (overloads.csv)'
			# dssText.Command = 'Export Powers kVA (powers.csv)'

			input_list_continuous = []
			input_list_categorical = []
			input_tensor_continuous = np.empty([0,0], dtype=np.float64).flatten()
			input_tensor_categorical = np.empty([0,0], dtype=np.float64).flatten()
			for object in object_list:
				list_continuous, list_categorical, tensor_continuous, tensor_categorical = object.convertToInputTensor()
				input_list_continuous = input_list_continuous + list_continuous
				input_list_categorical = input_list_categorical + list_categorical
				input_tensor_continuous = np.concatenate((input_tensor_continuous, tensor_continuous), axis=0)
				input_tensor_categorical = np.concatenate((input_tensor_categorical, tensor_categorical), axis=0)

			output_list = []
			output_tensor = np.empty([0,0], dtype=np.float64).flatten()
			for object in object_list:
				o_list, o_tensor = object.convertToOutputTensor()
				output_list = output_list + o_list
				output_tensor = np.concatenate((output_tensor, o_tensor), axis=0)

			return input_list_continuous, input_list_categorical, output_list, input_tensor_continuous, input_tensor_categorical, output_tensor
		else:
			losses = dssCkt.Losses
			return float(losses[0])*0.001 # kW

	# SIM STEP 0: SOLVE PUMP POWER CONSUMPTION
	# ----------------------------------------

	for pipe in object_pipe.matrix:
		if pipe[ENC.Pipe.ID] in [pipe_fail_id]:
			pipe[ENC.Pipe.OPERATIONAL_STATUS] = 0.0

	base_curve_matrix = np.array(object_curve.matrix, copy=True)
	base_junction_matrix = np.array(object_junction.matrix, copy=True)
	base_reservoir_matrix = np.array(object_reservoir.matrix, copy=True)
	base_tank_matrix = np.array(object_tank.matrix, copy=True)
	base_pipe_matrix = np.array(object_pipe.matrix, copy=True)
	base_pump_matrix = np.array(object_pump.matrix, copy=True)
	base_valve_matrix = np.array(object_valve.matrix, copy=True)
	base_pumpvalve_matrix = np.array(object_pumpvalve.matrix, copy=True)

	artificial_reservoir_id_shift = 1000.0
	max_groundwater_flow = 12399.0 # GPM
	groundwater_id_shift = 2000.0

	# Scale reservoir heads using water_df
	for reservoir in object_reservoir.matrix:
		if reservoir[ENC.Reservoir.ID] == 21.0:
			reservoir[ENC.Reservoir.TOTAL_HEAD] = max(reservoir[ENC.Reservoir.TOTAL_HEAD], 864.92*water_df + 817.08)
		elif reservoir[ENC.Reservoir.ID] == 22.0:
			reservoir[ENC.Reservoir.TOTAL_HEAD] = max(reservoir[ENC.Reservoir.TOTAL_HEAD], 951.11*water_df + 898.89)
		elif reservoir[ENC.Reservoir.ID] == 23.0:
			reservoir[ENC.Reservoir.TOTAL_HEAD] = max(reservoir[ENC.Reservoir.TOTAL_HEAD], 668.35*water_df + 631.65)

	groundwater_list = []
	map_to_groundwater_reservoir = {}
	map_to_groundwater_pipe = {}

	# Track real reservoirs
	for reservoir in object_reservoir.matrix:
		if reservoir[ENC.Reservoir.ID] >= 3000.0:
			groundwater_list.append(reservoir[ENC.Reservoir.ID])
			map_to_groundwater_reservoir[reservoir[ENC.Reservoir.ID]] = reservoir
			for pipe in object_pipe.matrix:
				if reservoir[ENC.Reservoir.ID] == pipe[ENC.Pipe.ID]:
					map_to_groundwater_pipe[reservoir[ENC.Reservoir.ID]] = pipe
		# WARNING THIS IS HARDCODED
		elif reservoir[ENC.Reservoir.ID] == 21.0:
			groundwater_list.append(reservoir[ENC.Reservoir.ID])
			map_to_groundwater_reservoir[reservoir[ENC.Reservoir.ID]] = reservoir
			for pipe in object_pipe.matrix:
				if pipe[ENC.Pipe.ID] == 4021.0:
					map_to_groundwater_pipe[reservoir[ENC.Reservoir.ID]] = pipe
		# WARNING THIS IS HARDCODED
		elif reservoir[ENC.Reservoir.ID] == 22.0:
			groundwater_list.append(reservoir[ENC.Reservoir.ID])
			map_to_groundwater_reservoir[reservoir[ENC.Reservoir.ID]] = reservoir
			for pipe in object_pipe.matrix:
				if pipe[ENC.Pipe.ID] == 1.0:
					map_to_groundwater_pipe[reservoir[ENC.Reservoir.ID]] = pipe
		# WARNING THIS IS HARDCODED
		elif reservoir[ENC.Reservoir.ID] == 23.0:
			groundwater_list.append(reservoir[ENC.Reservoir.ID])
			map_to_groundwater_reservoir[reservoir[ENC.Reservoir.ID]] = reservoir
			for pipe in object_pipe.matrix:
				if pipe[ENC.Pipe.ID] == 36.0:
					map_to_groundwater_pipe[reservoir[ENC.Reservoir.ID]] = pipe

	# Loop real reservoirs, turn off the ones with water inflow
	while len(groundwater_list) > 0:

		# initialize relevnt demand junctions
		demand_list = []
		map_to_junction = {}
		map_to_junction_groundwater = {}
		map_to_reservoir = {}
		map_to_pipe = {}

		# Track demand junctions
		for junction in object_junction.matrix:
			if junction[ENC.Junction.BASE_DEMAND_AVERAGE] > 0.0:
				demand_list.append(junction[ENC.Junction.ID])
		for junction in object_junction.matrix:
			if junction[ENC.Junction.ID] in demand_list:
				map_to_junction[junction[ENC.Junction.ID]] = junction
				found_junction_groundwater = 0
				for junction_groundwater in object_junction.matrix:
					if junction[ENC.Junction.ID] + groundwater_id_shift == junction_groundwater[ENC.Junction.ID]:
						map_to_junction_groundwater[junction[ENC.Junction.ID]] = junction_groundwater
						found_junction_groundwater = 1
				if found_junction_groundwater == 0:
					map_to_junction_groundwater[junction[ENC.Junction.ID]] = junction

		# Track artificial reservoirs
		for reservoir in object_reservoir.matrix:
			if reservoir[ENC.Reservoir.ID]-artificial_reservoir_id_shift in demand_list:
				map_to_reservoir[reservoir[ENC.Reservoir.ID]-artificial_reservoir_id_shift] = reservoir

		# Track pipes for artifical reservoirs
		for pipe in object_pipe.matrix:
			if pipe[ENC.Pipe.ID]-artificial_reservoir_id_shift in demand_list:
				map_to_pipe[pipe[ENC.Pipe.ID]-artificial_reservoir_id_shift] = pipe

		# Reset demand junction demands to 0
		for junction_id in demand_list:
			map_to_junction[junction_id][ENC.Junction.BASE_DEMAND] = 0.0

		# Begin EPANET pressure-driven analysis for artificial reservoirs
		while len(demand_list) > 0:

			# Close artifical reservoirs pipes
			for junction_id in demand_list:
				map_to_pipe[junction_id][ENC.Pipe.OPERATIONAL_STATUS] = 0.0

			# Set valve pressure loss to 0
			for valve in object_valve.matrix:
				valve[ENC.Valve.MODEL] = 2.0
				valve[ENC.Valve.SETTING] = 0.0
			run_EPANET()

			# Open demand junctions with positive pressure ratio
			# Can take multiple iterations
			pos_pres_bool = True
			while pos_pres_bool:
				pos_pres_bool = False
				max_pres_id = demand_list[0]
				for junction_id in demand_list:
					if max(map_to_junction[junction_id][ENC.Junction.PRESSURE], map_to_junction_groundwater[junction_id][ENC.Junction.PRESSURE]) > map_to_junction[max_pres_id][ENC.Junction.MIN_PRESSURE] and map_to_pipe[junction_id][ENC.Pipe.OPERATIONAL_STATUS] == 0.0:
						max_pres_id = junction_id
				# this uses the MINIMUM ALLOWABLE PRESSURE
				if max(map_to_junction[max_pres_id][ENC.Junction.PRESSURE], map_to_junction_groundwater[max_pres_id][ENC.Junction.PRESSURE]) > (map_to_junction[max_pres_id][ENC.Junction.MIN_PRESSURE] - 0.01) and map_to_pipe[max_pres_id][ENC.Pipe.OPERATIONAL_STATUS] == 0.0:
					map_to_pipe[max_pres_id][ENC.Pipe.OPERATIONAL_STATUS] = 1.0
					pos_pres_bool = True
				run_EPANET()

			# Set flow control valves to maximum amount of groundwater flow
			for valve in object_valve.matrix:
				valve[ENC.Valve.MODEL] = 3.0
				valve[ENC.Valve.SETTING] = max_groundwater_flow
			run_EPANET()

			# Close artifical reservoirs with inflows
			# Can take multiple iterations
			neg_dem_bool = True
			while neg_dem_bool:
				neg_dem_bool = False
				for junction_id in demand_list:
					if map_to_reservoir[junction_id][ENC.Reservoir.DEMAND] < 0.0:
						map_to_pipe[junction_id][ENC.Pipe.OPERATIONAL_STATUS] = 0.0
						neg_dem_bool = True
				run_EPANET()
			run_EPANET()

			# Set base_demand to maximum if possible
			pda_count = 0
			demand_list_copy = demand_list.copy()
			for junction_id in demand_list_copy:
				if map_to_reservoir[junction_id][ENC.Reservoir.DEMAND] >= water_df * map_to_junction[junction_id][ENC.Junction.BASE_DEMAND_AVERAGE]:
					map_to_junction[junction_id][ENC.Junction.BASE_DEMAND] = water_df * map_to_junction[junction_id][ENC.Junction.BASE_DEMAND_AVERAGE]
					map_to_pipe[junction_id][ENC.Pipe.OPERATIONAL_STATUS] = 0.0
					demand_list.remove(junction_id)
					pda_count += 1

			# Set base_demand to greater than 0 and less than maximum if there are no maximums
			if pda_count == 0:
				for junction_id in demand_list_copy:
					if map_to_reservoir[junction_id][ENC.Reservoir.DEMAND] >= -0.01:
						map_to_junction[junction_id][ENC.Junction.BASE_DEMAND] = map_to_reservoir[junction_id][ENC.Reservoir.DEMAND]
						map_to_pipe[junction_id][ENC.Pipe.OPERATIONAL_STATUS] = 0.0
						demand_list.remove(junction_id)
			# End inner loop
		run_EPANET()

		# Close real reservoirs with inflows if possible
		pda_count = 0
		groundwater_list_copy = groundwater_list.copy()
		for groundwater_id in groundwater_list_copy:
			if map_to_groundwater_reservoir[groundwater_id][ENC.Reservoir.DEMAND] > 0.0:
				map_to_groundwater_pipe[groundwater_id][ENC.Pipe.OPERATIONAL_STATUS] = 0.0
				groundwater_list.remove(groundwater_id)
				pda_count += 1

		# Delete real reservoirs from being tracked if no real reservoirs have inflows
		if pda_count == 0:
			for groundwater_id in groundwater_list_copy:
				groundwater_list.remove(groundwater_id)
		# End middle loop
	run_EPANET()

	# SIM STEP 1: SET LOAD AND DEMAND CURVES
	# ------------------------------

	power_factor = 0.0
	power_load_factor = power_df
	object_load.multiplyLoadFactor(power_load_factor, power_factor)
	print('power load factor', power_load_factor)
	# object_junction.multiplyLoadFactor(water_df) # unnecessary the EPANET PDNA will solve for this
	print('water demand factor', water_df)

	# SIM STEP 2: SET LOAD INTERCONNECTIONS
	# ----------------------------------

	object_load.setInterconnectionLoad(interconn_dict)

	# SIM STEP 3: SET GENERATOR DISPATCH
	# ----------------------------------

	exports = 0.0 # kW
	losses = 0.0 # kW

	def fun_set_power_dispatch(object_load, object_generator, losses, exports):
		counter = 0
		lost_min = 10000000.0
		while True:
			need_reserves, actual_reserves, nominal_reserves_dict = grb_solvers.unit_commitment_priority_list(object_load, object_generator, losses, exports) # unit commitment is variable
			new_loss = run_OpenDSS(0, True)
			counter += 1

			if math.fabs(losses - new_loss) > 1.0:
				if counter > 199:
					print('Dispatcher - Losses/Exports did not converge')
					sys.exit()
				elif counter > 150:
					while True:
						object_generator.matrix[:, ODC.Generator.OPERATIONAL_STATUS] = dispatcher_max
						need_reserves, actual_reserves, nominal_reserves_dict = grb_solvers.unit_commitment_priority_list_2(object_load, object_generator, losses, exports) # unit commitment is input
						new_loss = run_OpenDSS(0, True)
						counter +=1

						if math.fabs(losses - new_loss) < 1.0:
							return need_reserves, actual_reserves, nominal_reserves_dict
						else:
							losses += 0.8 * (new_loss - losses)
				elif counter > 100:
					while True:
						object_generator.matrix[:, ODC.Generator.OPERATIONAL_STATUS] = dispatcher_min
						need_reserves, actual_reserves, nominal_reserves_dict = grb_solvers.unit_commitment_priority_list_2(object_load, object_generator, losses, exports) # unit commitment is input
						new_loss = run_OpenDSS(0, True)
						counter +=1

						if math.fabs(losses - new_loss) < 1.0:
							return need_reserves, actual_reserves, nominal_reserves_dict
						else:
							losses += 0.8 * (new_loss - losses)
				elif counter > 50:
					if math.fabs(new_loss) < math.fabs(lost_min):
						lost_min = new_loss
						dispatcher_min = np.array(object_generator.matrix[:, ODC.Generator.OPERATIONAL_STATUS], copy=True)
					else:
						dispatcher_max = np.array(object_generator.matrix[:, ODC.Generator.OPERATIONAL_STATUS], copy=True)
				losses += 0.8*(new_loss - losses)
			else:
				return need_reserves, actual_reserves, nominal_reserves_dict

	need_reserves, actual_reserves, nominal_reserves_dict = fun_set_power_dispatch(object_load, object_generator, losses, exports)
	for generator in object_generator.matrix:
		if generator[ODC.Generator.ID] in [101.0, 102.0, 201.0, 202.0]:
			pass
		else:
			if math.fabs(nominal_reserves_dict[generator[ODC.Generator.ID]]) > 1.0 and generator[ODC.Generator.OPERATIONAL_STATUS] == 0.0:
				print('*********************** YOU GOOFED *******************************')
	print('exports #1', 0.5 * (object_cable.matrix[33, ODC.Cable.REAL_POWER_2] - object_cable.matrix[33, ODC.Cable.REAL_POWER_1]))
	print('')

	# SIM STEP 4: SET JUNCTION INTERCONNECTIONS
	# -----------------------------------------

	# SIM STEP 5:
	# Set water
	# ----------------------------

	object_curve.matrix = np.array(base_curve_matrix, copy=True)
	object_junction.matrix = np.array(base_junction_matrix, copy=True)
	object_reservoir.matrix = np.array(base_reservoir_matrix, copy=True)
	object_tank.matrix = np.array(base_tank_matrix, copy=True)
	object_pipe.matrix = np.array(base_pipe_matrix, copy=True)
	object_pump.matrix = np.array(base_pump_matrix, copy=True)
	object_valve.matrix = np.array(base_valve_matrix, copy=True)
	object_pumpvalve.matrix = np.array(base_pumpvalve_matrix, copy=True)

	object_junction.setInterconnectionDemand(interconn_dict, nominal_reserves_dict)

	artificial_reservoir_id_shift = 1000.0
	max_groundwater_flow = 12399.0 # GPM
	groundwater_id_shift = 2000.0

	# Scale reservoir heads using water_df
	for reservoir in object_reservoir.matrix:
		if reservoir[ENC.Reservoir.ID] == 21.0:
			reservoir[ENC.Reservoir.TOTAL_HEAD] = max(reservoir[ENC.Reservoir.TOTAL_HEAD], 864.92*water_df + 817.08)
		elif reservoir[ENC.Reservoir.ID] == 22.0:
			reservoir[ENC.Reservoir.TOTAL_HEAD] = max(reservoir[ENC.Reservoir.TOTAL_HEAD], 951.11*water_df + 898.89)
		elif reservoir[ENC.Reservoir.ID] == 23.0:
			reservoir[ENC.Reservoir.TOTAL_HEAD] = max(reservoir[ENC.Reservoir.TOTAL_HEAD], 668.35*water_df + 631.65)

	groundwater_list = []
	map_to_groundwater_reservoir = {}
	map_to_groundwater_pipe = {}

	# Track real reservoirs
	for reservoir in object_reservoir.matrix:
		if reservoir[ENC.Reservoir.ID] >= 3000.0:
			groundwater_list.append(reservoir[ENC.Reservoir.ID])
			map_to_groundwater_reservoir[reservoir[ENC.Reservoir.ID]] = reservoir
			for pipe in object_pipe.matrix:
				if reservoir[ENC.Reservoir.ID] == pipe[ENC.Pipe.ID]:
					map_to_groundwater_pipe[reservoir[ENC.Reservoir.ID]] = pipe
		# WARNING THIS IS HARDCODED
		elif reservoir[ENC.Reservoir.ID] == 21.0:
			groundwater_list.append(reservoir[ENC.Reservoir.ID])
			map_to_groundwater_reservoir[reservoir[ENC.Reservoir.ID]] = reservoir
			for pipe in object_pipe.matrix:
				if pipe[ENC.Pipe.ID] == 4021.0:
					map_to_groundwater_pipe[reservoir[ENC.Reservoir.ID]] = pipe
		# WARNING THIS IS HARDCODED
		elif reservoir[ENC.Reservoir.ID] == 22.0:
			groundwater_list.append(reservoir[ENC.Reservoir.ID])
			map_to_groundwater_reservoir[reservoir[ENC.Reservoir.ID]] = reservoir
			for pipe in object_pipe.matrix:
				if pipe[ENC.Pipe.ID] == 1.0:
					map_to_groundwater_pipe[reservoir[ENC.Reservoir.ID]] = pipe
		# WARNING THIS IS HARDCODED
		elif reservoir[ENC.Reservoir.ID] == 23.0:
			groundwater_list.append(reservoir[ENC.Reservoir.ID])
			map_to_groundwater_reservoir[reservoir[ENC.Reservoir.ID]] = reservoir
			for pipe in object_pipe.matrix:
				if pipe[ENC.Pipe.ID] == 36.0:
					map_to_groundwater_pipe[reservoir[ENC.Reservoir.ID]] = pipe

	# Loop real reservoirs, turn off the ones with water inflow
	while len(groundwater_list) > 0:

		# initialize relevnt demand junctions
		demand_list = []
		map_to_junction = {}
		map_to_junction_groundwater = {}
		map_to_reservoir = {}
		map_to_pipe = {}

		# Track demand junctions
		for junction in object_junction.matrix:
			if junction[ENC.Junction.BASE_DEMAND_AVERAGE] + junction[ENC.Junction.INTERCONNECTION_DISPATCH_DEMAND] + junction[ENC.Junction.INTERCONNECTION_RESPONSE_DEMAND] > 0.0:
				demand_list.append(junction[ENC.Junction.ID])
		for junction in object_junction.matrix:
			if junction[ENC.Junction.ID] in demand_list:
				map_to_junction[junction[ENC.Junction.ID]] = junction
				found_junction_groundwater = 0
				for junction_groundwater in object_junction.matrix:
					if junction[ENC.Junction.ID] + groundwater_id_shift == junction_groundwater[ENC.Junction.ID]:
						map_to_junction_groundwater[junction[ENC.Junction.ID]] = junction_groundwater
						found_junction_groundwater = 1
				if found_junction_groundwater == 0:
					map_to_junction_groundwater[junction[ENC.Junction.ID]] = junction

		# Track artificial reservoirs
		for reservoir in object_reservoir.matrix:
			if reservoir[ENC.Reservoir.ID]-artificial_reservoir_id_shift in demand_list:
				map_to_reservoir[reservoir[ENC.Reservoir.ID]-artificial_reservoir_id_shift] = reservoir

		# Track pipes for artifical reservoirs
		for pipe in object_pipe.matrix:
			if pipe[ENC.Pipe.ID]-artificial_reservoir_id_shift in demand_list:
				map_to_pipe[pipe[ENC.Pipe.ID]-artificial_reservoir_id_shift] = pipe

		# Reset demand junction demands to 0
		for junction_id in demand_list:
			map_to_junction[junction_id][ENC.Junction.BASE_DEMAND] = 0.0

		# Begin EPANET pressure-driven analysis for artificial reservoirs
		while len(demand_list) > 0:

			# Close artifical reservoirs pipes
			for junction_id in demand_list:
				map_to_pipe[junction_id][ENC.Pipe.OPERATIONAL_STATUS] = 0.0

			# Set valve pressure loss to 0
			for valve in object_valve.matrix:
				valve[ENC.Valve.MODEL] = 2.0
				valve[ENC.Valve.SETTING] = 0.0
			run_EPANET()

			# Open demand junctions with positive pressure ratio
			# Can take multiple iterations
			pos_pres_bool = True
			while pos_pres_bool:
				pos_pres_bool = False
				max_pres_id = demand_list[0]
				for junction_id in demand_list:
					if max(map_to_junction[junction_id][ENC.Junction.PRESSURE], map_to_junction_groundwater[junction_id][ENC.Junction.PRESSURE]) > map_to_junction[max_pres_id][ENC.Junction.MIN_PRESSURE] and map_to_pipe[junction_id][ENC.Pipe.OPERATIONAL_STATUS] == 0.0:
						max_pres_id = junction_id
				# this uses the MINIMUM ALLOWABLE PRESSURE
				if max(map_to_junction[max_pres_id][ENC.Junction.PRESSURE], map_to_junction_groundwater[max_pres_id][ENC.Junction.PRESSURE]) > (map_to_junction[max_pres_id][ENC.Junction.MIN_PRESSURE] - 0.01) and map_to_pipe[max_pres_id][ENC.Pipe.OPERATIONAL_STATUS] == 0.0:
					map_to_pipe[max_pres_id][ENC.Pipe.OPERATIONAL_STATUS] = 1.0
					pos_pres_bool = True
				run_EPANET()

			# Set flow control valves to maximum amount of groundwater flow
			for valve in object_valve.matrix:
				valve[ENC.Valve.MODEL] = 3.0
				valve[ENC.Valve.SETTING] = max_groundwater_flow
			run_EPANET()

			# Close artifical reservoirs with inflows
			# Can take multiple iterations
			neg_dem_bool = True
			while neg_dem_bool:
				neg_dem_bool = False
				for junction_id in demand_list:
					if map_to_reservoir[junction_id][ENC.Reservoir.DEMAND] < 0.0:
						map_to_pipe[junction_id][ENC.Pipe.OPERATIONAL_STATUS] = 0.0
						neg_dem_bool = True
				run_EPANET()
			run_EPANET()

			# Set base_demand to maximum if possible
			pda_count = 0
			demand_list_copy = demand_list.copy()
			for junction_id in demand_list_copy:
				if map_to_reservoir[junction_id][ENC.Reservoir.DEMAND] >= water_df * map_to_junction[junction_id][ENC.Junction.BASE_DEMAND_AVERAGE] + map_to_junction[junction_id][ENC.Junction.INTERCONNECTION_DISPATCH_DEMAND] + map_to_junction[junction_id][ENC.Junction.INTERCONNECTION_RESPONSE_DEMAND]:
					map_to_junction[junction_id][ENC.Junction.BASE_DEMAND] = water_df * map_to_junction[junction_id][ENC.Junction.BASE_DEMAND_AVERAGE] + map_to_junction[junction_id][ENC.Junction.INTERCONNECTION_DISPATCH_DEMAND] + map_to_junction[junction_id][ENC.Junction.INTERCONNECTION_RESPONSE_DEMAND]
					map_to_pipe[junction_id][ENC.Pipe.OPERATIONAL_STATUS] = 0.0
					demand_list.remove(junction_id)
					pda_count += 1

			# Set base_demand to greater than 0 and less than maximum if there are no maximums
			if pda_count == 0:
				for junction_id in demand_list_copy:
					if map_to_reservoir[junction_id][ENC.Reservoir.DEMAND] >= -0.01:
						map_to_junction[junction_id][ENC.Junction.BASE_DEMAND] = map_to_reservoir[junction_id][ENC.Reservoir.DEMAND]
						map_to_pipe[junction_id][ENC.Pipe.OPERATIONAL_STATUS] = 0.0
						demand_list.remove(junction_id)
			# End inner loop
		run_EPANET()

		# Close real reservoirs with inflows if possible
		pda_count = 0
		groundwater_list_copy = groundwater_list.copy()
		for groundwater_id in groundwater_list_copy:
			if map_to_groundwater_reservoir[groundwater_id][ENC.Reservoir.DEMAND] > 0.0:
				map_to_groundwater_pipe[groundwater_id][ENC.Pipe.OPERATIONAL_STATUS] = 0.0
				groundwater_list.remove(groundwater_id)
				pda_count += 1

		# Delete real reservoirs from being tracked if no real reservoirs have inflows
		if pda_count == 0:
			for groundwater_id in groundwater_list_copy:
				groundwater_list.remove(groundwater_id)
		# End middle loop
	run_EPANET()

	# SIM STEP 6: RUN POWER-WATER SIMULATION
	# --------------------------------------

	genid_to_genobject = {}
	juncid_to_genid_water = {}
	reduced_reserves_dict = {}

	for generator in object_generator.matrix:
		genid_to_genobject[generator[ODC.Generator.ID]] = generator

	for junction in object_junction.matrix:
		juncid_to_genid_water[junction[ENC.Junction.ID]] = []
		for generator in object_generator.matrix:
			if junction[ENC.Junction.ID] == generator[ODC.Generator.JUNCTION_ID]:
				juncid_to_genid_water[junction[ENC.Junction.ID]].append((generator[ODC.Generator.ID], generator[ODC.Generator.WATER_CONSUMPTION]))

	for junction in object_junction.matrix:
		if junction[ENC.Junction.BASE_DEMAND_AVERAGE] + junction[ENC.Junction.INTERCONNECTION_DISPATCH_DEMAND] + junction[ENC.Junction.INTERCONNECTION_RESPONSE_DEMAND] > 0.0:
			# Water demand is met for nominal reserves
			if junction[ENC.Junction.BASE_DEMAND] >= junction[ENC.Junction.INTERCONNECTION_DISPATCH_DEMAND] + junction[ENC.Junction.INTERCONNECTION_RESPONSE_DEMAND]:
				for genid, _ in juncid_to_genid_water[junction[ENC.Junction.ID]]:
					reduced_reserves_dict[genid] = nominal_reserves_dict[genid]
			elif junction[ENC.Junction.BASE_DEMAND] <= junction[ENC.Junction.INTERCONNECTION_DISPATCH_DEMAND]:
				for genid, _ in juncid_to_genid_water[junction[ENC.Junction.ID]]:
					reduced_reserves_dict[genid] = 0.0
			elif junction[ENC.Junction.INTERCONNECTION_DISPATCH_DEMAND] < junction[ENC.Junction.BASE_DEMAND] < junction[ENC.Junction.INTERCONNECTION_DISPATCH_DEMAND] + junction[ENC.Junction.INTERCONNECTION_RESPONSE_DEMAND]:
				def getWaterConsumption(genid_genwater):
					return genid_genwater[1]

				demand_for_reserves = junction[ENC.Junction.INTERCONNECTION_DISPATCH_DEMAND] + junction[ENC.Junction.INTERCONNECTION_RESPONSE_DEMAND] - junction[ENC.Junction.BASE_DEMAND]
				for genid, genwater in sorted(juncid_to_genid_water[junction[ENC.Junction.ID]], key=getWaterConsumption, reverse=True):
					if demand_for_reserves > 0.0:
						if nominal_reserves_dict[genid] * genid_to_genobject[genid][ODC.Generator.WATER_CONSUMPTION] * 0.001 <= demand_for_reserves:
							reduced_reserves_dict[genid] = 0.0
							demand_for_reserves -= nominal_reserves_dict[genid] * genid_to_genobject[genid][ODC.Generator.WATER_CONSUMPTION] * 0.001
						else:
							fraction = 1.0 - (demand_for_reserves/(nominal_reserves_dict[genid]*0.001*genid_to_genobject[genid][ODC.Generator.WATER_CONSUMPTION]))
							reduced_reserves_dict[genid] = fraction * nominal_reserves_dict[genid]
							demand_for_reserves -= (nominal_reserves_dict[genid] - reduced_reserves_dict[genid]) * genid_to_genobject[genid][ODC.Generator.WATER_CONSUMPTION] * 0.001
					else:
						reduced_reserves_dict[genid] = nominal_reserves_dict[genid]

			else:
				print("ERROR IN CALCULATING REDUCED RESERVES!")

	nominal_reserves_list = []
	reduced_reserves_list = []
	for generator in object_generator.matrix:
		nominal_reserves_list.append(nominal_reserves_dict.get(generator[ODC.Generator.ID], 0.0))
		reduced_reserves_list.append(nominal_reserves_dict.get(generator[ODC.Generator.ID], 0.0) - reduced_reserves_dict.get(generator[ODC.Generator.ID], 0.0))

	with open('C:\\Users\\' + os_username + '\\Documents\\git\\RISE-power-water-ss-1phase\\model_outputs\\analysis_power_water\\power_water_pipe_n1_{}_{}_jid{}.csv'.format(int(pipe_fail_id), a_sens, int(junc_sens)), 'a', newline='') as file:
		writer = csv.writer(file)
		writer.writerow([water_df, power_df, need_reserves, actual_reserves, sum(reduced_reserves_dict.values())] + nominal_reserves_list + reduced_reserves_list)

	# POWER N-1 CONTINGENCY ANALYSIS
	# ------------------------------
	for row in object_generator.matrix:
		reduced_reserves_val = nominal_reserves_dict.get(row[ODC.Generator.ID], 0.0) - reduced_reserves_dict.get(row[ODC.Generator.ID], 0.0)
		if reduced_reserves_val > 0.001:
			row[ODC.Generator.REAL_GENERATION_MAX_RATING] = row[ODC.Generator.REAL_GENERATION] + reduced_reserves_dict.get(row[ODC.Generator.ID], 0.0)

	for row in object_generator.matrix:
		if row[ODC.Generator.REAL_GENERATION_MAX_RATING] < row[ODC.Generator.REAL_GENERATION_MIN_RATING]:
			row[ODC.Generator.OPERATIONAL_STATUS] = 0.0
			row[ODC.Generator.REAL_GENERATION] = 0.0
			row[ODC.Generator.REAL_GENERATION_MIN_RATING] = 0.0
			row[ODC.Generator.REAL_GENERATION_MAX_RATING] = 0.0

	base_gen_commitment = np.array(object_generator.matrix[:, ODC.Generator.OPERATIONAL_STATUS], copy=True)
	base_gen_dispatch = np.array(object_generator.matrix[:, ODC.Generator.REAL_GENERATION], copy=True)
	base_gen_dispatch_min = np.array(object_generator.matrix[:, ODC.Generator.REAL_GENERATION_MIN_RATING], copy=True)
	base_gen_dispatch_max = np.array(object_generator.matrix[:, ODC.Generator.REAL_GENERATION_MAX_RATING], copy=True)
	list_gen_mint = []

	base_branch_commitment = np.array(object_cable.matrix[:, ODC.Cable.OPERATIONAL_STATUS_A], copy=True)
	list_branch_mint = []

	print('Generators')
	for row in object_generator.matrix:
		object_generator.matrix[:, ODC.Generator.OPERATIONAL_STATUS] = np.array(base_gen_commitment, copy=True)
		object_generator.matrix[:, ODC.Generator.REAL_GENERATION] = np.array(base_gen_dispatch, copy=True)
		object_generator.matrix[:, ODC.Generator.REAL_GENERATION_MIN_RATING] = np.array(base_gen_dispatch_min, copy=True)
		object_generator.matrix[:, ODC.Generator.REAL_GENERATION_MAX_RATING] = np.array(base_gen_dispatch_max, copy=True)
		run_OpenDSS(0, True)

		if row[ODC.Generator.REAL_GENERATION] != 0.0 or row[ODC.Generator.ID] in [101.0, 102.0, 201.0, 202.0]:
			row[ODC.Generator.OPERATIONAL_STATUS] = 0.0
			row[ODC.Generator.REAL_GENERATION] = 0.0
			row[ODC.Generator.REAL_GENERATION_MIN_RATING] = 0.0
			row[ODC.Generator.REAL_GENERATION_MAX_RATING] = 0.0
			run_OpenDSS(0, True)
			try:
				list_gen_mint.append(grb_solvers.contingency_response(object_load, object_generator, object_cable))
			except:
				list_gen_mint.append(10000)
		else:
			list_gen_mint.append(0)

	print('Cables')
	for row in object_cable.matrix:
		object_generator.matrix[:, ODC.Generator.OPERATIONAL_STATUS] = np.array(base_gen_commitment, copy=True)
		object_generator.matrix[:, ODC.Generator.REAL_GENERATION] = np.array(base_gen_dispatch, copy=True)
		object_generator.matrix[:, ODC.Generator.REAL_GENERATION_MIN_RATING] = np.array(base_gen_dispatch_min, copy=True)
		object_generator.matrix[:, ODC.Generator.REAL_GENERATION_MAX_RATING] = np.array(base_gen_dispatch_max, copy=True)
		object_cable.matrix[:, ODC.Cable.OPERATIONAL_STATUS_A] = np.array(base_branch_commitment, copy=True)
		run_OpenDSS(0, True)

		if row[ODC.Cable.ID] not in [10.0, 100.0]:
			if row[ODC.Cable.OPERATIONAL_STATUS_A] == 1.0:
				row[ODC.Cable.OPERATIONAL_STATUS_A] = 0.0
				run_OpenDSS(0, True)
				try:
					list_branch_mint.append(grb_solvers.contingency_response(object_load, object_generator, object_cable))
				except:
					list_branch_mint.append(10000)
			else:
				list_branch_mint.append(0)

	object_cable.matrix[:, ODC.Cable.OPERATIONAL_STATUS_A] = np.array(base_branch_commitment, copy=True)

	print('')

	with open('C:\\Users\\' + os_username + '\\Documents\\git\\RISE-power-water-ss-1phase\\model_outputs\\analysis_power_water\\power_water_gen_response_n1_{}_{}_jid{}.csv'.format(int(pipe_fail_id), a_sens, int(junc_sens)), 'a', newline='') as file:
		writer = csv.writer(file)
		writer.writerow([water_df, power_df] + list_gen_mint)

	with open('C:\\Users\\' + os_username + '\\Documents\\git\\RISE-power-water-ss-1phase\\model_outputs\\analysis_power_water\\power_water_branch_response_n1_{}_{}_jid{}.csv'.format(int(pipe_fail_id), a_sens, int(junc_sens)), 'a', newline='') as file:
		writer = csv.writer(file)
		writer.writerow([water_df, power_df] + list_branch_mint)

	# Interconnections have no effect
	# input_list_continuous, input_list_categorical, output_list, input_tensor_continuous, input_tensor_categorical, output_tensor = run_OpenDSS(dss_debug, False)
	# input_list_continuous1, input_list_categorical1, output_list1, input_tensor_continuous1, input_tensor_categorical1, output_tensor1 = run_EPANET()
	# Interconnections have an effect
	# _, _, output_list, _, _, output_tensor = run_OpenDSS(dss_debug, False)
	# _, _, output_list1, _, _, output_tensor1 = run_EPANET()

	# RESULTS STEP 1: FORMAT INPUT/OUTPUT TENSORS
	# -------------------------------------------

	# input_list_continuous = input_list_continuous + input_list_continuous1
	# input_list_categorical = input_list_categorical + input_list_categorical1
	# output_list = output_list + output_list1

	# input_tensor_continuous = np.concatenate((input_tensor_continuous, input_tensor_continuous1), axis=0)
	# input_tensor_categorical = np.concatenate((input_tensor_categorical, input_tensor_categorical1), axis=0)
	# output_tensor = np.concatenate((output_tensor, output_tensor1), axis=0)

	# RESULTS STEP 2: WRITE INPUT/OUTPUT TENSORS TO FILE
	# --------------------------------------------------

	# if write_cols:
	# 	with open('C:/Users/'+os_username+'/Documents/git/RISE-power-water-ss-1phase/tensor_outputs/input_list_continuous_columns.csv', 'w') as f:
	# 		writer = csv.writer(f, delimiter=',')
	# 		writer.writerow(input_list_continuous)
	# 	with open('C:/Users/'+os_username+'/Documents/git/RISE-power-water-ss-1phase/tensor_outputs/input_list_categorical_columns.csv', 'w') as f:
	# 		writer = csv.writer(f, delimiter=',')
	# 		writer.writerow(input_list_categorical)
	# 	with open('C:/Users/'+os_username+'/Documents/git/RISE-power-water-ss-1phase/tensor_outputs/output_list_columns.csv', 'w') as f:
	# 		writer = csv.writer(f, delimiter=',')
	# 		writer.writerow(output_list)

	# with open('C:/Users/'+os_username+'/Documents/git/RISE-power-water-ss-1phase/tensor_outputs/input_tensor_continuous.csv', 'ab') as f:
	# 	np.savetxt(f, input_tensor_continuous[None, :], fmt='%0.6f', delimiter=' ', newline='\n')
	# with open('C:/Users/'+os_username+'/Documents/git/RISE-power-water-ss-1phase/tensor_outputs/input_tensor_categorical.csv', 'ab') as f:
	# 	np.savetxt(f, input_tensor_categorical[None, :], fmt='%0.6f', delimiter=' ', newline='\n')
	# with open('C:/Users/'+os_username+'/Documents/git/RISE-power-water-ss-1phase/tensor_outputs/output_tensor.csv', 'ab') as f:
	# 	np.savetxt(f, output_tensor[None, :], fmt='%0.6f', delimiter=' ', newline='\n')

	# END SIMULATION
	# --------------

if __name__ == '__main__':
	write_cols = False # Write column names to seperate file
	dss_debug = 0

	power_df = float(sys.argv[1])
	water_df = float(sys.argv[2])
	a_sens = float(sys.argv[3])
	pipe_fid = float(sys.argv[4])
	junc_sens = float(sys.argv[5])

	main(dss_debug, write_cols, power_df, water_df, a_sens, pipe_fid, junc_sens)


text:
using System;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Ignite.Features.Views
{
    public sealed partial class InkingView
    {
        public Symbol TouchWriting = (Symbol)0xED5F;
        public Symbol CalligraphyPen = (Symbol)0xEDFB;

        public InkingView()
        {
            InitializeComponent();
        }

        private void OnToggleTouch(object sender, RoutedEventArgs e)
        {
            Canvas.InkPresenter.InputDeviceTypes = TouchToggle.IsChecked ?? false
                ? CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Touch
                : CoreInputDeviceTypes.Pen;
        }

        private async void OnOpen(object sender, RoutedEventArgs e)
        {
            var fileOpenPicker = new FileOpenPicker();
            fileOpenPicker.FileTypeFilter.Add(".ink");

            var inputFile = await fileOpenPicker.PickSingleFileAsync();
            var inputStream = await inputFile.OpenSequentialReadAsync();

            await Canvas.InkPresenter.StrokeContainer.LoadAsync(inputStream);
        }

        private async void OnSave(object sender, RoutedEventArgs e)
        {
            var fileSavePicker = new FileSavePicker();
            fileSavePicker.FileTypeChoices.Add("Ink", new [] { ".ink" });

            var outputFile = await fileSavePicker.PickSaveFileAsync();
            var outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite);

            await Canvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);

            Canvas.InkPresenter.StrokeContainer.Clear();
        }
    }
}


text:
package com.hyh.plg.activity;

/**
 * Created by tangdongwei on 2018/9/17.
 */
public class LaunchMode {

    public static final String LAUNCH_MODE = "launch_mode";

    public static final int ANYWAY = 0;

    public static final int STANDARD = 1;

    public static final int SINGLE_INSTANCE = 4;

    public static final int PRIOR_SINGLE_INSTANCE = 5;

}


text:
PROJECT =spi_bb
LIBS =

include ../../../common_board.mk

ifeq ($(BOARD),msp430g2553in20)
include ../../../common.mk
else
include ../../../common_empty.mk
endif


text:
package com.chupacadabra.evolution;

import java.util.List;

/**
 * Selection policy.
 */
@FunctionalInterface
public interface SelectionPolicy {

    /**
     * Select the better candidate.
     *
     * @param state The current state.
     * @param randomSource A source of randomness.
     * @param a First candidate.
     * @param b Second candidate.
     * @return The better candidate.
     */
    public Candidate select(DifferentialEvolutionState state, RandomSource randomSource, Candidate a, Candidate b);

    /**
     * Select the best candidate.
     *
     * @param state The state.
     * @param randomSource Source of randomness.
     * @param candidates Candidate list.
     * @return The best candidate.
     */
    public default Candidate select(final DifferentialEvolutionState state, final RandomSource randomSource, final List<Candidate> candidates) {
        Candidate bestChild = candidates.get(0);

        // repeatedly apply the selection policy.
        for (int index = 1; index < candidates.size(); index++) {
            bestChild = select(state, randomSource, bestChild, candidates.get(index));
        }

        return bestChild;
    }

}