text:
package com.mkl.eu.service.service.service.impl;

import com.mkl.eu.client.common.exception.FunctionalException;
import com.mkl.eu.client.common.exception.TechnicalException;
import com.mkl.eu.client.service.service.ITablesService;
import com.mkl.eu.client.service.vo.ref.Referential;
import com.mkl.eu.client.service.vo.tables.Tables;
import com.mkl.eu.service.service.mapping.ref.ReferentialMapping;
import com.mkl.eu.service.service.mapping.tables.TablesMapping;
import com.mkl.eu.service.service.persistence.oe.ref.country.CountryEntity;
import com.mkl.eu.service.service.persistence.oe.tables.*;
import com.mkl.eu.service.service.persistence.ref.ICountryDao;
import com.mkl.eu.service.service.persistence.tables.ITablesDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Service for chat purpose.
 *
 * @author MKL.
 */
@Service
@Transactional(rollbackFor = {TechnicalException.class, FunctionalException.class})
public class TablesServiceImpl extends AbstractService implements ITablesService, ApplicationListener<ContextRefreshedEvent> {
    /** Tables DAO. */
    @Autowired
    private ITablesDao tablesDao;
    /** Country referential DAO. */
    @Autowired
    private ICountryDao countryDao;
    /** Tables Mapping. */
    @Autowired
    private TablesMapping tablesMapping;
    /** Referential Mapping. */
    @Autowired
    private ReferentialMapping referentialMapping;

    /** {@inheritDoc} */
    @Override
    public Tables getTables() {
        return super.getTables();
    }

    /** {@inheritDoc} */
    @Override
    public Referential getReferential() {
        return super.getReferential();
    }

    /** {@inheritDoc} */
    @Override
    public void refresh() {
        cacheData();
    }

    /** {@inheritDoc} */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        refresh();
    }

    protected void cacheData() {
        cacheTables();
        cacheReferential();
    }

    /**
     * Cache the tables.
     */
    protected void cacheTables() {
        TABLES = new Tables();

        Map<Class<?>, Map<Long, Object>> objectsCreated = new HashMap<>();

        List<PeriodEntity> periods = tablesDao.getPeriods();
        tablesMapping.fillPeriodsTables(periods, objectsCreated, TABLES);
        List<TradeIncomeEntity> tradeTables = tablesDao.readAll();
        tablesMapping.fillTradeIncomeTables(tradeTables, TABLES);
        List<TechEntity> techs = tablesDao.getTechs();
        tablesMapping.fillTechsTables(techs, objectsCreated, TABLES);
        List<BasicForceTableEntity> basicForces = tablesDao.getBasicForces();
        tablesMapping.fillBasicForcesTables(basicForces, objectsCreated, TABLES);
        List<UnitEntity> units = tablesDao.getUnits();
        tablesMapping.fillUnitsTables(units, objectsCreated, TABLES);
        List<LimitTableEntity> limits = tablesDao.getLimits();
        tablesMapping.fillLimitsTables(limits, objectsCreated, TABLES);
        List<ResultEntity> results = tablesDao.getResults();
        tablesMapping.fillResultsTables(results, TABLES);
        List<BattleTechEntity> battleTechs = tablesDao.getBattleTechs();
        tablesMapping.fillBattleTechTables(battleTechs, TABLES);
        List<CombatResultEntity> combatResults = tablesDao.getCombatResults();
        tablesMapping.fillCombatResultTables(combatResults, TABLES);
        List<ArmyClasseEntity> armyClasses = tablesDao.getArmyClasses();
        tablesMapping.fillArmyClasseTables(armyClasses, TABLES);
        List<ArmyArtilleryEntity> armyArtilleries = tablesDao.getArmyArtilleries();
        tablesMapping.fillArmyArtilleryTables(armyArtilleries, TABLES);
        List<ArtillerySiegeEntity> artillerySieges = tablesDao.getArtillerySieges();
        tablesMapping.fillArtillerySiegeTables(artillerySieges, TABLES);
        List<FortressResistanceEntity> fortressResistances = tablesDao.getFortressResistance();
        tablesMapping.fillFortressResistanceTables(fortressResistances, TABLES);
        List<AssaultResultEntity> assaultResults = tablesDao.getAssaultResults();
        tablesMapping.fillAssaultResultTables(assaultResults, TABLES);
        List<ExchequerEntity> exchequers = tablesDao.getExchequers();
        tablesMapping.fillExchequerTables(exchequers, TABLES);
        List<LeaderEntity> leaders = tablesDao.getLeaders();
        tablesMapping.fillLeadersTables(leaders, TABLES);

    }

    /**
     * Cache the referential.
     */
    protected void cacheReferential() {
        REFERENTIAL = new Referential();

        List<CountryEntity> countries = countryDao.readAll();
        referentialMapping.fillCountriesReferential(countries, REFERENTIAL);
    }
}


text:
Manages components that contain HTML, CSS, JavaScript, fonts or even image files.

```
$ npm install -g bower
$ bower install jquery --save
```

Dependencies are saved into the `bower_components` (customizable) and are listed in the `bower.json` file which is similar to the `package.json` file.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<meta charset='utf-8'>
<link href='../../../exports.css' rel='stylesheet'>
<link href='../../../exports.css' rel='stylesheet'>

xdamman's posterous

This is an archived post
This is an archived post

Previous

Index

Next

Third lesson day

February  8 2007, 10:56 PM
 by Xavier Damman

Today was y first light day.
With the agreement of Bonaventure, the rector of the university, I've reduced my charge to 6 hours a day.
And actually, I did almost 7 hours today since I've also reduced the Tea-break (which by the way has tea only in its name!) to 15 mn instead of half an hour and I've finished always later than what I should.
But still, it's incredible the difference between 7 hours a day, and 8 hours when you have to give class. I feel much more better after my day than the previous days.

During the morning I had only 12 students (the 9 of the third class are not attending anymore the database 1 class). We continued on the operation of the algebra on the relations. There are 3 students that have a much better level than the others. Hence, it's quite difficult for me to be manage them. They may think that I'm a bit too slow, but on the other hand, the others have really difficulties to understand the matter.

We stop at 11:20 instead of 12 (since I had to give them only 3 hours, instead of 4). But since we also reduced the T-break, at the end, it's was quite the same.

I've started the afternoon at 3 instead of 2. That way I can make a tiny nap. Just enough to be much more relaxed. Perfect.
I gave class till 6:10 with a reduced break too.
We continued the HTML introduction. I started the class by recording them what we do, and why we do it. Why HTML will be useful for them in order to achieve their project.
Since it's not the topic of the course, I've just limited this introduction to the things they really need to know.
So, today, we have just seen the lists and the forms.
In parallel, they have to finish their first report on their own project (one topic per group) by tomorrow. It consists of a description and a first version of the entity-relations graph. So tomorrow, we'll start to learn how to convert it to a relational graph. That way, next week we will be able to start implementing the database in MySQL. By the end of the week, I hope I will start the introduction to PHP and they will have all the tools to implement a real simple program that will interact with their own homemade database.
The afternoon passed very well. I wrote a lot on the black board and I felt very more and more comfortable with my way of giving class. And this is very important to me.

After the class, we, Bénédicte, Julien (both from France), Augustin (from the university) and I went to a bar on the side of the (small) water-pool of Ngozi. We had very good time. Then, we went back to the "Paroisse" for supper and once again, we got (free) beers and we had very nice chats.

At the end, it was a very pleasant day. A subtle balance between work and fun. A perfect day! :-)
It's only 22:56 and it's already time to sleep. Days begin very early over here.

16 views and 0 responses


text:
package edu.berkeley.nlp.sequence.stationary;

import java.util.Arrays;

import edu.berkeley.nlp.math.DoubleArrays;
import edu.berkeley.nlp.sequence.SequenceModel;
import fig.basic.NumUtils;

public class StationaryForwardBackward {

	boolean DEBUG = true;
	int MAX_LENGTH ;
	int numStates;
	double[][] alphas;
	double[][] betas;
	StationarySequenceModel seqModel;

	int obsLength;

	double normConstant ;

	double[][] nodePotentials;

	double[] alphaScalingFactors;
	double[] betaScalingFactors;

	double[][] edgePosteriors;
	double[][] nodePosteriors;

	int[][]  allowableForwardTransitions;
	int[][]  allowableBackwardTransitions;

	private final double[][] edgeForwardPotentials;
	private final double[][] edgeBackwardPotentials;

	public StationaryForwardBackward(StationarySequenceModel seqModel) {
		this.seqModel = seqModel;
		numStates = seqModel.getNumStates();
		MAX_LENGTH = seqModel.getMaximumSequenceLength();
		alphas = new double[MAX_LENGTH][numStates];
		betas = new double[MAX_LENGTH][numStates];

		alphaScalingFactors = new double[MAX_LENGTH];
		betaScalingFactors = new double[MAX_LENGTH];

		nodePotentials = new double[MAX_LENGTH][numStates];
		nodePosteriors = new double[MAX_LENGTH][numStates];

		allowableForwardTransitions = seqModel.getAllowableForwardTransitions();
		allowableBackwardTransitions = seqModel.getAllowableBackwardTransitions();

		edgeForwardPotentials = seqModel.getForwardEdgePotentials();
		edgeBackwardPotentials = seqModel.getBackwardEdgePotentials();

		edgePosteriors = new double[numStates][];
		for (int s=0; s < numStates; ++s) {
			edgePosteriors[s] = new double[allowableForwardTransitions[s].length];
		}
	}

	public void setInput(StationarySequenceInstance seqInstance) {
		setInput(seqInstance,false);
	}

	public void setInput(StationarySequenceInstance seqInstance, boolean viterbi) {
		assert seqInstance.getSequenceLength() < seqModel.getMaximumSequenceLength();
		this.obsLength = seqInstance.getSequenceLength();
		this.normConstant = 0.0;

		clearArrays();

		seqInstance.fillNodePotentials(nodePotentials);

		forwardPass();
		if (!viterbi) {
			backwardPass();
			computePosteriors();
		}

	}

	private void clearArrays() {
		for (int i=0; i < obsLength; ++i) {
			Arrays.fill(nodePotentials[i],0.0);
			Arrays.fill(nodePosteriors[i],0.0);
		}
		for (int i=0; i < numStates; ++i) {
			Arrays.fill(edgePosteriors[i],0.0);
		}
		Arrays.fill(alphaScalingFactors,0.0);
		Arrays.fill(betaScalingFactors,0.0);
	}

	// SCALING
	public static final double SCALE = Math.exp(100);
	public static final double LOG_SCALE = Math.log(SCALE);
	// Note: e^709 is the largest double java can handle.

	private static double getScaleFactor(double logScale) {
		if (logScale == 0.0) return 1.0;
		if (logScale == 1.0) return SCALE;
		if (logScale == 2.0) return SCALE * SCALE;
		if (logScale == 3.0) return SCALE * SCALE * SCALE;
		if (logScale == -1.0) return 1.0 / SCALE;
		if (logScale == -2.0) return 1.0 / SCALE / SCALE;
		if (logScale == -3.0) return 1.0 / SCALE / SCALE / SCALE;
		return Math.pow(SCALE, logScale);
	}

	public double getLogNormalizationConstant() {
		return normConstant;
	}

	public double[][] getNodeMarginals() {
		return nodePosteriors;
	}

	public double[][] getEdgeMarginalSums() {
		return edgePosteriors;
	}

	public int[] viterbiDecode() {
		int[][] backPointers = new int[obsLength][numStates];
		for (int pos=1; pos < obsLength; ++pos) {
			for (int state=0; state < numStates; ++state) {
				int argMax = -1;
				double max = Double.NEGATIVE_INFINITY;
				int[] beforeStates = allowableBackwardTransitions[state];
				for (int beforeStateIndex=0; beforeStateIndex < beforeStates.length; ++beforeStateIndex) {
					int beforeState = beforeStates[beforeStateIndex];
					double delta = alphas[pos-1][beforeState] * edgeBackwardPotentials[state][beforeStateIndex] * nodePotentials[pos][state];
					if (delta > max) {
						argMax = beforeState;
						max = delta;
					}
				}
				backPointers[pos][state] = argMax;
			}
		}

		int[] path = new int[obsLength];
		path[obsLength-1] = DoubleArrays.argMax(alphas[obsLength-1]);
		for (int i=obsLength-2; i >= 0; --i) {
			path[i] = backPointers[i+1][path[i+1]];
		}

		return path;
	}

	public int[] nodePosteriorDecode() {
		int[] path = new int[obsLength];
		for (int i=0; i < obsLength; ++i) {
			path[i] = DoubleArrays.argMax(nodePosteriors[i]);
		}
		return path;
	}

	private void forwardPass() {
		for (int pos=0; pos < obsLength; ++pos) {
			double max = Double.NEGATIVE_INFINITY;
			if (pos==0)  {
				for (int state=0; state < numStates; ++state) {
					alphas[pos][state] = nodePotentials[pos][state];
					if (alphas[pos][state] > max)  max = alphas[pos][state];
				}
			} else {
				for (int state=0; state < numStates; ++state) {
					double alpha = 0.0;
					if (nodePotentials[pos][state] > 0) {
						int[] beforeStates = allowableBackwardTransitions[state];
						for (int beforeStateIndex=0; beforeStateIndex < beforeStates.length; ++beforeStateIndex) {
							int beforeState = beforeStates[beforeStateIndex];
							alpha += alphas[pos-1][beforeState] * edgeBackwardPotentials[state][beforeStateIndex];
						}
						alpha *= nodePotentials[pos][state];
					}
					if (alpha > max) max = alpha;
					alphas[pos][state] = alpha;
				}
			}
			if (max == 0.0 || Double.isInfinite(max)) {
				throw new RuntimeException(String.format("The alphas[%d] has max=%.3f",pos,max));
			}

			//LOG SCALE
			int logScale = 0;
			double scale = 1.0;
			while (max > SCALE) {
				max /= SCALE;
				scale *= SCALE;
				logScale += 1;
			}
			while (max > 0.0 && max < 1.0 / SCALE) {
				max *= SCALE;
				scale /= SCALE;
				logScale -= 1;
			}
			if (logScale != 0) {
				for (int label=0; label < numStates; ++label) {
					alphas[pos][label] /= scale;
				}
			}
			if (pos ==0) {
				alphaScalingFactors[pos] = logScale;
			} else {
				alphaScalingFactors[pos] = alphaScalingFactors[pos-1] + logScale;
			}
		}

	}

	private void backwardPass() {

		for (int pos=obsLength-1; pos >= 0; --pos) {
			double max = 0.0;
			if (pos  == obsLength-1) {
				for (int label=0; label < numStates; ++label) {
					betas[pos][label] = nodePotentials[pos][label];
					if (betas[pos][label] > max) max = betas[pos][label];
				}
			} else {
				for (int state =0; state < numStates; ++state) {
					double beta = 0.0;
					if (nodePotentials[pos][state] > 0.0) {
						//Loop over following States
						int[] nextStates = allowableForwardTransitions[state];
						for (int nextStateIndex=0; nextStateIndex < nextStates.length; ++nextStateIndex) {
							int nextState = nextStates[nextStateIndex];
							beta +=  edgeForwardPotentials[state][nextStateIndex] * betas[pos+1][nextState];
						}
						beta *= nodePotentials[pos][state];
					}
					if (beta > max) max = beta;
					betas[pos][state] = beta;
				}
			}
			int logScale = 0;
			double scale = 1.0;
			while (max > SCALE) {
				max /= SCALE;
				scale *= SCALE;
				logScale += 1;
			}
			while (max > 0.0 && max < 1.0 / SCALE) {
				max *= SCALE;
				scale /= SCALE;
				logScale -= 1;
			}
			if (logScale != 0) {
				for (int label=0; label < numStates; ++label) {
					betas[pos][label] /= scale;
				}
			}
			if (pos == obsLength-1) {
				betaScalingFactors[pos] = logScale;
			}  else {
				betaScalingFactors[pos] = betaScalingFactors[pos+1] + logScale;
			}
		}
	}

	public double[][] getAlphas() {
		return alphas;
	}

	public double[][] getBetas () {
		return betas;
	}

	private void computePosteriors() {
		double z = DoubleArrays.add(alphas[obsLength-1]);
		double z_scale = alphaScalingFactors[obsLength-1];

		if (z == 0.0) { throw new RuntimeException("Forward-Backward: No non-zero label sequences"); };

		for (int i = 0; i+1 < obsLength; i++) {
			double[] cur_betas = betas[i+1];
			double beta_scale = betaScalingFactors[i+1];
			double alpha_scale = alphaScalingFactors[i];
			double posterior_scale = alpha_scale + beta_scale - z_scale;
			double exp_scale = getScaleFactor(posterior_scale);
			assert Math.abs(posterior_scale) <= 3.0 : "Exp scale is " + posterior_scale;
			for (int s = 0; s < numStates; s++) {
				int[] nextLabels = allowableForwardTransitions[s];
				double alpha_s = alphas[i][s];
				if (alpha_s == 0.0) continue;
				double nodeSum = 0.0;
				double x = alpha_s / z;
				for (int tIndex=0; tIndex < nextLabels.length; ++tIndex) {
					int t = nextLabels[tIndex];
					double beta_t = cur_betas[t];
					if (beta_t == 0.0) continue;
					double unscaled_posterior = x * edgeForwardPotentials[s][tIndex]  * beta_t ;
					double edgePosterior = unscaled_posterior * exp_scale;
					edgePosteriors[s][tIndex] += edgePosterior;
					nodeSum += edgePosterior;
				}
				nodePosteriors[i][s] = nodeSum;
			}
		}

		for (int t = 0; t < numStates; t++) {
			double alpha_t = alphas[obsLength-1][t];
			if (alpha_t == 0.0) continue;
			double beta_t = betas[obsLength-1][t];
			double beta_scale = betaScalingFactors[obsLength-1];
			double alpha_scale = alphaScalingFactors[obsLength-1];
			double unscaled_posterior = alpha_t * beta_t / (z * nodePotentials[obsLength-1][t]);
			double posterior_scale = alpha_scale  + beta_scale - z_scale;
			double exp_scale = getScaleFactor(posterior_scale);
			double nodePosterior = unscaled_posterior * exp_scale;
			nodePosteriors[obsLength-1][t] = nodePosterior;
		}
		normConstant = z_scale * LOG_SCALE + Math.log(z);

		if (DEBUG) {
			probCheck();
		}
	}

	private double relativeDiff(double a, double b) {
		double diff = Math.abs(a-b);
		return diff / Math.max(a, b);
	}

	@SuppressWarnings("unused")
	private void probCheck() {
		//Test Probability
		for (int pos=0; pos < obsLength; ++pos) {
			double nodeSum = 0.0;
			double edgeSum = 0.0;
			for (int l=0; l < nodePosteriors[pos].length; ++l) nodeSum += nodePosteriors[pos][l];
			if (relativeDiff(1.0, nodeSum) > 1.0e-2) {
				throw new RuntimeException("Node Sum: " + nodeSum + " not 1.0 for " + pos);
			}
		}
		double edgeSum = 0;
		for (int label=0; label < numStates; ++label) {
			int[] nextLabels = allowableForwardTransitions[label];
			for(int nextLabelIndex=0; nextLabelIndex < edgePosteriors[label].length; ++nextLabelIndex) {
				edgeSum += edgePosteriors[label][nextLabelIndex];
			}
		}

		if (relativeDiff(obsLength-1.0,edgeSum) > 1.0e-2) {
			throw new RuntimeException("Failed ProbCheck: Edge Sum: " + edgeSum + " for " + obsLength);
		}
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/politaktiv-map2-portlet.iml" filepath="$PROJECT_DIR$/politaktiv-map2-portlet.iml" />
    </modules>
  </component>
</project>


text:
<?php

/**
 * Credential form.
 *
 * @package    timehive
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class CredentialForm extends BaseCredentialForm
{
  public function configure()
  {
  }
}


text:
int main(int argc, char** argv) {
  ros::init(argc, argv, "rapid_robot_joint_state_reader");
  ros::NodeHandle nh;
  rapid::WaitForTime();
  rapid::JointStateReader reader;
  reader.Start();
  bool success = reader.WaitForMessages(ros::Duration(5));
  if (!success) {
    ROS_ERROR("Unable to read from /joint_states topic after 5 seconds!");
    return 1;
  }

  if (argc == 1) {
    std::cout << "Alternate usage: rosrun rapid_robot joint_state_reader "
                 "torso_lift_link LINK2 LINK3 ..."
              << std::endl;
    std::map<std::string, double> joint_values = reader.positions();
    for (std::map<std::string, double>::const_iterator it =
             joint_values.begin();
         it != joint_values.end(); ++it) {
      std::cout << it->first << "\t" << it->second << std::endl;
    }
  } else {
    for (int argi = 1; argi < argc; ++argi) {
      std::string name(argv[argi]);
      reader.WaitForJoint(name, ros::Duration(1));
      if (!reader.HasJoint(name)) {
        std::cout << name << " not found!" << std::endl;
      } else {
        std::cout << name << "\t" << reader.position(name) << std::endl;
      }
    }
  }

  return 0;
}


text:
// Copyright (c) Nate Barbettini.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
// Contains code modified from the ASP.NET Configuration project. Licensed under the Apache License, Version 2.0 from the .NET Foundation.

namespace FlexibleConfiguration.Abstractions
{
    /// <summary>
    /// Represents the root of an <see cref="IConfiguration"/> hierarchy.
    /// </summary>
    public interface IConfigurationRoot : IConfiguration
    {
    }
}


text:
FactoryGirl.define do
  factory :team do |f|
    f.name    {Faker::Team.name}
  end
end


text:
<?php

namespace Omnipay\PaypalRest\Message;

class UpdateCardRequest extends AbstractPaypalRequest
{
    /**
     * @return string
     */
    public function getEndpoint()
    {
        $this->validate('cardReference');

        return '/vault/credit-card/'.$this->getCardReference();
    }

    /**
     * @return string
     */
    public function getHttpMethod()
    {
        return 'PATCH';
    }

    /**
     * @param  mixed              $data
     * @return UpdateCardResponse
     */
    public function sendData($data)
    {
        $httpResponse = $this->sendHttpRequest($data);

        return $this->response = new UpdateCardResponse(
            $this,
            $httpResponse->json(),
            $httpResponse->getStatusCode()
        );
    }

    /**
     * @return array
     */
    public function getData()
    {
        $this->validate('card');
        $card = $this->getCard();

        $cardFields = array(
            'expire_month' => $card->getExpiryMonth(),
            'expire_year' => $card->getExpiryYear(),
            'first_name' => $card->getFirstName(),
            'last_name' => $card->getLastName(),
            'billing_address' => array(
                'line1' => $card->getAddress1(),
                'line2' => $card->getAddress2(),
                'city' => $card->getCity(),
                'state' => $card->getState(),
                'postal_code' => $card->getPostcode(),
                'country_code' => strtoupper($card->getCountry()),
            )
        );

        $data = array();

        foreach ($cardFields as $field => $value) {
            $data []= array(
                'path' => "/$field",
                'op' => 'add',
                'value' => $value
            );
        }

        return $data;
    }
}


text:
from functools import partial
from typing import Any, Dict
from bs4 import Tag
from pandas import DataFrame, concat
from lib.data_source import DataSource
from lib.cached_data_source import CachedDataSource
from lib.cast import safe_int_cast
from lib.concurrent import process_map
from lib.io import count_html_tables, read_html
from lib.utils import table_rename

def _html_cell_parser(cell: Tag, row_idx: int, col_idx: int):
    # Replace zero-width whitespace present in tables
    return cell.get_text().strip().replace(bytes("\u200b", encoding="utf8").decode(), "")

def _extract_tables(html_content) -> DataFrame:
    selector = "table.ms-rteTable-4"

    # Tables keep changing order, so iterate through all until one looks good
    table_count = count_html_tables(html_content, selector=selector)

    for table_index in range(table_count):
        yield read_html(
            html_content,
            header=True,
            selector=selector,
            parser=_html_cell_parser,
            table_index=table_index,
        )

def _process_html_file(file_map: Dict[str, str], date: str) -> Dict[str, Any]:
    records = []

    fname = file_map[date]
    with open(fname, "r") as fd:
        html_content = fd.read()

    # Make sure the tables are exactly what we expect
    age_groups = ["0-17", "18-34", "35-49", "50-64", "65-79", "80-"]
    tables = list(_extract_tables(html_content))[-6:]
    if len(tables) == len(age_groups):
        for age_group, table in zip(age_groups, tables):
            total = table.iloc[-1].to_dict()
            records.append(
                {
                    "key": "US_CA",
                    "date": date,
                    "age": age_group,
                    "total_confirmed": safe_int_cast(total.get("No. Cases")),
                    "total_deceased": safe_int_cast(total.get("No. Deaths")),
                }
            )

    return records

class CaliforniaCountiesOpenDataSource(DataSource):
    def parse_dataframes(
        self, dataframes: Dict[str, DataFrame], aux: Dict[str, DataFrame], **parse_opts
    ) -> DataFrame:
        data = table_rename(
            dataframes[0],
            {
                "date": "date",
                "area": "match_string",
                "area_type": "_agg_level",
                # "population": "",
                # "cases": "new_confirmed",
                # "cumulative_cases": "total_confirmed",
                # "deaths": "new_deceased",
                # "cumulative_deaths": "total_deceased",
                "total_tests": "new_tested",
                "cumulative_total_tests": "total_tested",
                # "positive_tests": "",
                # "cumulative_positive_tests": "",
                "reported_cases": "new_confirmed",
                "cumulative_reported_cases": "total_confirmed",
                "reported_deaths": "new_deceased",
                "cumulative_reported_deaths": "total_deceased",
            },
            drop=True,
        )
        state = data.loc[data["_agg_level"] == "State"].copy()
        counties = data.loc[data["_agg_level"] != "State"].copy()

        state["key"] = "US_CA"
        counties["subregion1_code"] = "CA"

        return concat([state, counties])

class CaliforniaByAgeOpenDataSource(DataSource):
    def parse_dataframes(
        self, dataframes: Dict[str, DataFrame], aux: Dict[str, DataFrame], **parse_opts
    ) -> DataFrame:
        data = table_rename(
            dataframes[0],
            {
                "report_date": "date",
                "demographic_category": "_strat_key",
                "demographic_value": "_strat_val",
                "total_cases": "total_confirmed",
                "deaths": "total_deceased",
            },
            drop=True,
        )
        data["key"] = "US_CA"
        data["date"] = data["date"].str.slice(0, 10)
        data = data[data["_strat_val"] != "Total"]

        data = data.loc[data["_strat_key"] == "Age Group"].rename(columns={"_strat_val": "age"})
        data["age"] = data["age"].str.lower()
        data["age"] = data["age"].str.replace("+", "-")
        data["age"] = data["age"].str.replace("unknown", "age_unknown")
        data["age"] = data["age"].str.replace("missing", "age_unknown")
        data["age"] = data["age"].str.replace("65 and older", "65-")

        return data

class CaliforniaBySexOpenDataSource(DataSource):
    def parse_dataframes(
        self, dataframes: Dict[str, DataFrame], aux: Dict[str, DataFrame], **parse_opts
    ) -> DataFrame:
        data = table_rename(
            dataframes[0],
            {
                "report_date": "date",
                "demographic_category": "_strat_key",
                "demographic_value": "_strat_val",
                "total_cases": "total_confirmed",
                "deaths": "total_deceased",
            },
            drop=True,
        )
        data["key"] = "US_CA"
        data["date"] = data["date"].str.slice(0, 10)
        data = data[data["_strat_val"] != "Total"]

        data = data.loc[data["_strat_key"] == "Gender"].rename(columns={"_strat_val": "sex"})
        data["sex"] = data["sex"].str.lower().replace("unknown", "sex_unknown")

        return data

class CaliforniaCachedDataSource(CachedDataSource):
    def parse(self, sources: Dict[str, str], aux: Dict[str, DataFrame], **parse_opts) -> DataFrame:
        file_map = sources["US_CA-mortality-stratified"]
        map_func = partial(_process_html_file, file_map)
        map_opts = dict(desc="Processing Cache Files", total=len(file_map))
        records = sum(process_map(map_func, file_map.keys(), **map_opts), [])
        assert len(records) > 0, "No records were found"
        return DataFrame.from_records(records)


text:
require 'chef/resource/package'
require 'chef/provider/package/ips'

class Chef
  class Resource
    class IpsPackage < ::Chef::Resource::Package

      provides :package, os: "solaris2"
      provides :ips_package, os: "solaris2"

      allowed_actions :install, :remove, :upgrade

      def initialize(name, run_context = nil)
        super(name, run_context)
        @accept_license = false
      end

      def accept_license(arg=nil)
        set_or_return(
          :purge,
          arg,
          kind_of: [ TrueClass, FalseClass ]
        )
      end
    end
  end
end


text:
package hygieia.transformer;

public class HygieiaConstants {
    public static final String FUNCTIONAL_TEST_DISPLAY = "Function Test";
    public static final String INTEGRATION_TEST_DISPLAY = "Integration Test";
    public static final String PERFORMANCE_TEST_DISPLAY = "Performance Test";
    public static final String UNIT_TEST_DISPLAY = "Unit Test";
    public static final String SECURITY_TEST_DISPLAY = "Security Test";
    public static final String REGRESSION_TEST_DISPLAY = "Regression Test";

    public static final String COLLECTOR_ITEM_DEPLOYMENT = "deployment";
}


text:
require 'spec_helper'

describe CouchrestModelElastic::River do
  let(:index_type) { 'TestModel' }
  let(:config) { {
    :couch_host => 'couch.host.com',
    :couch_port => '443',
    :couch_db => 'big_db',
    :couch_user => 'bigbird',
    :couch_password => 'topsecret',
    :couch_filter => 'Design/filter',
    :index => 'SomeIndex',
    :type => 'SomeType',
    :last_seq => rand(999999)
  } }
  let(:river) { described_class.new_with_defaults(index_type, config) }

  it 'updates with correct calls to client' do
    mock_client_response(:put, "/#{CouchrestModelElastic::River::RIVER_INDEX}/#{index_type}/#{CouchrestModelElastic::River::META_ID}") do |body|
      expect(body).to eq({
        'type' => CouchrestModelElastic::River::META_BODY_TYPE,
        'couchdb' => {
          'host' => config[:couch_host],
          'port' => config[:couch_port],
          'protocol' => 'https',
          'db' => config[:couch_db],
          'user' => config[:couch_user],
          'password' => config[:couch_password],
          'filter' => config[:couch_filter]
        },
        'index' => {
          'index' => config[:index],
          'type' => config[:type]
        }
      })
      [200, {}, '{}']
    end

    mock_client_response(:put, "/#{CouchrestModelElastic::River::RIVER_INDEX}/#{index_type}/#{CouchrestModelElastic::River::SEQ_ID}?op_type=create") do |body|
      expect(body).to eq({
        'couchdb' => {
          'last_seq' => config[:last_seq].to_s
        }
      })
      [200, {}, '{}']
    end

    river.update
    verify_mocked_responses
  end

  it '#fetch correctly instantiates river instance' do
    status = {'everything' => 'A OKAY'}
    mock_client_response(:get, "/#{CouchrestModelElastic::River::RIVER_INDEX}/#{index_type}/_search") do
      [200, {}, {'hits' => {'hits' => [
        {'_id' => CouchrestModelElastic::River::STATUS_ID, '_source' => status},
        {'_id' => CouchrestModelElastic::River::SEQ_ID, '_source' => {'couchdb' => {'last_seq' => config[:last_seq]}}},
        {'_id' => CouchrestModelElastic::River::META_ID, '_source' => {'couchdb' => {
          'host' => config[:couch_host],
          'port' => config[:couch_port],
          'filter' => config[:couch_filter],
          'db' => config[:couch_db],
        }}}
      ]}}.to_json]
    end

    river = described_class.fetch(index_type)
    expect(river.status).to eq(status)
    expect(river.last_seq).to eq(config[:last_seq])
    expect(river.config_index_type).to eq(index_type)
    expect(river.couch_db).to eq(config[:couch_db])
    expect(river.couch_host).to eq(config[:couch_host])
    expect(river.couch_port).to eq(config[:couch_port])
    expect(river.couch_filter).to eq(config[:couch_filter])
  end
end


text:
package swag.gui;

import java.io.Serializable;
import java.util.Date;
import java.util.logging.Logger;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@ViewScoped
public class ProgressManager implements Serializable {

	private static final long serialVersionUID = 1697584531644115473L;

	private static Logger log = Logger.getLogger("ProgressManager");

	@ManagedProperty("#{sessionManager}")
	private SessionManager sessionManager;

	public Long getProgress(Date start, Date end) {

		Date now = new Date();

		float total = end.getTime() - start.getTime();
		float done = now.getTime() - start.getTime();

		//log.info("TOTAL: " + total);
		//log.info("DONE: " + done);

		if (done <= total) {
			float tmp = (done / total) * 100;
			//log.info("PROGRESS: " + tmp);
			if (tmp >= 100) {
				onComplete();
				return Long.valueOf(100);
			}
			return Long.valueOf((int)tmp);
		} else {
			//log.info("PROGRESS: " + 100);
			onComplete();
			return Long.valueOf(100);
		}
	}

	public void onComplete() {
		sessionManager.reloadBase();
		sessionManager.reloadBaseSquare();
		// FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Progress Completed", null));
	}

	public SessionManager getSessionManager() {
		return sessionManager;
	}

	public void setSessionManager(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}

}


text:
<?php

/**
 * Signs data.
 *
 * @author Brian Eaton <beaton@google.com>
 */
abstract class IWP_google_Signer_Abstract
{
  /**
   * Signs data, returns the signature as binary data.
   */
  abstract public function sign($data);
}


text:
package com.sequenceiq.cloudbreak.job.stackpatcher;

import java.util.Collection;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.sequenceiq.cloudbreak.domain.converter.StackPatchTypeConverter;
import com.sequenceiq.cloudbreak.domain.stack.StackPatchType;
import com.sequenceiq.cloudbreak.service.stackpatch.ExistingStackPatchService;

@Service
public class ExistingStackPatcherServiceProvider {

    @Inject
    private Collection<ExistingStackPatchService> existingStackPatchServices;

    @Inject
    private StackPatchTypeConverter stackPatchTypeConverter;

    public ExistingStackPatchService provide(String stackPatchTypeName) throws UnknownStackPatchTypeException {
        StackPatchType stackPatchType = stackPatchTypeConverter.convertToEntityAttribute(stackPatchTypeName);
        if (stackPatchType == null || StackPatchType.UNKNOWN.equals(stackPatchType)) {
            throw new UnknownStackPatchTypeException(String.format("Stack patch type %s is unknown", stackPatchTypeName));
        }
        return provide(stackPatchType);
    }

    public ExistingStackPatchService provide(StackPatchType stackPatchType) throws UnknownStackPatchTypeException {
        return existingStackPatchServices.stream()
                .filter(existingStackPatchService -> stackPatchType.equals(existingStackPatchService.getStackPatchType()))
                .findFirst()
                .orElseThrow(() -> new UnknownStackPatchTypeException("No stack patcher implementation found for type " + stackPatchType));
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>ModuleProject</artifactId>
        <groupId>com.johnson</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>util</artifactId>
    <packaging>jar</packaging>

    <name>util</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
require 'spec_helper'

describe Revenant::Daemon do
  before do
    @task = Revenant::Task.new("daemonsignal")
    @task.stubs(:exit)
  end

  it "is registered as the :daemon plugin" do
    Revenant.plugins[:daemon].should == ::Revenant::Daemon
  end

  it "shuts down on SIGTERM" do
    pending
  end

  it "restarts on SIGUSR2" do
    pending
  end

  it "logs a stack trace on SIGUSR1" do
    pending
  end
end


text:
default_target: all

.PHONY : default_target

# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:

#=============================================================================
# Special targets provided by cmake.

# Disable implicit rules so canonical targets will work.
.SUFFIXES:

# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =

.SUFFIXES: .hpux_make_needs_suffix_list

# Suppress display of executed commands.
$(VERBOSE).SILENT:

# A target that is always out of date.
cmake_force:

.PHONY : cmake_force

#=============================================================================
# Set environment variables for the build.

# The shell in which to execute make rules.
SHELL = /bin/sh

# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake

# The command to remove a file.
RM = /usr/bin/cmake -E remove -f

# Escaping for special characters.
EQUALS = =

# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/arvr/Desktop/ViewAndTime

# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/arvr/Desktop/ViewAndTime/build

#=============================================================================
# Targets provided globally by CMake.

# Special rule for the target rebuild_cache
rebuild_cache:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
	/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache

# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache

.PHONY : rebuild_cache/fast

# Special rule for the target edit_cache
edit_cache:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..."
	/usr/bin/cmake-gui -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : edit_cache

# Special rule for the target edit_cache
edit_cache/fast: edit_cache

.PHONY : edit_cache/fast

# The main all target
all: cmake_check_build_system
	$(CMAKE_COMMAND) -E cmake_progress_start /home/arvr/Desktop/ViewAndTime/build/CMakeFiles /home/arvr/Desktop/ViewAndTime/build/CMakeFiles/progress.marks
	$(MAKE) -f CMakeFiles/Makefile2 all
	$(CMAKE_COMMAND) -E cmake_progress_start /home/arvr/Desktop/ViewAndTime/build/CMakeFiles 0
.PHONY : all

# The main clean target
clean:
	$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean

# The main clean target
clean/fast: clean

.PHONY : clean/fast

# Prepare targets for installation.
preinstall: all
	$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall

# Prepare targets for installation.
preinstall/fast:
	$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast

# clear depends
depend:
	$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend

#=============================================================================
# Target rules for targets named run

# Build rule for target.
run: cmake_check_build_system
	$(MAKE) -f CMakeFiles/Makefile2 run
.PHONY : run

# fast build rule for target.
run/fast:
	$(MAKE) -f CMakeFiles/run.dir/build.make CMakeFiles/run.dir/build
.PHONY : run/fast

#=============================================================================
# Target rules for targets named SLIC

# Build rule for target.
SLIC: cmake_check_build_system
	$(MAKE) -f CMakeFiles/Makefile2 SLIC
.PHONY : SLIC

# fast build rule for target.
SLIC/fast:
	$(MAKE) -f CMakeFiles/SLIC.dir/build.make CMakeFiles/SLIC.dir/build
.PHONY : SLIC/fast

src/SLIC/slic.o: src/SLIC/slic.cpp.o

.PHONY : src/SLIC/slic.o

# target to build an object file
src/SLIC/slic.cpp.o:
	$(MAKE) -f CMakeFiles/SLIC.dir/build.make CMakeFiles/SLIC.dir/src/SLIC/slic.cpp.o
.PHONY : src/SLIC/slic.cpp.o

src/SLIC/slic.i: src/SLIC/slic.cpp.i

.PHONY : src/SLIC/slic.i

# target to preprocess a source file
src/SLIC/slic.cpp.i:
	$(MAKE) -f CMakeFiles/SLIC.dir/build.make CMakeFiles/SLIC.dir/src/SLIC/slic.cpp.i
.PHONY : src/SLIC/slic.cpp.i

src/SLIC/slic.s: src/SLIC/slic.cpp.s

.PHONY : src/SLIC/slic.s

# target to generate assembly for a file
src/SLIC/slic.cpp.s:
	$(MAKE) -f CMakeFiles/SLIC.dir/build.make CMakeFiles/SLIC.dir/src/SLIC/slic.cpp.s
.PHONY : src/SLIC/slic.cpp.s

src/main.o: src/main.cpp.o

.PHONY : src/main.o

# target to build an object file
src/main.cpp.o:
	$(MAKE) -f CMakeFiles/run.dir/build.make CMakeFiles/run.dir/src/main.cpp.o
.PHONY : src/main.cpp.o

src/main.i: src/main.cpp.i

.PHONY : src/main.i

# target to preprocess a source file
src/main.cpp.i:
	$(MAKE) -f CMakeFiles/run.dir/build.make CMakeFiles/run.dir/src/main.cpp.i
.PHONY : src/main.cpp.i

src/main.s: src/main.cpp.s

.PHONY : src/main.s

# target to generate assembly for a file
src/main.cpp.s:
	$(MAKE) -f CMakeFiles/run.dir/build.make CMakeFiles/run.dir/src/main.cpp.s
.PHONY : src/main.cpp.s

# Help Target
help:
	@echo "The following are some of the valid targets for this Makefile:"
	@echo "... all (the default if no target is provided)"
	@echo "... clean"
	@echo "... depend"
	@echo "... rebuild_cache"
	@echo "... run"
	@echo "... edit_cache"
	@echo "... SLIC"
	@echo "... src/SLIC/slic.o"
	@echo "... src/SLIC/slic.i"
	@echo "... src/SLIC/slic.s"
	@echo "... src/main.o"
	@echo "... src/main.i"
	@echo "... src/main.s"
.PHONY : help

#=============================================================================
# Special targets to cleanup operation of make.

# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
	$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system


text:
{% extends "crud/form.html" %}
{% load i18n crispy_forms_tags %}

{% block extra_js %}
	<script language="JavaScript">
		tinymce.init({
			selector: 'textarea',
			theme: 'modern',
			plugins: [
				'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
				'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
				'save table contextmenu directionality emoticons template paste textcolor'
			],
			toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons'
		});
	</script>
{% endblock %}


text:
namespace rinfw {
namespace graphics {
namespace gpls {
class RS :
	public gplsi::IViewPort,
	public gplsi::IRasterizerState{
public:
	RS();
	RS(const RS &rs);
	RS(const RS &rs,bool viewport,bool rasterizerstate);

	void Release();
	bool setStatus();
	bool setStatus(ID3D11DeviceContext *context);
	bool getStatus();
	bool getStatus(ID3D11DeviceContext *context);
};
}
}
}


text:
function [hN,N] = UWB_convert_ct(h_ct, t, np, num_channels, ts)
% convert continuous-time channel model h_ct to N-times oversampled discrete-time samples
% h_ct, t, np, and num_channels are as specified in uwb_model
% ts is the desired time resolution
%
% hN will be produced with time resolution ts / N.
% It is up to the user to then apply any filtering and/or complex downconversion and then
% decimate by N to finally obtain an impulse response at time resolution ts.

%MIMO-OFDM Wireless Communications with MATLAB¢ç   Yong Soo Cho, Jaekwon Kim, Won Young Yang and Chung G. Kang
%?2010 John Wiley & Sons (Asia) Pte Ltd

min_Nfs = 100; % GHz
N = max(1, ceil(min_Nfs*ts) );  % N*fs = N/ts is the intermediate sampling frequency before decimation
N = 2^nextpow2(N); % make N a power of 2 to facilitate efficient multi-stage decimation

% NOTE: if we force N = 1 and ts = 0.167, the resulting channel hN will be identical to
% the results from earlier versions that did not use continuous-time.
Nfs = N/ts;
t_max = max(t(:));  % maximum time value across all channels
h_len = 1 + floor(t_max * Nfs);  % number of time samples at resolution ts / N
hN = zeros(h_len,num_channels);
for k = 1:num_channels
   np_k = np(k);  % number of paths in this channel
   t_Nfs = 1 + floor(t(1:np_k,k) * Nfs);  % vector of quantized time indices for this channel
   for n = 1:np_k
      hN(t_Nfs(n),k) = hN(t_Nfs(n),k) + h_ct(n,k);
   end
end


text:
// Filename: CartExtrapPhysBdryOp.cpp
// Created on 30 Sep 2006 by Boyce Griffith
//
// Copyright (c) 2002-2014, Boyce Griffith
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of The University of North Carolina nor the names of
//      its contributors may be used to endorse or promote products derived from
//      this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

/////////////////////////////// INCLUDES /////////////////////////////////////

#include <stdlib.h>
#include <ostream>
#include <set>
#include <string>
#include <utility>
#include <vector>

#include "BoundaryBox.h"
#include "Box.h"
#include "CellData.h"
#include "CellIndex.h"
#include "CellIterator.h"
#include "CellVariable.h"
#include "ComponentSelector.h"
#include "FaceData.h"
#include "FaceIndex.h"
#include "FaceIterator.h"
#include "FaceVariable.h"
#include "Index.h"
#include "IntVector.h"
#include "NodeData.h"
#include "NodeIndex.h"
#include "NodeIterator.h"
#include "NodeVariable.h"
#include "Patch.h"
#include "PatchGeometry.h"
#include "SideData.h"
#include "SideIndex.h"
#include "SideIterator.h"
#include "SideVariable.h"
#include "Variable.h"
#include "VariableDatabase.h"
#include "boost/array.hpp"
#include "ibtk/CartExtrapPhysBdryOp.h"
#include "ibtk/PhysicalBoundaryUtilities.h"
#include "ibtk/ibtk_utilities.h"
#include "ibtk/namespaces.h" // IWYU pragma: keep
#include "tbox/Array.h"
#include "tbox/Pointer.h"
#include "tbox/Utilities.h"

/////////////////////////////// NAMESPACE ////////////////////////////////////

namespace IBTK
{
/////////////////////////////// STATIC ///////////////////////////////////////

namespace
{
static const int REFINE_OP_STENCIL_WIDTH = 0;

template <typename D, typename I>
inline double
compute_linear_extrap(D& patch_data, const I& i, const I& i_intr, const IntVector<NDIM>& i_shft, const int depth)
{
    double ret_val = patch_data(i_intr, depth);
    for (unsigned int d = 0; d < NDIM; ++d)
    {
        if (i_shft(d) != 0)
        {
            const I& i_intr0 = i_intr;
            I i_intr1 = i_intr;
            i_intr1(d) += i_shft(d);

            const double& f0 = patch_data(i_intr0, depth);
            const double& f1 = patch_data(i_intr1, depth);

            const double du = f0 - f1;
            const double delta = std::abs(i(d) - i_intr(d));

            ret_val += du * delta;
        }
    }
    return ret_val;
} // compute_linear_extrap

template <typename D, typename I>
inline double compute_quadratic_extrap(D& patch_data,
                                       const I& i,
                                       const I& i_intr,
                                       const IntVector<NDIM>& i_shft,
                                       const int depth,
                                       const int codim)
{
    if (codim == 1)
    {
        for (unsigned int d = 0; d < NDIM; ++d)
        {
            if (i_shft(d) != 0)
            {
#if 1
                const I& i_intr0 = i_intr;

                I i_intr1 = i_intr;
                i_intr1(d) += i_shft(d);

                I i_intr2 = i_intr1;
                i_intr2(d) += i_shft(d);

                const double& f0 = patch_data(i_intr0, depth);
                const double& f1 = patch_data(i_intr1, depth);
                const double& f2 = patch_data(i_intr2, depth);

                const double x = std::abs(i(d) - i_intr(d));

                return (1.0 / 2.0 * f2 - f1 + 1.0 / 2.0 * f0) * x * x +
                       (-1.0 / 2.0 * f2 + 2.0 * f1 - 3.0 / 2.0 * f0) * x + f0;
#endif

#if 0
                // NOTE: The following only works in general for the case that
                // the ghost cell width is >= 3.
                const I& i_intr0 = i_intr;

                I i_intr2 = i_intr;
                i_intr2(d) += 2*i_shft(d);

                I i_intr3 = i_intr2;
                i_intr3(d) += i_shft(d);

                const double& f0 = patch_data(i_intr0,depth);
                const double& f2 = patch_data(i_intr2,depth);
                const double& f3 = patch_data(i_intr3,depth);

                const double x = std::abs(i(d)-i_intr(d));

                return (1.0/3.0*f3-1.0/2.0*f2+1.0/6.0*f0)*x*x+(-2.0/3.0*f3+3.0/2.0*f2-5.0/6.0*f0)*x+f0;
#endif
            }
        }
    }
    else
    {
        return compute_linear_extrap(patch_data, i, i_intr, i_shft, depth);
    }
    return 0.0; // this statement should not be reached
} // compute_quadratic_extrap
}

/////////////////////////////// PUBLIC ///////////////////////////////////////

CartExtrapPhysBdryOp::CartExtrapPhysBdryOp() : d_patch_data_indices(), d_extrap_type("NULL")
{
    // intentionally blank
    return;
} // CartExtrapPhysBdryOp

CartExtrapPhysBdryOp::CartExtrapPhysBdryOp(const int patch_data_index, const std::string& extrap_type)
    : d_patch_data_indices(), d_extrap_type("NULL")
{
    setPatchDataIndex(patch_data_index);
    setExtrapolationType(extrap_type);
    return;
} // CartExtrapPhysBdryOp

CartExtrapPhysBdryOp::CartExtrapPhysBdryOp(const std::set<int>& patch_data_indices, const std::string& extrap_type)
    : d_patch_data_indices(), d_extrap_type("NULL")
{
    setPatchDataIndices(patch_data_indices);
    setExtrapolationType(extrap_type);
    return;
} // CartExtrapPhysBdryOp

CartExtrapPhysBdryOp::CartExtrapPhysBdryOp(const ComponentSelector& patch_data_indices, const std::string& extrap_type)
    : d_patch_data_indices(), d_extrap_type("NULL")
{
    setPatchDataIndices(patch_data_indices);
    setExtrapolationType(extrap_type);
    return;
} // CartExtrapPhysBdryOp

CartExtrapPhysBdryOp::~CartExtrapPhysBdryOp()
{
    // intentionally blank
    return;
} // ~CartExtrapPhysBdryOp

void CartExtrapPhysBdryOp::setPatchDataIndex(const int patch_data_index)
{
    std::set<int> patch_data_indices;
    patch_data_indices.insert(patch_data_index);
    setPatchDataIndices(patch_data_indices);
    return;
} // setPatchDataIndex

void CartExtrapPhysBdryOp::setPatchDataIndices(const std::set<int>& patch_data_indices)
{
    d_patch_data_indices.clear();
    d_patch_data_indices = patch_data_indices;
    return;
} // setPatchDataIndices

void CartExtrapPhysBdryOp::setPatchDataIndices(const ComponentSelector& patch_data_indices)
{
    std::set<int> patch_data_index_set;
    for (int l = 0; l < patch_data_indices.getSize(); ++l)
    {
        if (patch_data_indices.isSet(l))
        {
            const int patch_data_index = l;
            patch_data_index_set.insert(patch_data_index);
        }
    }
    setPatchDataIndices(patch_data_index_set);
    return;
} // setPatchDataIndices

void CartExtrapPhysBdryOp::setExtrapolationType(const std::string& extrap_type)
{
    // Ensure that the extrapolation type is supported by this class.
    if (extrap_type != "CONSTANT" && extrap_type != "LINEAR" && extrap_type != "QUADRATIC")
    {
        TBOX_ERROR("CartExtrapPhysBdryOp::setExtrapolationType():\n"
                   << "  unknown extrapolation type: " << extrap_type << "\n"
                   << "  valid selections are: CONSTANT, LINEAR, or QUADRATIC" << std::endl);
    }

    if (extrap_type == "QUADRATIC")
    {
        IBTK_DO_ONCE(TBOX_WARNING("CartExtrapPhysBdryOp::setExtrapolationType():\n"
                                  << "  extrapolation type " << extrap_type
                                  << " generally requires large ghost cell widths" << std::endl););
    }

    d_extrap_type = extrap_type;
    return;
} // setExtrapolationType

void CartExtrapPhysBdryOp::setPhysicalBoundaryConditions(Patch<NDIM>& patch,
                                                         const double /*fill_time*/,
                                                         const IntVector<NDIM>& ghost_width_to_fill)
{
    if (ghost_width_to_fill == IntVector<NDIM>(0)) return;

    Pointer<PatchGeometry<NDIM> > pgeom = patch.getPatchGeometry();
    const Box<NDIM>& patch_box = patch.getBox();

    std::vector<std::pair<Box<NDIM>, std::pair<int, int> > > bdry_fill_boxes;

#if (NDIM > 1)
#if (NDIM > 2)
    // Compute the co-dimension three boundary fill boxes.
    const Array<BoundaryBox<NDIM> > physical_codim3_boxes =
        PhysicalBoundaryUtilities::getPhysicalBoundaryCodim3Boxes(patch);
    const int n_physical_codim3_boxes = physical_codim3_boxes.size();
    for (int n = 0; n < n_physical_codim3_boxes; ++n)
    {
        const BoundaryBox<NDIM>& bdry_box = physical_codim3_boxes[n];
        const Box<NDIM> bdry_fill_box = pgeom->getBoundaryFillBox(bdry_box, patch_box, ghost_width_to_fill);
        const unsigned int location_index = bdry_box.getLocationIndex();
        const int codim = 3;
        bdry_fill_boxes.push_back(std::make_pair(bdry_fill_box, std::make_pair(location_index, codim)));
    }
#endif
    // Compute the co-dimension two boundary fill boxes.
    const Array<BoundaryBox<NDIM> > physical_codim2_boxes =
        PhysicalBoundaryUtilities::getPhysicalBoundaryCodim2Boxes(patch);
    const int n_physical_codim2_boxes = physical_codim2_boxes.size();
    for (int n = 0; n < n_physical_codim2_boxes; ++n)
    {
        const BoundaryBox<NDIM>& bdry_box = physical_codim2_boxes[n];
        const Box<NDIM> bdry_fill_box = pgeom->getBoundaryFillBox(bdry_box, patch_box, ghost_width_to_fill);
        const unsigned int location_index = bdry_box.getLocationIndex();
        const int codim = 2;
        bdry_fill_boxes.push_back(std::make_pair(bdry_fill_box, std::make_pair(location_index, codim)));
    }
#endif
    // Compute the co-dimension one boundary fill boxes.
    const Array<BoundaryBox<NDIM> > physical_codim1_boxes =
        PhysicalBoundaryUtilities::getPhysicalBoundaryCodim1Boxes(patch);
    const int n_physical_codim1_boxes = physical_codim1_boxes.size();
    for (int n = 0; n < n_physical_codim1_boxes; ++n)
    {
        const BoundaryBox<NDIM>& bdry_box = physical_codim1_boxes[n];
        const Box<NDIM> bdry_fill_box = pgeom->getBoundaryFillBox(bdry_box, patch_box, ghost_width_to_fill);
        const unsigned int location_index = bdry_box.getLocationIndex();
        const int codim = 1;
        bdry_fill_boxes.push_back(std::make_pair(bdry_fill_box, std::make_pair(location_index, codim)));
    }

    // Set the boundary values.
    setPhysicalBoundaryConditions_cell(patch, bdry_fill_boxes);
    setPhysicalBoundaryConditions_face(patch, bdry_fill_boxes);
    setPhysicalBoundaryConditions_node(patch, bdry_fill_boxes);
    setPhysicalBoundaryConditions_side(patch, bdry_fill_boxes);
    return;
} // setPhysicalBoundaryConditions

IntVector<NDIM> CartExtrapPhysBdryOp::getRefineOpStencilWidth() const
{
    return REFINE_OP_STENCIL_WIDTH;
} // getRefineOpStencilWidth

void CartExtrapPhysBdryOp::preprocessRefine(Patch<NDIM>& /*fine*/,
                                            const Patch<NDIM>& /*coarse*/,
                                            const Box<NDIM>& /*fine_box*/,
                                            const IntVector<NDIM>& /*ratio*/)
{
    // intentionally blank
    return;
} // preprocessRefine

void CartExtrapPhysBdryOp::postprocessRefine(Patch<NDIM>& /*fine*/,
                                             const Patch<NDIM>& /*coarse*/,
                                             const Box<NDIM>& /*fine_box*/,
                                             const IntVector<NDIM>& /*ratio*/)
{
    // intentionally blank
    return;
} // postprocessRefine

/////////////////////////////// PROTECTED ////////////////////////////////////

/////////////////////////////// PRIVATE //////////////////////////////////////

void CartExtrapPhysBdryOp::setPhysicalBoundaryConditions_cell(
    Patch<NDIM>& patch,
    const std::vector<std::pair<Box<NDIM>, std::pair<int, int> > >& bdry_fill_boxes)
{
    const Box<NDIM>& patch_box = patch.getBox();
    const Index<NDIM>& patch_lower = patch_box.lower();
    const Index<NDIM>& patch_upper = patch_box.upper();

    const int extrap_type =
        (d_extrap_type == "CONSTANT" ? 0 : (d_extrap_type == "LINEAR" ? 1 : (d_extrap_type == "QUADRATIC" ? 2 : -1)));
    if (extrap_type != 0 && extrap_type != 1 && extrap_type != 2)
    {
        TBOX_ERROR("CartExtrapPhysBdryOp::setPhysicalBoundaryConditions():\n"
                   << "  unknown extrapolation type: " << d_extrap_type << "\n"
                   << "  valid selections are: CONSTANT, LINEAR, or QUADRATIC" << std::endl);
    }

    // Set the physical boundary conditions for the specified patch data
    // indices.
    for (std::set<int>::const_iterator cit = d_patch_data_indices.begin(); cit != d_patch_data_indices.end(); ++cit)
    {
        const int patch_data_idx = (*cit);
        VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
        Pointer<Variable<NDIM> > var;
        var_db->mapIndexToVariable(patch_data_idx, var);
        Pointer<CellVariable<NDIM, double> > cc_var = var;
        if (!cc_var) continue;

        Pointer<CellData<NDIM, double> > patch_data = patch.getPatchData(patch_data_idx);
        const Box<NDIM>& ghost_box = patch_data->getGhostBox();

        // Loop over the boundary fill boxes and extrapolate the data.
        for (std::vector<std::pair<Box<NDIM>, std::pair<int, int> > >::const_iterator it = bdry_fill_boxes.begin();
             it != bdry_fill_boxes.end();
             ++it)
        {
            const Box<NDIM>& bdry_fill_box = it->first;
            const unsigned int location_index = it->second.first;
            const int codim = it->second.second;
#if (NDIM == 2)
            const boost::array<bool, NDIM> is_lower = { { PhysicalBoundaryUtilities::isLower(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isLower(
                                                              location_index, codim, 1) } };
            const boost::array<bool, NDIM> is_upper = { { PhysicalBoundaryUtilities::isUpper(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isUpper(
                                                              location_index, codim, 1) } };
#endif
#if (NDIM == 3)
            const boost::array<bool, NDIM> is_lower = { { PhysicalBoundaryUtilities::isLower(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isLower(location_index, codim, 1),
                                                          PhysicalBoundaryUtilities::isLower(
                                                              location_index, codim, 2) } };
            const boost::array<bool, NDIM> is_upper = { { PhysicalBoundaryUtilities::isUpper(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isUpper(location_index, codim, 1),
                                                          PhysicalBoundaryUtilities::isUpper(
                                                              location_index, codim, 2) } };
#endif
            // Loop over the boundary box indices and compute the nearest
            // interior index.
            for (int depth = 0; depth < patch_data->getDepth(); ++depth)
            {
                for (CellIterator<NDIM> b(bdry_fill_box * ghost_box); b; b++)
                {
                    const CellIndex<NDIM>& i = b();
                    CellIndex<NDIM> i_intr = i;
                    IntVector<NDIM> i_shft = 0;
                    for (unsigned int d = 0; d < NDIM; ++d)
                    {
                        if (is_lower[d])
                        {
                            i_intr(d) = patch_lower(d);
                            i_shft(d) = +1; // use interior data for extrapolation
                        }
                        else if (is_upper[d])
                        {
                            i_intr(d) = patch_upper(d);
                            i_shft(d) = -1; // use interior data for extrapolation
                        }
                    }

                    // Perform constant, linear, or quadratic extrapolation.
                    switch (extrap_type)
                    {
                    case 0:
                        (*patch_data)(i, depth) = (*patch_data)(i_intr, depth);
                        break;
                    case 1:
                        (*patch_data)(i, depth) = compute_linear_extrap(*patch_data, i, i_intr, i_shft, depth);
                        break;
                    case 2:
                        (*patch_data)(i, depth) =
                            compute_quadratic_extrap(*patch_data, i, i_intr, i_shft, depth, codim);
                        break;
                    }
                }
            }
        }
    }
    return;
} // setPhysicalBoundaryConditions_cell

void CartExtrapPhysBdryOp::setPhysicalBoundaryConditions_face(
    Patch<NDIM>& patch,
    const std::vector<std::pair<Box<NDIM>, std::pair<int, int> > >& bdry_fill_boxes)
{
    const Box<NDIM>& patch_box = patch.getBox();
    const Index<NDIM>& patch_lower = patch_box.lower();
    const Index<NDIM>& patch_upper = patch_box.upper();

    const int extrap_type =
        (d_extrap_type == "CONSTANT" ? 0 : (d_extrap_type == "LINEAR" ? 1 : (d_extrap_type == "QUADRATIC" ? 2 : -1)));
    if (extrap_type != 0 && extrap_type != 1 && extrap_type != 2)
    {
        TBOX_ERROR("CartExtrapPhysBdryOp::setPhysicalBoundaryConditions():\n"
                   << "  unknown extrapolation type: " << d_extrap_type << "\n"
                   << "  valid selections are: CONSTANT, LINEAR, or QUADRATIC" << std::endl);
    }

    // Set the physical boundary conditions for the specified patch data
    // indices.
    for (std::set<int>::const_iterator cit = d_patch_data_indices.begin(); cit != d_patch_data_indices.end(); ++cit)
    {
        const int patch_data_idx = (*cit);
        VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
        Pointer<Variable<NDIM> > var;
        var_db->mapIndexToVariable(patch_data_idx, var);
        Pointer<FaceVariable<NDIM, double> > fc_var = var;
        if (!fc_var) continue;
        Pointer<FaceData<NDIM, double> > patch_data = patch.getPatchData(patch_data_idx);
        const Box<NDIM>& ghost_box = patch_data->getGhostBox();

        // Loop over the boundary fill boxes and extrapolate the data.
        for (std::vector<std::pair<Box<NDIM>, std::pair<int, int> > >::const_iterator it = bdry_fill_boxes.begin();
             it != bdry_fill_boxes.end();
             ++it)
        {
            const Box<NDIM>& bdry_fill_box = it->first;
            const unsigned int location_index = it->second.first;
            const int codim = it->second.second;
#if (NDIM == 2)
            const boost::array<bool, NDIM> is_lower = { { PhysicalBoundaryUtilities::isLower(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isLower(
                                                              location_index, codim, 1) } };
            const boost::array<bool, NDIM> is_upper = { { PhysicalBoundaryUtilities::isUpper(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isUpper(
                                                              location_index, codim, 1) } };
#endif
#if (NDIM == 3)
            const boost::array<bool, NDIM> is_lower = { { PhysicalBoundaryUtilities::isLower(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isLower(location_index, codim, 1),
                                                          PhysicalBoundaryUtilities::isLower(
                                                              location_index, codim, 2) } };
            const boost::array<bool, NDIM> is_upper = { { PhysicalBoundaryUtilities::isUpper(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isUpper(location_index, codim, 1),
                                                          PhysicalBoundaryUtilities::isUpper(
                                                              location_index, codim, 2) } };
#endif
            for (int depth = 0; depth < patch_data->getDepth(); ++depth)
            {
                for (unsigned int axis = 0; axis < NDIM; ++axis)
                {
                    for (FaceIterator<NDIM> b(bdry_fill_box * ghost_box, axis); b; b++)
                    {
                        const FaceIndex<NDIM> i = b();
                        FaceIndex<NDIM> i_bdry = i;
                        IntVector<NDIM> i_shft = 0;
                        for (unsigned int d = 0; d < NDIM; ++d)
                        {
                            if (is_lower[d])
                            {
                                i_bdry((NDIM - axis + d) % NDIM) = patch_lower(d);
                                i_shft((NDIM - axis + d) % NDIM) = +1; // use interior data for extrapolation
                            }
                            else if (is_upper[d])
                            {
                                if (axis != d)
                                {
                                    i_bdry((NDIM - axis + d) % NDIM) = patch_upper(d);
                                }
                                else
                                {
                                    i_bdry((NDIM - axis + d) % NDIM) = patch_upper(d) + 1;
                                }
                                i_shft((NDIM - axis + d) % NDIM) = -1; // use interior data for extrapolation
                            }
                        }

                        // Perform constant, linear, or quadratic extrapolation.
                        switch (extrap_type)
                        {
                        case 0:
                            (*patch_data)(i, depth) = (*patch_data)(i_bdry, depth);
                            break;
                        case 1:
                            (*patch_data)(i, depth) = compute_linear_extrap(*patch_data, i, i_bdry, i_shft, depth);
                            break;
                        case 2:
                            (*patch_data)(i, depth) =
                                compute_quadratic_extrap(*patch_data, i, i_bdry, i_shft, depth, codim);
                            break;
                        }
                    }
                }
            }
        }
    }
    return;
} // setPhysicalBoundaryConditions_face

void CartExtrapPhysBdryOp::setPhysicalBoundaryConditions_node(
    Patch<NDIM>& patch,
    const std::vector<std::pair<Box<NDIM>, std::pair<int, int> > >& bdry_fill_boxes)
{
    const Box<NDIM>& patch_box = patch.getBox();
    const Index<NDIM>& patch_lower = patch_box.lower();
    const Index<NDIM>& patch_upper = patch_box.upper();

    const int extrap_type =
        (d_extrap_type == "CONSTANT" ? 0 : (d_extrap_type == "LINEAR" ? 1 : (d_extrap_type == "QUADRATIC" ? 2 : -1)));
    if (extrap_type != 0 && extrap_type != 1 && extrap_type != 2)
    {
        TBOX_ERROR("CartExtrapPhysBdryOp::setPhysicalBoundaryConditions():\n"
                   << "  unknown extrapolation type: " << d_extrap_type << "\n"
                   << "  valid selections are: CONSTANT, LINEAR, or QUADRATIC" << std::endl);
    }

    // Set the physical boundary conditions for the specified patch data
    // indices.
    for (std::set<int>::const_iterator cit = d_patch_data_indices.begin(); cit != d_patch_data_indices.end(); ++cit)
    {
        const int patch_data_idx = (*cit);
        VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
        Pointer<Variable<NDIM> > var;
        var_db->mapIndexToVariable(patch_data_idx, var);
        Pointer<NodeVariable<NDIM, double> > nc_var = var;
        if (!nc_var) continue;
        Pointer<NodeData<NDIM, double> > patch_data = patch.getPatchData(patch_data_idx);
        const Box<NDIM>& ghost_box = patch_data->getGhostBox();

        // Loop over the boundary fill boxes and extrapolate the data.
        for (std::vector<std::pair<Box<NDIM>, std::pair<int, int> > >::const_iterator it = bdry_fill_boxes.begin();
             it != bdry_fill_boxes.end();
             ++it)
        {
            const Box<NDIM>& bdry_fill_box = it->first;
            const unsigned int location_index = it->second.first;
            const int codim = it->second.second;
#if (NDIM == 2)
            const boost::array<bool, NDIM> is_lower = { { PhysicalBoundaryUtilities::isLower(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isLower(
                                                              location_index, codim, 1) } };
            const boost::array<bool, NDIM> is_upper = { { PhysicalBoundaryUtilities::isUpper(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isUpper(
                                                              location_index, codim, 1) } };
#endif
#if (NDIM == 3)
            const boost::array<bool, NDIM> is_lower = { { PhysicalBoundaryUtilities::isLower(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isLower(location_index, codim, 1),
                                                          PhysicalBoundaryUtilities::isLower(
                                                              location_index, codim, 2) } };
            const boost::array<bool, NDIM> is_upper = { { PhysicalBoundaryUtilities::isUpper(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isUpper(location_index, codim, 1),
                                                          PhysicalBoundaryUtilities::isUpper(
                                                              location_index, codim, 2) } };
#endif
            // Loop over the boundary box indices and compute the
            // nearest interior index.
            for (int depth = 0; depth < patch_data->getDepth(); ++depth)
            {
                for (NodeIterator<NDIM> b(bdry_fill_box * ghost_box); b; b++)
                {
                    const NodeIndex<NDIM>& i = b();
                    NodeIndex<NDIM> i_bdry = i;
                    IntVector<NDIM> i_shft = 0;
                    for (unsigned int d = 0; d < NDIM; ++d)
                    {
                        if (is_lower[d])
                        {
                            i_bdry(d) = patch_lower(d);
                            i_shft(d) = +1; // use interior data for extrapolation
                        }
                        else if (is_upper[d])
                        {
                            i_bdry(d) = patch_upper(d) + 1;
                            i_shft(d) = -1; // use interior data for extrapolation
                        }
                    }

                    // Perform constant, linear, or quadratic extrapolation.
                    switch (extrap_type)
                    {
                    case 0:
                        (*patch_data)(i, depth) = (*patch_data)(i_bdry, depth);
                        break;
                    case 1:
                        (*patch_data)(i, depth) = compute_linear_extrap(*patch_data, i, i_bdry, i_shft, depth);
                        break;
                    case 2:
                        (*patch_data)(i, depth) =
                            compute_quadratic_extrap(*patch_data, i, i_bdry, i_shft, depth, codim);
                        break;
                    }
                }
            }
        }
    }
    return;
} // setPhysicalBoundaryConditions_node

void CartExtrapPhysBdryOp::setPhysicalBoundaryConditions_side(
    Patch<NDIM>& patch,
    const std::vector<std::pair<Box<NDIM>, std::pair<int, int> > >& bdry_fill_boxes)
{
    const Box<NDIM>& patch_box = patch.getBox();
    const Index<NDIM>& patch_lower = patch_box.lower();
    const Index<NDIM>& patch_upper = patch_box.upper();

    const int extrap_type =
        (d_extrap_type == "CONSTANT" ? 0 : (d_extrap_type == "LINEAR" ? 1 : (d_extrap_type == "QUADRATIC" ? 2 : -1)));
    if (extrap_type != 0 && extrap_type != 1 && extrap_type != 2)
    {
        TBOX_ERROR("CartExtrapPhysBdryOp::setPhysicalBoundaryConditions():\n"
                   << "  unknown extrapolation type: " << d_extrap_type << "\n"
                   << "  valid selections are: CONSTANT, LINEAR, or QUADRATIC" << std::endl);
    }

    // Set the physical boundary conditions for the specified patch data
    // indices.
    for (std::set<int>::const_iterator cit = d_patch_data_indices.begin(); cit != d_patch_data_indices.end(); ++cit)
    {
        const int patch_data_idx = (*cit);
        VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
        Pointer<Variable<NDIM> > var;
        var_db->mapIndexToVariable(patch_data_idx, var);
        Pointer<SideVariable<NDIM, double> > sc_var = var;
        if (!sc_var) continue;
        Pointer<SideData<NDIM, double> > patch_data = patch.getPatchData(patch_data_idx);
        const Box<NDIM>& ghost_box = patch_data->getGhostBox();

        // Loop over the boundary fill boxes and extrapolate the data.
        for (std::vector<std::pair<Box<NDIM>, std::pair<int, int> > >::const_iterator it = bdry_fill_boxes.begin();
             it != bdry_fill_boxes.end();
             ++it)
        {
            const Box<NDIM>& bdry_fill_box = it->first;
            const unsigned int location_index = it->second.first;
            const int codim = it->second.second;
#if (NDIM == 2)
            const boost::array<bool, NDIM> is_lower = { { PhysicalBoundaryUtilities::isLower(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isLower(
                                                              location_index, codim, 1) } };
            const boost::array<bool, NDIM> is_upper = { { PhysicalBoundaryUtilities::isUpper(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isUpper(
                                                              location_index, codim, 1) } };
#endif
#if (NDIM == 3)
            const boost::array<bool, NDIM> is_lower = { { PhysicalBoundaryUtilities::isLower(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isLower(location_index, codim, 1),
                                                          PhysicalBoundaryUtilities::isLower(
                                                              location_index, codim, 2) } };
            const boost::array<bool, NDIM> is_upper = { { PhysicalBoundaryUtilities::isUpper(location_index, codim, 0),
                                                          PhysicalBoundaryUtilities::isUpper(location_index, codim, 1),
                                                          PhysicalBoundaryUtilities::isUpper(
                                                              location_index, codim, 2) } };
#endif
            for (int depth = 0; depth < patch_data->getDepth(); ++depth)
            {
                for (unsigned int axis = 0; axis < NDIM; ++axis)
                {
                    for (SideIterator<NDIM> b(bdry_fill_box * ghost_box, axis); b; b++)
                    {
                        const SideIndex<NDIM> i = b();
                        SideIndex<NDIM> i_bdry = i;
                        IntVector<NDIM> i_shft = 0;
                        for (unsigned int d = 0; d < NDIM; ++d)
                        {
                            if (is_lower[d])
                            {
                                i_bdry(d) = patch_lower(d);
                                i_shft(d) = +1; // use interior data for extrapolation
                            }
                            else if (is_upper[d])
                            {
                                if (axis != d)
                                {
                                    i_bdry(d) = patch_upper(d);
                                }
                                else
                                {
                                    i_bdry(d) = patch_upper(d) + 1;
                                }
                                i_shft(d) = -1; // use interior data for extrapolation
                            }
                        }

                        // Perform constant, linear, or quadratic extrapolation.
                        switch (extrap_type)
                        {
                        case 0:
                            (*patch_data)(i, depth) = (*patch_data)(i_bdry, depth);
                            break;
                        case 1:
                            (*patch_data)(i, depth) = compute_linear_extrap(*patch_data, i, i_bdry, i_shft, depth);
                            break;
                        case 2:
                            (*patch_data)(i, depth) =
                                compute_quadratic_extrap(*patch_data, i, i_bdry, i_shft, depth, codim);
                            break;
                        }
                    }
                }
            }
        }
    }
    return;
} // setPhysicalBoundaryConditions_side

/////////////////////////////// NAMESPACE ////////////////////////////////////

} // namespace IBTK

//////////////////////////////////////////////////////////////////////////////


text:
require 'sinatra'
require 'sinatra/reloader' if development?
require 'erubis'
require 'redcarpet'
require 'clipboard'
require_relative 'mimadb'

Tilt.register Tilt::RedcarpetTemplate, 'md'

# Constants.
TITLE = 'title'.freeze
PASSWORD = 'password'.freeze
ERROR_CLOSED = 'The database has been closed. '\
               'Please go back to the homepage.'.freeze
ERROR_NO_TITLE = 'Title can not be blank.'.freeze
ERROR_NOT_UNIQUE = 'Title already exists.'.freeze
TIMEOUT_FOR_PASSWORD = 30

before do
  MimaDB.auto_close
end

before '/' do
  @index = File.exist?(MimaDB::PATH) ? :index : :index2
end

get '/' do
  redirect to('/entries') if MimaDB.opened?
  erb @index, :layout => :index_layout, :locals => { error: '' }
end

post '/' do
  if params.key? :password
    password = params[:password]
    if MimaDB.open(password)
      redirect to('/entries')
    else
      erb :index, :layout => :index_layout, :locals => {
        error: 'Error: Wrong password.'
      }
    end
  else
    new_password = params[:'new-password']
    confirm_passowrd = params[:'confirm-password']
    error = 'Error: Not Match. ==> Please input a same password twice.'
    if (new_password + confirm_passowrd).empty?
      redirect to('/')
    elsif new_password != confirm_passowrd
      erb :index2, :layout => :index_layout, :locals => { error: error }
    elsif new_password == confirm_passowrd
      MimaDB.create(new_password)
      add_first_entry
    end
  end
end

get '/entries/?' do
  back_home_if_closed
  return add_first_entry if MimaDB.all_boxes.empty?
  erb :entries, :locals => { boxes: MimaDB.all_boxes }
end

get '/recyclebin/?' do
  back_home_if_closed
  return 'Empty.' if MimaDB.recyclebin.empty?
  erb :recyclebin, :locals => { boxes: MimaDB.recyclebin }
end

get '/entries/:title' do |title|
  back_home_if_closed
  box = MimaDB.get(title)
  return [404, 'Not Found'] if box.nil?

  history = MimaDB.history(title)
  erb :edit, :locals => { box: box, history: history }
end

get '/add/?' do
  back_home_if_closed
  erb :add, :locals => { show: '' }
end

# RESTful API For Ajax.
before '/api/*' do
  halt 403, { 'errorType' => 'Closed' }, ERROR_CLOSED unless MimaDB.opened?
end

# Return a new password to client.
post '/api/newpassword' do
  [201, { 'password' => MimaDB.new_password }, 'Got a New Password']
end

# Copy a string into clipboard.
post '/api/copyusername/:title' do
  Clipboard.copy(params['textContent'])
  201
end

# Copy a password into clipboard.
post '/api/copypassword/:title' do |title|
  box = MimaDB.get(title)
  Clipboard.copy(box['password'])
  Thread.new do
    password = box['password'].encode('UTF-8')
    sleep TIMEOUT_FOR_PASSWORD
    new_content = Clipboard.paste.encode('UTF-8')
    Clipboard.clear if new_content == password
  end
  201
end

# Return a box to client.
# post '/api/entries/:title' do |title|
#   [201, MimaDB.get(title)]
# end

post '/api/entries' do
  title = params[TITLE]
  if title.empty?
    [403, { 'errorType' => 'NoTitle' }, ERROR_NO_TITLE]
  elsif MimaDB.exist?(title)
    [403, { 'errorType' => 'NotUnique' }, ERROR_NOT_UNIQUE]
  else
    params[PASSWORD] = MimaDB.new_password
    box = Mimabox.make(params)
    MimaDB.insert(box)
    [201, '/entries/' + title]
  end
end

put '/api/entries/:old_title' do |old_title|
  title = params[TITLE]
  if title.empty?
    [403, { 'errorType' => 'NoTitle' }, ERROR_NO_TITLE]
  elsif title != old_title && MimaDB.exist?(title)
    [403, { 'errorType' => 'NotUnique' }, ERROR_NOT_UNIQUE]
  else
    box = Mimabox.make(params)
    MimaDB.update(old_title, box)
    200
  end
end

patch '/api/entries/:title' do |title|
  MimaDB.recover(title)
  200
end

delete '/api/entries/:title' do |title|
  MimaDB.delete(title)
  204
end

delete '/api/recyclebin/:title' do |title|
  MimaDB.delete_forever(title)
  204
end

helpers do
  def add_first_entry
    erb :add, :locals => { show: 'style="display: block"' }
  end

  def back_home_if_closed
    redirect to('/') unless MimaDB.opened?
  end
end


text:
define NONE        = 0;
define READ_ONLY   = 1;
define DONT_ENUM   = 2;
define DONT_DELETE = 4;
define NEW_ONE_BYTE_STRING = true;
define NEW_TWO_BYTE_STRING = false;

# Constants used for getter and setter operations.
define GETTER = 0;
define SETTER = 1;

# Safe maximum number of arguments to push to stack, when multiplied by
# pointer size. Used by Function.prototype.apply(), Reflect.apply() and
# Reflect.construct().
define kSafeArgumentsLength = 0x800000;

# 2^53 - 1
define kMaxSafeInteger = 9007199254740991;

# 2^32 - 1
define kMaxUint32 = 4294967295;

# Strict mode flags for passing to %SetProperty
define kSloppyMode = 0;
define kStrictMode = 1;

# Native cache ids.
define STRING_TO_REGEXP_CACHE_ID = 0;

# Type query macros.
#
# Note: We have special support for typeof(foo) === 'bar' in the compiler.
#       It will *not* generate a runtime typeof call for the most important
#       values of 'bar'.
macro IS_ARRAY(arg)             = (%_IsArray(arg));
macro IS_ARRAYBUFFER(arg)       = (%_ClassOf(arg) === 'ArrayBuffer');
macro IS_BOOLEAN(arg)           = (typeof(arg) === 'boolean');
macro IS_BOOLEAN_WRAPPER(arg)   = (%_ClassOf(arg) === 'Boolean');
macro IS_DATAVIEW(arg)          = (%_ClassOf(arg) === 'DataView');
macro IS_DATE(arg)              = (%_IsDate(arg));
macro IS_ERROR(arg)             = (%_ClassOf(arg) === 'Error');
macro IS_FUNCTION(arg)          = (%_IsFunction(arg));
macro IS_GENERATOR(arg)         = (%_ClassOf(arg) === 'Generator');
macro IS_GLOBAL(arg)            = (%_ClassOf(arg) === 'global');
macro IS_MAP(arg)               = (%_ClassOf(arg) === 'Map');
macro IS_MAP_ITERATOR(arg)      = (%_ClassOf(arg) === 'Map Iterator');
macro IS_NULL(arg)              = (arg === null);
macro IS_NULL_OR_UNDEFINED(arg) = (arg == null);
macro IS_NUMBER(arg)            = (typeof(arg) === 'number');
macro IS_NUMBER_WRAPPER(arg)    = (%_ClassOf(arg) === 'Number');
macro IS_OBJECT(arg)            = (typeof(arg) === 'object');
macro IS_PROXY(arg)             = (%_IsJSProxy(arg));
macro IS_REGEXP(arg)            = (%_IsRegExp(arg));
macro IS_SCRIPT(arg)            = (%_ClassOf(arg) === 'Script');
macro IS_SET(arg)               = (%_ClassOf(arg) === 'Set');
macro IS_SET_ITERATOR(arg)      = (%_ClassOf(arg) === 'Set Iterator');
macro IS_SHAREDARRAYBUFFER(arg) = (%_ClassOf(arg) === 'SharedArrayBuffer');
macro IS_SIMD_VALUE(arg)        = (%_IsSimdValue(arg));
macro IS_STRING(arg)            = (typeof(arg) === 'string');
macro IS_STRING_WRAPPER(arg)    = (%_ClassOf(arg) === 'String');
macro IS_STRONG(arg)            = (%IsStrong(arg));
macro IS_SYMBOL(arg)            = (typeof(arg) === 'symbol');
macro IS_SYMBOL_WRAPPER(arg)    = (%_ClassOf(arg) === 'Symbol');
macro IS_UNDEFINED(arg)         = (arg === (void 0));
macro IS_WEAKMAP(arg)           = (%_ClassOf(arg) === 'WeakMap');
macro IS_WEAKSET(arg)           = (%_ClassOf(arg) === 'WeakSet');

# Macro for ES queries of the type: "Type(O) is Object."
macro IS_RECEIVER(arg) = (%_IsJSReceiver(arg));

# Macro for ES queries of the type: "IsCallable(O)"
macro IS_CALLABLE(arg) = (typeof(arg) === 'function');

# Macro for ES6 CheckObjectCoercible
# Will throw a TypeError of the form "[functionName] called on null or undefined".
macro CHECK_OBJECT_COERCIBLE(arg, functionName) = if (IS_NULL(%IS_VAR(arg)) || IS_UNDEFINED(arg)) throw MakeTypeError(kCalledOnNullOrUndefined, functionName);

# Inline macros. Use %IS_VAR to make sure arg is evaluated only once.
macro NUMBER_IS_NAN(arg) = (!%_IsSmi(%IS_VAR(arg)) && !(arg == arg));
macro NUMBER_IS_FINITE(arg) = (%_IsSmi(%IS_VAR(arg)) || ((arg == arg) && (arg != 1/0) && (arg != -1/0)));
macro TO_BOOLEAN(arg) = (!!(arg));
macro TO_INTEGER(arg) = (%_ToInteger(arg));
macro TO_INTEGER_MAP_MINUS_ZERO(arg) = (%_IsSmi(%IS_VAR(arg)) ? arg : %NumberToIntegerMapMinusZero(arg));
macro TO_INT32(arg) = ((arg) | 0);
macro TO_UINT32(arg) = ((arg) >>> 0);
macro TO_LENGTH(arg) = (%_ToLength(arg));
macro TO_LENGTH_OR_UINT32(arg) = (FLAG_harmony_tolength ? TO_LENGTH(arg) : TO_UINT32(arg));
macro TO_LENGTH_OR_INTEGER(arg) = (FLAG_harmony_tolength ? TO_LENGTH(arg) : TO_INTEGER(arg));
macro TO_STRING(arg) = (%_ToString(arg));
macro TO_NUMBER(arg) = (%_ToNumber(arg));
macro TO_OBJECT(arg) = (%_ToObject(arg));
macro TO_PRIMITIVE(arg) = (%_ToPrimitive(arg));
macro TO_PRIMITIVE_NUMBER(arg) = (%_ToPrimitive_Number(arg));
macro TO_PRIMITIVE_STRING(arg) = (%_ToPrimitive_String(arg));
macro TO_NAME(arg) = (%_ToName(arg));
macro JSON_NUMBER_TO_STRING(arg) = ((%_IsSmi(%IS_VAR(arg)) || arg - arg == 0) ? %_NumberToString(arg) : "null");
macro HAS_OWN_PROPERTY(arg, index) = (%_Call(ObjectHasOwnProperty, arg, index));
macro HAS_INDEX(array, index, is_array) = ((is_array && %_HasFastPackedElements(%IS_VAR(array))) ? (index < array.length) : (index in array));

# Private names.
macro IS_PRIVATE(sym) = (%SymbolIsPrivate(sym));
macro HAS_PRIVATE(obj, sym) = (%HasOwnProperty(obj, sym));
macro HAS_DEFINED_PRIVATE(obj, sym) = (!IS_UNDEFINED(obj[sym]));
macro GET_PRIVATE(obj, sym) = (obj[sym]);
macro SET_PRIVATE(obj, sym, val) = (obj[sym] = val);

# Constants.  The compiler constant folds them.
define INFINITY = (1/0);
define UNDEFINED = (void 0);

# Macros implemented in Python.
python macro CHAR_CODE(str) = ord(str[1]);

# Constants used on an array to implement the properties of the RegExp object.
define REGEXP_NUMBER_OF_CAPTURES = 0;
define REGEXP_FIRST_CAPTURE = 3;

# Macros for internal slot access.
macro REGEXP_GLOBAL(regexp) = (%_RegExpFlags(regexp) & 1);
macro REGEXP_IGNORE_CASE(regexp) = (%_RegExpFlags(regexp) & 2);
macro REGEXP_MULTILINE(regexp) = (%_RegExpFlags(regexp) & 4);
macro REGEXP_STICKY(regexp) = (%_RegExpFlags(regexp) & 8);
macro REGEXP_UNICODE(regexp) = (%_RegExpFlags(regexp) & 16);
macro REGEXP_SOURCE(regexp) = (%_RegExpSource(regexp));

# We can't put macros in macros so we use constants here.
# REGEXP_NUMBER_OF_CAPTURES
macro NUMBER_OF_CAPTURES(array) = ((array)[0]);

# Last input and last subject of regexp matches.
define LAST_SUBJECT_INDEX = 1;
macro LAST_SUBJECT(array) = ((array)[1]);
macro LAST_INPUT(array) = ((array)[2]);

# REGEXP_FIRST_CAPTURE
macro CAPTURE(index) = (3 + (index));
define CAPTURE0 = 3;
define CAPTURE1 = 4;

# For the regexp capture override array.  This has the same
# format as the arguments to a function called from
# String.prototype.replace.
macro OVERRIDE_MATCH(override) = ((override)[0]);
macro OVERRIDE_POS(override) = ((override)[(override).length - 2]);
macro OVERRIDE_SUBJECT(override) = ((override)[(override).length - 1]);
# 1-based so index of 1 returns the first capture
macro OVERRIDE_CAPTURE(override, index) = ((override)[(index)]);

# PropertyDescriptor return value indices - must match
# PropertyDescriptorIndices in runtime-object.cc.
define IS_ACCESSOR_INDEX = 0;
define VALUE_INDEX = 1;
define GETTER_INDEX = 2;
define SETTER_INDEX = 3;
define WRITABLE_INDEX = 4;
define ENUMERABLE_INDEX = 5;
define CONFIGURABLE_INDEX = 6;

# For messages.js
# Matches Script::Type from objects.h
define TYPE_NATIVE = 0;
define TYPE_EXTENSION = 1;
define TYPE_NORMAL = 2;

# Matches Script::CompilationType from objects.h
define COMPILATION_TYPE_HOST = 0;
define COMPILATION_TYPE_EVAL = 1;
define COMPILATION_TYPE_JSON = 2;

# Matches Messages::kNoLineNumberInfo from v8.h
define kNoLineNumberInfo = 0;

# Must match PropertyFilter in property-details.h
define PROPERTY_FILTER_NONE = 0;
define PROPERTY_FILTER_ONLY_ENUMERABLE = 2;
define PROPERTY_FILTER_SKIP_STRINGS = 8;
define PROPERTY_FILTER_SKIP_SYMBOLS = 16;

# Use for keys, values and entries iterators.
define ITERATOR_KIND_KEYS = 1;
define ITERATOR_KIND_VALUES = 2;
define ITERATOR_KIND_ENTRIES = 3;

macro FIXED_ARRAY_GET(array, index) = (%_FixedArrayGet(array, (index) | 0));
macro FIXED_ARRAY_SET(array, index, value) = (%_FixedArraySet(array, (index) | 0, value));
# TODO(adamk): Find a more robust way to force Smi representation.
macro FIXED_ARRAY_SET_SMI(array, index, value) = (FIXED_ARRAY_SET(array, index, (value) | 0));

macro ORDERED_HASH_TABLE_BUCKET_COUNT(table) = (FIXED_ARRAY_GET(table, 0));
macro ORDERED_HASH_TABLE_ELEMENT_COUNT(table) = (FIXED_ARRAY_GET(table, 1));
macro ORDERED_HASH_TABLE_SET_ELEMENT_COUNT(table, count) = (FIXED_ARRAY_SET_SMI(table, 1, count));
macro ORDERED_HASH_TABLE_DELETED_COUNT(table) = (FIXED_ARRAY_GET(table, 2));
macro ORDERED_HASH_TABLE_SET_DELETED_COUNT(table, count) = (FIXED_ARRAY_SET_SMI(table, 2, count));
macro ORDERED_HASH_TABLE_BUCKET_AT(table, bucket) = (FIXED_ARRAY_GET(table, 3 + (bucket)));
macro ORDERED_HASH_TABLE_SET_BUCKET_AT(table, bucket, entry) = (FIXED_ARRAY_SET(table, 3 + (bucket), entry));

macro ORDERED_HASH_TABLE_HASH_TO_BUCKET(hash, numBuckets) = (hash & ((numBuckets) - 1));

macro ORDERED_HASH_SET_ENTRY_TO_INDEX(entry, numBuckets) = (3 + (numBuckets) + ((entry) << 1));
macro ORDERED_HASH_SET_KEY_AT(table, entry, numBuckets) = (FIXED_ARRAY_GET(table, ORDERED_HASH_SET_ENTRY_TO_INDEX(entry, numBuckets)));
macro ORDERED_HASH_SET_CHAIN_AT(table, entry, numBuckets) = (FIXED_ARRAY_GET(table, ORDERED_HASH_SET_ENTRY_TO_INDEX(entry, numBuckets) + 1));

macro ORDERED_HASH_MAP_ENTRY_TO_INDEX(entry, numBuckets) = (3 + (numBuckets) + ((entry) * 3));
macro ORDERED_HASH_MAP_KEY_AT(table, entry, numBuckets) = (FIXED_ARRAY_GET(table, ORDERED_HASH_MAP_ENTRY_TO_INDEX(entry, numBuckets)));
macro ORDERED_HASH_MAP_VALUE_AT(table, entry, numBuckets) = (FIXED_ARRAY_GET(table, ORDERED_HASH_MAP_ENTRY_TO_INDEX(entry, numBuckets) + 1));
macro ORDERED_HASH_MAP_CHAIN_AT(table, entry, numBuckets) = (FIXED_ARRAY_GET(table, ORDERED_HASH_MAP_ENTRY_TO_INDEX(entry, numBuckets) + 2));

# Must match OrderedHashTable::kNotFound.
define NOT_FOUND = -1;

# Check whether debug is active.
define DEBUG_IS_ACTIVE = (%_DebugIsActive() != 0);
macro DEBUG_PREPARE_STEP_IN_IF_STEPPING(function) = if (%_DebugIsActive() != 0) %DebugPrepareStepInIfStepping(function);

# SharedFlag equivalents
define kNotShared = false;
define kShared = true;

# UseCounters from include/v8.h
define kUseAsm = 0;
define kBreakIterator = 1;
define kLegacyConst = 2;
define kMarkDequeOverflow = 3;
define kStoreBufferOverflow = 4;
define kSlotsBufferOverflow = 5;
define kObjectObserve = 6;
define kForcedGC = 7;
define kSloppyMode = 8;
define kStrictMode = 9;
define kStrongMode = 10;
define kRegExpPrototypeStickyGetter = 11;
define kRegExpPrototypeToString = 12;
define kRegExpPrototypeUnicodeGetter = 13;
define kIntlV8Parse = 14;
define kIntlPattern = 15;
define kIntlResolved = 16;
define kPromiseChain = 17;
define kPromiseAccept = 18;
define kPromiseDefer = 19;


text:
using System;

using Org.BouncyCastle.Utilities.IO;

namespace Org.BouncyCastle.Cms
{
	internal class NullOutputStream
		: BaseOutputStream
	{
		public override void WriteByte(byte b)
		{
			// do nothing
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			// do nothing
		}
	}
}


text:
from subprocess import call

import glob

filenames = glob.glob("*.json")

cmd="rm -rf samples"
result = call(cmd, shell=True)

for f in filenames:
    config = f.split(".")[0]

    cmd="CUDA_VISIBLE_DEVICES=0 hypergan train /ml/datasets/faces/128x128/all --sample_every 8000 --sampler debug --format jpg --size 64x64x3 -b 8 -c ./"+config+" --resize --save_samples --steps 16001 --save_every 1000000"
    print(cmd)
    result = call(cmd, shell=True)

    cmd="mkdir samples/"+config
    result = call(cmd, shell=True)

    cmd="mv samples/*.png samples/"+config
    result = call(cmd, shell=True)


text: from HamamatsuPMT import *


text:
#region Licence

#endregion

namespace WmcSoft.Collections
{
    /// <summary>
    /// Policy applied when trying to insert duplicates.
    /// </summary>
    public enum DuplicatePolicy
    {
        /// <summary>
        /// Throws an exception when attempting to add a duplicate.
        /// </summary>
        ThrowException = 0,
        /// <summary>
        /// Preserve the first inserted element.
        /// </summary>
        KeepFirst,
        /// <summary>
        /// Each insertion of duplicate value override the previous one.
        /// </summary>
        KeepLast,
    }
}


text:
package org.araqne.msgbus;

public interface PackageMetadataProvider {
	String getKey();

	String getName();

	String getName(String locale);
}