text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/networksecurity/v1beta1/client_tls_policy.proto

namespace Google\Cloud\NetworkSecurity\V1beta1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Response returned by the ListClientTlsPolicies method.
 *
 * Generated from protobuf message google.cloud.networksecurity.v1beta1.ListClientTlsPoliciesResponse
 */
class ListClientTlsPoliciesResponse extends \Google\Protobuf\Internal\Message
{
    /**
     * List of ClientTlsPolicy resources.
     *
     * Generated from protobuf field repeated .google.cloud.networksecurity.v1beta1.ClientTlsPolicy client_tls_policies = 1;
     */
    private $client_tls_policies;
    /**
     * If there might be more results than those appearing in this response, then
     * `next_page_token` is included. To get the next set of results, call this
     * method again using the value of `next_page_token` as `page_token`.
     *
     * Generated from protobuf field string next_page_token = 2;
     */
    private $next_page_token = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type array<\Google\Cloud\NetworkSecurity\V1beta1\ClientTlsPolicy>|\Google\Protobuf\Internal\RepeatedField $client_tls_policies
     *           List of ClientTlsPolicy resources.
     *     @type string $next_page_token
     *           If there might be more results than those appearing in this response, then
     *           `next_page_token` is included. To get the next set of results, call this
     *           method again using the value of `next_page_token` as `page_token`.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Networksecurity\V1Beta1\ClientTlsPolicy::initOnce();
        parent::__construct($data);
    }

    /**
     * List of ClientTlsPolicy resources.
     *
     * Generated from protobuf field repeated .google.cloud.networksecurity.v1beta1.ClientTlsPolicy client_tls_policies = 1;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getClientTlsPolicies()
    {
        return $this->client_tls_policies;
    }

    /**
     * List of ClientTlsPolicy resources.
     *
     * Generated from protobuf field repeated .google.cloud.networksecurity.v1beta1.ClientTlsPolicy client_tls_policies = 1;
     * @param array<\Google\Cloud\NetworkSecurity\V1beta1\ClientTlsPolicy>|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setClientTlsPolicies($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\NetworkSecurity\V1beta1\ClientTlsPolicy::class);
        $this->client_tls_policies = $arr;

        return $this;
    }

    /**
     * If there might be more results than those appearing in this response, then
     * `next_page_token` is included. To get the next set of results, call this
     * method again using the value of `next_page_token` as `page_token`.
     *
     * Generated from protobuf field string next_page_token = 2;
     * @return string
     */
    public function getNextPageToken()
    {
        return $this->next_page_token;
    }

    /**
     * If there might be more results than those appearing in this response, then
     * `next_page_token` is included. To get the next set of results, call this
     * method again using the value of `next_page_token` as `page_token`.
     *
     * Generated from protobuf field string next_page_token = 2;
     * @param string $var
     * @return $this
     */
    public function setNextPageToken($var)
    {
        GPBUtil::checkString($var, True);
        $this->next_page_token = $var;

        return $this;
    }

}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.default = void 0;

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}

/**
 * First-in, First-out task queue that manages a dedicated pool
 * for each worker as well as a shared queue. The FIFO ordering is guaranteed
 * across the worker specific and shared queue.
 */
class FifoQueue {
  constructor() {
    _defineProperty(this, '_workerQueues', []);

    _defineProperty(this, '_sharedQueue', new InternalQueue());
  }

  enqueue(task, workerId) {
    if (workerId == null) {
      this._sharedQueue.enqueue(task);

      return;
    }

    let workerQueue = this._workerQueues[workerId];

    if (workerQueue == null) {
      workerQueue = this._workerQueues[workerId] = new InternalQueue();
    }

    const sharedTop = this._sharedQueue.peekLast();

    const item = {
      previousSharedTask: sharedTop,
      task
    };
    workerQueue.enqueue(item);
  }

  dequeue(workerId) {
    var _this$_workerQueues$w, _workerTop$previousSh, _workerTop$previousSh2;

    const workerTop =
      (_this$_workerQueues$w = this._workerQueues[workerId]) === null ||
      _this$_workerQueues$w === void 0
        ? void 0
        : _this$_workerQueues$w.peek();
    const sharedTaskIsProcessed =
      (_workerTop$previousSh =
        workerTop === null || workerTop === void 0
          ? void 0
          : (_workerTop$previousSh2 = workerTop.previousSharedTask) === null ||
            _workerTop$previousSh2 === void 0
          ? void 0
          : _workerTop$previousSh2.request[1]) !== null &&
      _workerTop$previousSh !== void 0
        ? _workerTop$previousSh
        : true; // Process the top task from the shared queue if
    // - there's no task in the worker specific queue or
    // - if the non-worker-specific task after which this worker specifif task
    //   hasn been queued wasn't processed yet

    if (workerTop != null && sharedTaskIsProcessed) {
      var _this$_workerQueues$w2,
        _this$_workerQueues$w3,
        _this$_workerQueues$w4;

      return (_this$_workerQueues$w2 =
        (_this$_workerQueues$w3 = this._workerQueues[workerId]) === null ||
        _this$_workerQueues$w3 === void 0
          ? void 0
          : (_this$_workerQueues$w4 = _this$_workerQueues$w3.dequeue()) ===
              null || _this$_workerQueues$w4 === void 0
          ? void 0
          : _this$_workerQueues$w4.task) !== null &&
        _this$_workerQueues$w2 !== void 0
        ? _this$_workerQueues$w2
        : null;
    }

    return this._sharedQueue.dequeue();
  }
}

exports.default = FifoQueue;

/**
 * FIFO queue for a single worker / shared queue.
 */
class InternalQueue {
  constructor() {
    _defineProperty(this, '_head', null);

    _defineProperty(this, '_last', null);
  }

  enqueue(value) {
    const item = {
      next: null,
      value
    };

    if (this._last == null) {
      this._head = item;
    } else {
      this._last.next = item;
    }

    this._last = item;
  }

  dequeue() {
    if (this._head == null) {
      return null;
    }

    const item = this._head;
    this._head = item.next;

    if (this._head == null) {
      this._last = null;
    }

    return item.value;
  }

  peek() {
    var _this$_head$value, _this$_head;

    return (_this$_head$value =
      (_this$_head = this._head) === null || _this$_head === void 0
        ? void 0
        : _this$_head.value) !== null && _this$_head$value !== void 0
      ? _this$_head$value
      : null;
  }

  peekLast() {
    var _this$_last$value, _this$_last;

    return (_this$_last$value =
      (_this$_last = this._last) === null || _this$_last === void 0
        ? void 0
        : _this$_last.value) !== null && _this$_last$value !== void 0
      ? _this$_last$value
      : null;
  }
}

redpajama_set_name: RedPajamaGithub


text:
const ee = require('sepal/ee')

const addCloud = cloudMasking =>
    image => image.addBandsReplace(cloud(image, cloudMasking))

const cloud = (image, cloudMasking) => {
    const scoreThreshold = () => {
        switch (cloudMasking) {
        case 'AGGRESSIVE': return 0.25
        case 'MODERATE': return 0.30
        default: return 0.30
        }
    }
    const threshold = scoreThreshold()
    return image
        .selfExpression(`
            i.cloud or (!i.soil and !i.snow and
            (cloudScore > ${threshold} or (cloudScore > 0 and i.aerosol > 0.2) or i.hazeScore == 0))
        `, {
            cloudScore: cloudScore(image)
        })
        .rename('cloud')
}

// Based on scripts by Ian Hausman, which in turn is based on script by Matt Hancher
// https://groups.google.com/d/msg/google-earth-engine-developers/i63DS-Dg8Sg/_hgCBEYeBwAJ
const cloudScore = image => {
    let score = ee.Image(1)
    let blueCirrusScore = ee.Image(0)

    // Clouds are reasonably bright in the blue or cirrus bands.
    // Use .max as a pseudo OR conditional
    blueCirrusScore = blueCirrusScore.max(image.select('blue').unitScaleClamp(0.1, 0.5))
    blueCirrusScore = blueCirrusScore.max(image.select('aerosol').unitScaleClamp(0.1, 0.5))
    blueCirrusScore = blueCirrusScore.max(image.select('cirrus').unitScaleClamp(0.1, 0.3))
    score = score.min(blueCirrusScore)

    // Clouds are reasonably bright in all visible bands.
    score = score.min(
        image.selfExpression('i.red + i.green + i.blue').unitScaleClamp(0.2, 0.8)
    )

    // Clouds are reasonably bright in all infrared bands.
    score = score.min(
        image.selfExpression('i.nir + i.swir1 + i.swir2').unitScaleClamp(0.3, 0.8)
    )

    // However, clouds are not snow.
    score = score.min(image.select('ndsi').unitScaleClamp(0.8, 0.6))

    return score
}

module.exports = addCloud


text:
require 'google/protobuf'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("google/cloud/automl/v1/text_segment.proto", :syntax => :proto3) do
    add_message "google.cloud.automl.v1.TextSegment" do
      optional :content, :string, 3
      optional :start_offset, :int64, 1
      optional :end_offset, :int64, 2
    end
  end
end

module Google
  module Cloud
    module AutoML
      module V1
        TextSegment = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1.TextSegment").msgclass
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<META HTTP-EQUIV="Content-Type" Content="text/html; charset=Windows-1252">
<TITLE>Dialog Side-Channel Attack on the Hybrid Encryption Protocol (Textbook RSA)</TITLE>
<link rel="stylesheet" type="text/css" href="CrypTool_Help.css">

<OBJECT TYPE="application/x-oleobject" CLASSID="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" VIEWASTEXT ID="Object1">
	<PARAM NAME="Keyword" VALUE="Dialog (overview of all dialogs)">
	<PARAM NAME="Keyword" VALUE="Visualization">
	<PARAM NAME="Keyword" VALUE="Demonstrations / Scenarios">
	<PARAM NAME="Keyword" VALUE="Side-channel attack">
</OBJECT>

Dialog Side-Channel Attack on the Hybrid Encryption Protocol (Textbook RSA)

You can access this dialog via the menu entry Analysis \ Asymmetric Encryption \ Side-Channel Attack on "Textbook RSA".

With this dialog you can execute and thereby understand the side-channel attack on "Textbook RSA".

For better handling there are inactive buttons as well as active buttons: active buttons appear in a strong coloring and can be clicked. Inactive buttons cannot be clicked and therefore appear in a gray, slightly faded coloring. Some buttons do not turn active until a certain context is reached.

The dialog window is grouped vertically: on the left side there is the navigation bar which is used to control the side-channel attack step by step. On the right side there are three info buttons for each of the involved actors and pictures of the communication channel and the side-channel. The buttons of the navigation bar appear in either red or green coloring. A red button indicates that the corresponding step was not yet executed, whereas a green button indicates that the corresponding step was already executed.

The communication channel of Alice and Bob is located in the middle of the dialog. It is a public channel, so Trudy is also allowed to send and receive information over this channel.

Placed around the communication channel there are three info buttons representing the three involved actors Alice, Bob and Trudy. Please click one of these buttons for detailed status information on the respective actor.

Further on you can see a traffic light representing the actual side-channel. Bob's server reveals information over this channel after being stimulated by Trudy with unscheduled information: In case the server cannot decrypt a received message properly, the traffic light shines red. If the decryption was successful, the traffic light shines green.

The process of the side-channel attack is separated into seven single steps which can be executed one after another:

Single step description
Executing actor

Introduction

Preparations

Alice

Message transmission

Alice

Message reception

Bob

Message interception

Trudy

Start attack cycle

Trudy

Generate report

Initiating a step by clicking on the appropriate button will show a dialog with more detailed information. Nevertheless you can obtain context sensitive help by pushing the F1 key.

Remark 1:

Using the check box in the lower right corner of the dialog you can prevent additional information dialogs from popping up. But note that fundamental information is presented irrespective of the status of this check box.

Remark 2:

If you have problems executing the side-channel attack then you can you can obtain help here.


text:
import fetch from 'isomorphic-fetch'
import {API_URL} from "../config";

export const REQUEST_FILES_LIST = 'REQUEST_FILES_LIST';
export const RECEIVE_FILES_LIST_ERROR = 'RECEIVE_FILES_LIST_ERROR';
export const RECEIVE_FILES_LIST_SUCCESS = 'RECEIVE_FILES_LIST_SUCCESS';

export const UPDATE_FILE = 'UPDATE_FILE';
export const UPDATE_FILE_ERROR = 'UPDATE_FILE_ERROR';
export const UPDATE_FILE_SUCCESS = 'UPDATE_FILE_SUCCESS';

export const CREATE_FOLDER = 'CREATE_FOLDER';
export const CREATE_FOLDER_SUCCESS = 'CREATE_FOLDER_SUCCESS';
export const CREATE_FOLDER_ERROR = 'CREATE_FOLDER_ERROR';

export const REMOVE_FILE = 'REMOVE_FILE';
export const REMOVE_FILE_SUCCESS = 'REMOVE_FILE_SUCCESS';
export const REMOVE_FILE_ERROR = 'REMOVE_FILE_ERROR';

export function requestFilesList(panelIndex) {
  return {
    type: REQUEST_FILES_LIST,
    panelIndex: panelIndex,
    status: 'loading'
  };
}

function receiveFilesListSuccess(data, panelIndex) {
  return {
    type: RECEIVE_FILES_LIST_SUCCESS,
    data,
    panelIndex
  };
}

function receiveFilesListError(error, panelIndex) {
  return {
    type: RECEIVE_FILES_LIST_ERROR,
    error,
    panelIndex
  };
}

export function updateFile(panelIndex) {
  return {
    type: UPDATE_FILE,
    panelIndex: panelIndex,
    saving: true
  };
}

function updateFileError(error, panelIndex) {
  return {
    type: UPDATE_FILE_ERROR,
    error,
    panelIndex,
    saving: false
  };
}

export function createFolder(panelIndex, path) {
  return {
    type: CREATE_FOLDER,
    panelIndex: panelIndex,
    path: path
  };
}

function createFolderError(error, panelIndex) {
  return {
    type: CREATE_FOLDER_ERROR,
    error,
    panelIndex
  };
}

export function removeFile(panelIndex, path) {
  return {
    type: REMOVE_FILE,
    panelIndex: panelIndex,
    path: path
  };
}

function removeFileError(error, panelIndex) {
  return {
    type: REMOVE_FILE_ERROR,
    error,
    panelIndex
  };
}

export function recieveFilesList(path, panelIndex) {
  path = path.replace(/^\/+/,'');
  return function (dispatch) {
    dispatch(requestFilesList(panelIndex));
    fetch(API_URL + path)
    .then(response => response.json())
    .then(data => dispatch(receiveFilesListSuccess(data, panelIndex)))
    .catch(error => dispatch(receiveFilesListError(error, panelIndex)));
  };
}

export function updateFileRequest(path, newFileName, panelIndex, onSuccess, onError) {
  return function (dispatch) {
    dispatch(updateFile(panelIndex));
    fetch(API_URL + path, {
      method: 'POST',
      body: JSON.stringify({action: 'update',fileName:newFileName})
    })
    .then(response => response.json())
    .then(
      data => dispatch(receiveFilesListSuccess(data, panelIndex)),
      error => dispatch(updateFileError(error, panelIndex))
    ).then(
      () => onSuccess(),
      () => onError()
    );
  };
}

export function createFolderRequest(path, panelIndex) {
  return function (dispatch) {
    dispatch(createFolder(panelIndex, path));
    dispatch(requestFilesList(panelIndex));
    fetch(API_URL + path, {
      method: 'POST',
      body: JSON.stringify({action: 'create'})
    })
    .then(response => response.json())
    .then(
      data => dispatch(receiveFilesListSuccess(data, panelIndex)),
      error => dispatch(createFolderError(error, panelIndex))
    );
  };
}

export function removeFilesRequest(files, panelIndex) {
  return function (dispatch) {

    dispatch(requestFilesList(panelIndex));

    Promise.all(files.map((item)=> {
      dispatch(removeFile(panelIndex, item.path));
      return fetch(API_URL + item.path, {
        method: 'POST',
        body: JSON.stringify({action: 'delete'})
      });
    })).then(values => {
      return values[values.length-1];
    })
    .then(response => response.json())
    .then(
      data => dispatch(receiveFilesListSuccess(data, panelIndex)),
      error => dispatch(removeFileError(error, panelIndex))
    );
  };
}


text:
<?php

namespace Castoridae\ComputerBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Computer
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Castoridae\ComputerBundle\Entity\ComputerRepository")
 */
class Computer
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var integer
     *
     * @ORM\Column(name="user_id", type="integer")
     */
    private $userId;

    /**
     * @ORM\OneToMany(targetEntity="Castoridae\ComputerBundle\Entity\Computer\Data", mappedBy="computer")
     */
    private $data;

    /**
     * @ORM\ManyToOne(targetEntity="Castoridae\UserBundle\Entity\User", inversedBy="machine")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    protected $user;

    /**
     * @ORM\Column(name="created_at", type="datetime")
     */
    private $createdAt;

    function __construct()
    {
        $this->createdAt = new \DateTime();
        $this->data = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Computer
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set userId
     *
     * @param integer $userId
     * @return Computer
     */
    public function setUserId($userId)
    {
        $this->userId = $userId;

        return $this;
    }

    /**
     * Get userId
     *
     * @return integer
     */
    public function getUserId()
    {
        return $this->userId;
    }

    /**
     * @return mixed
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * @param mixed $user
     */
    public function setUser($user)
    {
        $this->user = $user;
    }

    /**
     * @return mixed
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param mixed $createdAt
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * @return mixed
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param mixed $data
     */
    public function setData($data)
    {
        $this->data = $data;
    }

}


text:
{% macro confirm_delete_modal(id, btn_text, url) %}

        {{ btn_text }}

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

{{_('Delete modal header') }}

{{ _('You are deleting some data. It cannot be rollback.') }}

        <form method="POST" action="{{ url }}">
          <button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
          <button class="btn btn-primary" type="submit">{{ _('Delete') }}</button>
        </form>

{% endmacro %}


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using PoESkillTree.Engine.GameModel;
using PoESkillTree.SkillTreeFiles;

namespace PoESkillTree.Utils.UrlProcessing
{
    /// <summary>
    /// Represents an object that extracts build information from the tree url.
    /// </summary>
    public abstract class BuildUrlDeserializer
    {
        private readonly IAscendancyClasses _ascendancyClasses;
        protected string BuildUrl { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="BuildUrlDeserializer"/> class.
        /// </summary>
        /// <param name="buildUrl">The PoE build url.</param>
        /// <param name="ascendancyClasses">The instance of the <see cref="ascendancyClasses"/>
        /// to access general information about skill tree.</param>
        protected BuildUrlDeserializer(string buildUrl, IAscendancyClasses ascendancyClasses)
        {
            BuildUrl = buildUrl ?? string.Empty;
            _ascendancyClasses = ascendancyClasses;
        }

        /// <summary>
        /// Returns the basic build data.
        /// </summary>
        public abstract BuildUrlData GetBuildData();

        /// <summary>
        /// Returns the id of a character class decoded from the tree url.
        /// </summary>
        protected abstract int GetCharacterClassId();

        /// <summary>
        /// Returns the id of an ascendancy class decoded from the tree url.
        /// </summary>
        public abstract int GetAscendancyClassId();

        /// <summary>
        /// Validates that the build url can be deserialized without exceptions.
        /// </summary>
        /// <param name="exception">The exception that was thrown on deserializing the build url. Null if true is
        /// returned.</param>
        /// <returns>True iff the build url can be deserialized without exceptions</returns>
        public abstract bool ValidateBuildUrl([NotNullWhen(false)] out Exception? exception);

        /// <summary>
        /// Returns the number of non-ascendancy points the given tree url uses.
        /// </summary>
        public int GetPointsCount()
            => GetBuildData().SkilledNodesIds.Count(
                id => SkillTree.Skillnodes.TryGetValue(id, out var skillNode)
                      && (!skillNode.IsRootNode && !skillNode.IsAscendancyNode));

        /// <summary>
        /// Returns the character class of the given build url.
        /// </summary>
        public CharacterClass GetCharacterClass()
            => (CharacterClass) GetCharacterClassId();

        /// <summary>
        /// Returns the ascendancy class of the given build url.
        /// Returns null if the tree has no ascendancy class selected.
        /// </summary>
        public string? GetAscendancyClass()
        {
            var ascendancyId = GetAscendancyClassId();

            // No Ascendancy class selected.
            if (ascendancyId == 0)
                return null;

            return _ascendancyClasses.GetAscendancyClassName(GetCharacterClass(), ascendancyId);
        }
    }
}


text:
package de.codengine.tankerkoenig.models.requests;

import java.util.Map;

import de.codengine.tankerkoenig.exception.RequesterException;

abstract class BaseRequest<R extends Result> implements Request<R>
{
   private final String apiKey;
   private final String baseUrl;
   private final Requester requester;

   BaseRequest(final String apiKey, final String baseUrl, final Requester requester)
   {
      this.apiKey = apiKey;
      this.baseUrl = baseUrl;
      this.requester = requester;
   }

   /**
    * Executes the request using the underlying {@link Requester},
    * which will return the requested result object
    *
    * @throws RequesterException Checked Exceptions that might be thrown during request execution
    */
   @Override
   public final R execute() throws RequesterException
   {
      return requester.execute(this, getResultClass());
   }

   abstract String getEndpoint();

   abstract Map<String, Object> getRequestParameters();

   abstract void validate();

   abstract Method getMethod();

   abstract Class<R> getResultClass();

   String getApiKey()
   {
      return apiKey;
   }

   String getBaseUrl()
   {
      return baseUrl;
   }
}


text:
Adds syntax highlighting to `TODO`, `FIXME`, `CHANGED`, `XXX`, and `IDEA` in comments
and text in Atom.

Originally [converted](http://atom.io/docs/latest/converting-a-text-mate-bundle)
from the [TODO TextMate bundle](https://github.com/textmate/todo.tmbundle).

Contributions are greatly appreciated. Please fork this repository and open a
pull request to add snippets, make grammar tweaks, etc.


text:
SVG Web Sizing Strategy

Warning

This document is provided for historical and informational purposes but should
not be used as a reference.

I believe the observations are accurate and the strategies described in this document
are pretty much what was initially coded into SVG Web. However, when it comes to
specific sizing behavior in specific scenarios, this document should not be considered
an accurate and up-to-date reference.

This document was written early in the design of SVG Web sizing behavior and there may
be mistakes in it and also, since then, bugs have been fixed and there are new generations
of browsers and behavior may have changed.

Contents

  Introduction

  Overview

         Safari

         Mozilla/FF

         Opera

         IE

         Reference

  Object Sizing

     Both object width and height are specified

     Neither object width nor height are specified

     Only object width is specified

     Only object height is specified

  Why Flash Scaling is not used

Introduction

The goal of this project is to define a consistent SVG sizing behavior for SVG
Web to emulate when used in flash mode. Different browsers size SVG images
in different ways, and so we have decided to pick one browser behavior and
implement that consistently on all browsers so that web developers can
rely on consistent behavior without having to implement that themselves.

When an object tag is used to embed an SVG image, the size of the object
can be different from the size of the SVG image that is rendered within it.
These can be considered two different layers of sizing and clipping.

With some browsers (e.g. Opera,Firefox 3.x) native implementations,
object sizing can utilize the SVG sizing parameters when either the
object height or width is not specified.

Both Opera and Firefox have made different choices with respect to sizing.
The issues are complex enough that it is not clear what behavior is more
correct or desirable in various circumstances. Safari, on the other hand
has some clear shortcomings that call out to be patched over.

The question is what behavior should SVG Web simulate for the automatic
object sizing? Should it simulate the browser native rendering of whatever
browser is being used? What about Safari with its shortcomings and IE which
has no native behavior? Should we consider using a common sizing behavior
for all browsers? (Just asking. I know this has serious issues.)

Before answering those questions, the current native behavior of the
different browsers should be considered.

This document describes, for the different browsers, how object sizing
logic works and how SVG sizing and scaling works within the object
boundaries.

In the Flash Scaling section, we describe what purpose automatic Flash
scaling is good for and why we do not use it.

Overview

Safari

With Safari 4.0.3 native rendering, the object is sized completely
independent of the svg sizing parameters (width, height, viewBox,
preserveAspectRatio). Percentages on the object refer to the parent
node and percentages on the SVG refer to the object size.
If pixels or percentages are not provided on the object tag, the
object width defaults to 300 and the object height defaults to 150.
Obviously, this is simple and easiest to implement, but it means
the Safari browser requires manually specifying the object height
and width to match the svg height and width or you end up stuck
with 300x150. This seems to be a serious shortcoming.

Mozilla

Mozilla recognized that the simple 300 x 150 object default size
is a not ideal for SVG files because SVG files specify a preferred
height and width and should not be considered different from other
images that do not have to specify their size.
(See https://bugzilla.mozilla.org/show_bug.cgi?id=321531 and
https://bugzilla.mozilla.org/show_bug.cgi?id=294086).
As of Firefox 3, object sizing utilizes the SVG sizing parameters
when either the object height or width is not specified.

Opera

Opera 9.64 also utilizes the svg sizing parameters when either the
object height or width is not specified. It has similar logic to
firefox does but it made different choices in certain circumstances.

The common scenario is when an svg width and height is provided
in pixels in the svg tag. The two variations of that scenarios
are when the svg image is included with an object tag that has
a both a width and height or neither of them.

In the case where neither object width or height are provided, Firefox
and Opera will both use the svg width and height (if it is pixels)
to size the object. Safari however uses an object size of 300x150.

In the case where the object height and width is specified in the object
tag, and the svg file has a viewBox, firefox will scale the viewBox
into the object area, but Opera and Safari will scale the viewBox
into the svg height and width, regardless of the object size. In case
of size mismatches, Opera will add scroll bars to the object while
Safari clips.

The rules for Firefox and Opera get complex because you can have
pixel, percentages, or missing values for object height,
object width, svg height, and svg width and there seems to be
a different behavior for every circumstance.

It is worth mentioning that after the object is sized, the svg
height and width are used, generally, as follows:

For Safari:

The svg height and width determine size of the SVG
'canvas' within the object area. If the width or height
exceeds the object area, the svg file is clipped.
If it is smaller, the svg file does not fill the
whole area (respecting preserveAspectRatio).

For Opera & FF:

The svg height and width are used in various ways, if they are
used at all. The rules below define how they are used.

IE

For IE, we will have to pick an object sizing behavior since there is
no native object/SVG sizing behavior. (We pick Mozilla/Firefox).

Reference

Here is some additional reference material:

http://www.w3.org/TR/CSS21/visudet.html#inline-replaced-width

http://www.w3.org/TR/CSS21/visudet.html#inline-replaced-height

Object and SVG Sizing Behavior

These are my observations of browser behavior, which SVG Web will try to emulate.
Specifically, SVG Web is emulating the behavior of the latest version
of Mozilla/FireFox. The rationale is that this is the browser with the highest
market share that supports SVG natively. We have made the design decision
with SVG Web that we should pick one sizing behavior and implement that
consistently instead of trying to emulate the behavior of the
browser we are running on. Users will expect sizing to be consistent and
if we do not implement that, then everyone using SVG Web will have to
fix it themselves.
Also, choosing a single behavior was pretty much a no brainer when it
became clear that the behavior of some browsers was less than ideal.

CSS1Compat (FF only)
----------

If both object width and height are specified:
   The object width is used directly.
   For object height:
       If object height is pixels that is used.
       If the object height is %:
           If width and height are both specified on the SVG file in pixels,
               then the height is calculated based on the object width and the
               aspect ratio between the svg height and width.
               If viewBox is specified:
                   ClipMode: UseNone
               If viewBox is not specified:
                   ClipMode: UseBoth
           else
               If viewBox is specified:
                   The object height is calculated using the svg width
                   and the aspect ratio from the viewBox.
                   ClipMode: UseNone
               If viewBox is not specified:
                   If the svg height is in pixels use that.
                   If the svg height is missing or %:
                       The object height is 150px.
                   ClipMode: UseBoth

If neither object width nor height are specified:
    Use BackCompat mode

If object width is specified, but object height is not specified:
    Use BackCompat mode

If only object height is specified:
    If object height is pixels that is used.
        If width and height are both specified on the SVG file in pixels,
            then the object width is calculated based on the object height and the
            aspect ratio between the svg height and width.
        else
            If viewBox is specified:
                Then the width is calculated based on the object height
                and the aspect ratio on the viewBox.
                ClipMode: UseNone
            else
                If the object width is the svg width
                ClipMode: UseBoth
    else
        The object width is the svg width.
        If the svg height is in pixels use that for height
        else
            If viewBox is specified:
                Then the height is calculated based on the object width
                and the aspect ratio on the viewBox.
                ClipMode: UseNone
            else
                height is 150

BackCompat
----------

If both object width and height are specified:
    Height and width are used directly for the size of the object/embed.
    This applies whether the dimensions are provided as a percentage,
    or any unit of measure like pixels, or a mix of both.
    This is the same for FF, Safari, and Opera.

    With respect to SVG rendering:
        If viewBox is specified:
            On Safari and Opera, if svg width and height are specified,
                then they are used to specify the area of the object
                that the viewBox will be rendered within (respecting
                preserveAspectRatio).
                (On Opera only, if svg width/height exceeds object bounds,
                scroll bars appear.)
            On Firefox, svg width and height are ignored here and the area
                the viewBox is rendered in (respecting preserveAspectRatio)
                fills the entire object area.
                ClipMode: UseNone

        If viewBox is not specified:
            Then svg width and height are used
            as clipping areas within the object area and the default viewBox
            is matched to the width and height so no scaling is done.
            SVG sizes exceeding the object area are clipped.
            ClipMode: UseBoth

If neither object width nor height are specified:
    On Safari the object defaults to 300px by 150px.

    On Opera object width is taken from the svg element (defaulting
        defaulting to 100% if not present). Percentages are based on the
        parent node.

        An SVG width percentage further determines the area of
        the object that will be available for rendering.

        For height:
          If height is specified on the SVG in pixels, then that is used.
          If height is specified in percentage:
            If viewBox is specified:
                The object height is calculated using the svg width
                and the aspect ratio from the viewBox.
                The area the viewBox is rendered in (respecting
                preserveAspectRatio) fills the entire object area
                available for rendering.

            If viewBox is not specified:
                An object height of 150px is used.
                SVG renders without scaling.

            An SVG height percentage further determines the area of
            the object that will be available for rendering.
            ClipMode: UseHeight

    On Mozilla/FF, object width is taken from the svg element (defaulting
        to 100% if not present). Percentages are based on the parent
        of the object.

        The svg width is not used further in svg rendering.

        For height:
          If height is specified on the SVG in pixels, then that is used.
          If height is specified in percentage:
            If viewBox is specified:
                The object height is calculated using the svg width
                and the aspect ratio from the viewBox.
                SVG height percentages do not appear to have any effect in
                this scenario.
                ClipMode: UseNone

            If viewBox is not specified:
                An object height of 150px is used.
                An SVG height percentage further determines the area of
                the object that will be available for rendering.
                ClipMode: UseHeight

If object width is specified, but object height is not specified:

    On Safari the object height defaults to 150px.

    On Opera, for the object height:
       If the viewBox is specified,
           Then the object height is calculated based on the object width
           and the aspect ratio on the viewBox.
           An svg width or height determines the portion of the object
           area that the viewBox will be rendered within
           starting from the top left corner of the object (defaulting to 100%).
           An svg height percentage determines the portion of
           the object area that the viewBox will be rendered within.
           The viewBox renders into resulting area.
       else if the viewBox is not specified,
           If svg height is % or missing:
               The object height is 150px.
               The svg rendering height % is relative to 150px and
               starts from the top edge of the object (defaulting to 100%).
           If svg height is pixels:
               The object (and the svg rendering) height is the svg height.
           SVG renders without scaling.
           The svg width determines the portion of the object
           area that the viewBox will be rendered within
           starting from the left edge of the object (defaulting to 100%).

    On FF, for the object height:
       If the viewBox is specified,
           If width and height are both specified on the SVG file in pixels,
               then the height is calculated based on the object width and the
               aspect ratio between the svg height and width.
               The viewBox scales into resulting area (honoring preserveAspectRatio).
               SVG height and width are not using in actual rendering.
           else
               Then the height is calculated based on the object width
               and the aspect ratio on the viewBox.
               The viewBox renders into resulting area. Note there will
               be no borders inside the object because the SVG scales
               exactly into the available space (because the aspect resolution
               was matched).
               SVG height and width are not used at all.
           ClipMode: UseNone
       else if the viewBox is not specified,
           If width and height are both specified on the SVG file in pixels,
               then the height is calculated based on the object width and the
               aspect ratio between the svg height and width.
               The viewBox scales into resulting area (honoring preserveAspectRatio).
           else
               If svg height is % or missing:
                   The object height is 150px.
                   The svg rendering height % is relative to 150px and
                   starts from the top edge of the object (defaulting to 100%).
               If svg height is pixels:
                   The object (and the svg rendering) height is the svg height.
           SVG renders without scaling.
           The svg width determines the portion of the object
           area that the viewBox will be rendered within
           starting from the left edge of the object (defaulting to 100%).
           ClipMode: UseBoth

If only object height is specified:
    On Safari the object width defaults to 300px.

    On Opera, for the object width:
       If the viewBox is specified,
           Then the width is calculated based on the object height
           and the aspect ratio on the viewBox.
           An SVG width percentage determines the portion of
           the object area that the viewBox will be rendered within.
           An SVG height percentage determines the portion of
           the object area that the viewBox will be rendered within.
           The viewBox renders into resulting area.
       else if the viewBox is not specified,
           The object width is taken from the svg width (defaulting to 100%).

           The svg width is ALSO used for the svg clipping region.
           So the same svg percent is used both to size the object and
           the svg file within the object. Okay...

           The svg height is used to define the svg rendering
           area inside the object. Percents are relative to the object
           height. No value defaults to 100%.

           Exceeding the object area results in scroll bars

    On FF, for the object width:
       Object tag height is used for object, whether % or pixels.
       If viewBox is specified:
           If width and height are both specified on the SVG file in pixels,
               then the object width is calculated based on the object height and the
               aspect ratio between the svg height and width.
           Else
               Then the width is calculated based on the object height
               and the aspect ratio on the viewBox.
           The viewBox scales into resulting area (honoring preserveAspectRatio).
           SVG height and width are not used further in actual rendering.
           ClipMode: UseNone
       If viewBox is not specified:
           The object width is taken from the svg width (defaulting to 100%).

           The svg width is ALSO used for the svg clipping region.
           So the same svg percent is used both to size the object and
           the svg file within the object. Okay...

           The svg height is used to define the svg rendering
           area inside the object. Percents are relative to the object
           height. No value defaults to 100%.

           Exceeding the object area results in scroll bars for the object.
           ClipMode: UseBoth

3. Flash Scaling

The SVG drawing coordinates are draw initially to the flash
coordinate system which, by default, are then mapped to browser coordinates.
The "preferred" size of the SVG Web flash "movie" and the resulting
coordinate system are define at flash compile time. The width and height
of the flash coordinate system is defined at the top of SVGViewerWeb.as
in the [SWF] directive. Currently, this is 2048 by 1024.

When you use SVG Web in your web page you specify a height and
width (probably in the <object> tag) and then the flash coordinates are
mapped into that height and width by flash. Flash uses the Stage.scaleMode
parameter to determine exactly how the scaling is done. By default,
it sizes the image to the object to a size which allows you to see
the entire image within the area, preserves the aspect ratio, and
is as large as possible within those constraints ("showAll").

For example, if we use the default flash scaling mode, and
you specify a width and height of an SVG object as 512 by 256 (which
applies to the resulting flash object) then the image will appear
four times smaller than would be rendered by SVG if rendered
natively because it must scale the 2048x1024 flash coordinates
each by .25 to fit into the 512x256 area.

In the default scaling mode, flash attempts to scale the flash coordinate
system (2048 x 1024) into the object space. If the object area is square,
then there would be borders above and below the flash object.

The problem with the above arises when the top svg element
uses a viewbox or width/height that is more tall than wide. In this case,
when the browser renders the SVG natively, it correctly places borders
on the sides. However, in our case, unless we specify an object size that
is wider in aspect resolution than 2048x1024 (unlikely), flash resizing
still places the borders on the top and bottom because it still thinks the
flash area is more wide than tall (2048x1024) when compared to the object
area.

The flash plugin is not aware of the svg size or aspect ratio. It is only
aware of its own coordinate space (2048x1024), which is fixed at compile time.
Therefore, we cannot rely on flash resizing to help us scale the svg the
right way. We must disable flash scaling with the "noScale" mode and
performing the scaling manually in the rendering code.


text:
#### Foreign Environment
> A foreign environment interface for Fish shell

[![MIT License](https://img.shields.io/badge/license-MIT-007EC7.svg?style=flat-square)](/LICENSE)
[![Fish Shell Version](https://img.shields.io/badge/fish-v2.2.0-007EC7.svg?style=flat-square)](http://fishshell.com)
[![Oh My Fish Framework](https://img.shields.io/badge/Oh%20My%20Fish-Framework-007EC7.svg?style=flat-square)](https://www.github.com/oh-my-fish/oh-my-fish)
[![test](https://github.com/oh-my-fish/plugin-foreign-env/actions/workflows/test.yml/badge.svg)](https://github.com/oh-my-fish/plugin-foreign-env/actions/workflows/test.yml)

Foreign environment wraps application execution in a way that environment variables that are exported or modified get imported back into fish. This makes possible running popular bash scripts, like the excellent `nvm`.

# Install

Be sure to have [Oh My Fish][omf-link] installed, so you just need to:

```fish
omf install foreign-env
```

If you dislike shell frameworks, you can still use Foreign Environment in Fish! Clone this repo somewhere and append to your `~/.config/fish/config.fish`:

```fish
set fish_function_path $fish_function_path <insert path to foreign-env repo>/functions
```

# Usage examples

You can use bash syntax to export variables:

```fish
fenv export PYTHON=python2
```

This will have the same effect as typing:

```fish
set -g -x PYTHON python2
```

You can also call multiple commands, separated by semicolon:

```fish
fenv source ~/.nvm/nvm.sh \; nvm --help
```

When commands aren't double quoted, you need to escape semicolon with slash `\;` to prevent fish from interpreting it. Or just quote the whole command:

```fish
fenv "source ~/.nvm/nvm.sh; nvm --help"
```

# Caveats

* Currently we only handle environment variables that are added or modified. If a variable is unset (removed from environment) it will not be removed from fish.

# License

[MIT][mit] © [Derek Willian Stavis][author]

[mit]:            http://opensource.org/licenses/MIT
[author]:         http://github.com/derekstavis
[omf-link]:       https://www.github.com/oh-my-fish/oh-my-fish


text:
static const char pathSeparatorBytes[] = { ';', '\0' };

static const Nucleus_Size pathSeparatorNumberOfBytes = sizeof(pathSeparatorBytes);

Nucleus_NonNull() Nucleus_Status
Nucleus_getPathSeparator
    (
        const char **bytes,
        Nucleus_Size *numberOfBytes
    )
{
    if (Nucleus_Unlikely(!bytes || !numberOfBytes)) return Nucleus_Status_InvalidArgument;
    *bytes = pathSeparatorBytes;
    *numberOfBytes = pathSeparatorNumberOfBytes;
    return Nucleus_Status_Success;
}


text:
namespace sp { namespace graphics {

	class SP_API PBRMaterial : public Material
	{
	private:
		static API::Texture2D* s_PreintegratedFG;
	public:
		PBRMaterial(String name, API::Shader* shader);
		PBRMaterial(String name, String shader = DEFAULT_SHADER_NAME);
		~PBRMaterial();

		void Init();

		void SetEnviromentMap(API::TextureCube* texture);

		// PBR Statics
		void SetAlbedo(const maths::vec4& color);
		void SetMetallic(const maths::vec3& color);
		void UsingNormalMap(bool value);

		// PBR Maps
		void SetAlbedoMap(API::Texture2D* texture);
		void SetMetallicMap(API::Texture2D* texture);
		void SetNormalMap(API::Texture2D* texture);

		API::Texture* GetAlbedoMap();
		API::Texture* GetMetallicMap();
		API::Texture* GetNormalMap();
	};

	class SP_API PBRMaterialInstance : public MaterialInstance
	{
	public:
		PBRMaterialInstance(PBRMaterial* material);
		PBRMaterialInstance(String name);

		void SetEnviromentMap(API::TextureCube* texture);

		// PBR Statics
		void SetAlbedo(const maths::vec4& color);
		void SetMetallic(const maths::vec3& color);
		void UsingNormalMap(bool value);

		// PBR Maps
		void SetAlbedoMap(API::Texture2D* texture);
		void SetMetallicMap(API::Texture2D* texture);
		void SetNormalMap(API::Texture2D* texture);
	};

} }
#endif // !PBR_MATERIAL_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Elasticsearch.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Nest.Resolvers.Converters;

using Nest.Resolvers;

namespace Nest
{
	///
	/// Provides a base for descriptors that need to describe a path in the form of
	///

	///	/{index}/{name}
	///

	/// neither parameter is optional
	///
	public class IndexNamePathDescriptor
 : BasePathDescriptor

		where P : IndexNamePathDescriptor
, new()
		where K : FluentRequestParameters<K>, new()
	{
		internal IndexNameMarker _Index { get; set; }
		internal string _Name { get; set; }

		public P Index<T>() where T : class
		{
			this._Index = typeof(T);
			return (P)this;
		}

		public P Index(string indexType)
		{
			this._Index = indexType;
			return (P)this;
		}

		public P Index(Type indexType)
		{
			this._Index = indexType;
			return (P)this;
		}

		public P Name(string name)
		{
			this._Name = name;
			return (P)this;
		}

		internal virtual ElasticsearchPathInfo<K> ToPathInfo<K>(IConnectionSettingsValues settings, K queryString)
			where K : FluentRequestParameters<K>, new()
		{
			if (this._Name == null)
				throw new DslException("missing Name()");
			var inferrer = new ElasticInferrer(settings);
			var index = inferrer.IndexName(this._Index) ?? inferrer.DefaultIndex;
			var pathInfo = new ElasticsearchPathInfo<K>()
			{
				Index = index,
				Name = this._Name
			};
			pathInfo.RequestParameters = queryString ?? new K();
			pathInfo.RequestParameters.RequestConfiguration(r=>this._RequestConfiguration);
			return pathInfo;
		}

	}
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Orleans.Hosting;
using Orleans.Runtime.TestHooks;
using Orleans.TestingHost.Utils;

namespace Orleans.TestingHost
{
    /// <summary>Configuration builder for starting a <see cref="TestCluster"/>.</summary>
    public class TestClusterBuilder
    {
        private readonly List<Action<IConfigurationBuilder>> configureHostConfigActions = new List<Action<IConfigurationBuilder>>();
        private readonly List<Action> configureBuilderActions = new List<Action>();

        /// <summary>
        /// Initializes a new instance of <see cref="TestClusterBuilder"/> using the default options.
        /// </summary>
        public TestClusterBuilder()
            : this(2)
        {
        }

        /// <summary>
        /// Initializes a new instance of <see cref="TestClusterBuilder"/> overriding the initial silos count.
        /// </summary>
        /// <param name="initialSilosCount">The number of initial silos to deploy.</param>
        public TestClusterBuilder(short initialSilosCount)
        {
            this.Options = new TestClusterOptions
            {
                InitialSilosCount = initialSilosCount,
                ClusterId = CreateClusterId(),
                ServiceId = Guid.NewGuid().ToString("N"),
                UseTestClusterMembership = true,
                InitializeClientOnDeploy = true,
                ConfigureFileLogging = true,
                AssumeHomogenousSilosForTesting = true
            };

            this.AddClientBuilderConfigurator<AddTestHooksApplicationParts>();
            this.AddSiloBuilderConfigurator<AddTestHooksApplicationParts>();
            this.ConfigureBuilder(ConfigureDefaultPorts);
        }

        public Dictionary<string, object> Properties { get; } = new Dictionary<string, object>();

        public TestClusterOptions Options { get; }

        /// <summary>
        /// Delegate used to create and start an individual silo.
        /// </summary>
        public Func<string, IList<IConfigurationSource>, Task<SiloHandle>> CreateSiloAsync { private get; set; }

        public TestClusterBuilder ConfigureBuilder(Action configureDelegate)
        {
            this.configureBuilderActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate)));
            return this;
        }

        /// <summary>
        /// Set up the configuration for the builder itself. This will be used as a base to initialize each silo host
        /// for use later in the build process. This can be called multiple times and the results will be additive.
        /// </summary>
        /// <param name="configureDelegate">The delegate for configuring the <see cref="IConfigurationBuilder"/> that will be used
        /// to construct the <see cref="IConfiguration"/> for the host.</param>
        /// <returns>The same instance of the host builder for chaining.</returns>
        public TestClusterBuilder ConfigureHostConfiguration(Action<IConfigurationBuilder> configureDelegate)
        {
            this.configureHostConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate)));
            return this;
        }

        public void AddSiloBuilderConfigurator<TSiloBuilderConfigurator>() where TSiloBuilderConfigurator : ISiloBuilderConfigurator, new()
        {
            this.Options.SiloBuilderConfiguratorTypes.Add(typeof(TSiloBuilderConfigurator).AssemblyQualifiedName);
        }

        public void AddClientBuilderConfigurator<TClientBuilderConfigurator>() where TClientBuilderConfigurator : IClientBuilderConfigurator, new()
        {
            this.Options.ClientBuilderConfiguratorTypes.Add(typeof(TClientBuilderConfigurator).AssemblyQualifiedName);
        }

        public TestCluster Build()
        {
            var configBuilder = new ConfigurationBuilder();

            foreach (var action in configureBuilderActions)
            {
                action();
            }

            configBuilder.AddInMemoryCollection(this.Options.ToDictionary());
            foreach (var buildAction in this.configureHostConfigActions)
            {
                buildAction(configBuilder);
            }

            var configuration = configBuilder.Build();
            var finalOptions = new TestClusterOptions();
            configuration.Bind(finalOptions);

            var configSources = new ReadOnlyCollection<IConfigurationSource>(configBuilder.Sources);
            var testCluster = new TestCluster(finalOptions, configSources);
            if (this.CreateSiloAsync != null) testCluster.CreateSiloAsync = this.CreateSiloAsync;
            return testCluster;
        }

        public static string CreateClusterId()
        {
            string prefix = "testcluster-";
            int randomSuffix = ThreadSafeRandom.Next(1000);
            DateTime now = DateTime.UtcNow;
            string DateTimeFormat = @"yyyy-MM-dd\tHH-mm-ss";
            return $"{prefix}{now.ToString(DateTimeFormat, CultureInfo.InvariantCulture)}-{randomSuffix}";
        }

        private void ConfigureDefaultPorts()
        {
            // Set base ports if none are currently set.
            (int baseSiloPort, int baseGatewayPort) = GetAvailableConsecutiveServerPortsPair(this.Options.InitialSilosCount + 3);
            if (this.Options.BaseSiloPort == 0) this.Options.BaseSiloPort = baseSiloPort;
            if (this.Options.BaseGatewayPort == 0) this.Options.BaseGatewayPort = baseGatewayPort;
        }

        // Returns a pairs of ports which have the specified number of consecutive ports available for use.
        internal static ValueTuple<int, int> GetAvailableConsecutiveServerPortsPair(int consecutivePortsToCheck = 5)
        {
            // Evaluate current system tcp connections
            IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();

            // each returned port in the pair will have to have at least this amount of available ports following it

            return (GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 22300, 30000, consecutivePortsToCheck),
                GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 40000, 50000, consecutivePortsToCheck));
        }

        private static int GetAvailableConsecutiveServerPorts(IPEndPoint[] tcpConnInfoArray, int portStartRange, int portEndRange, int consecutivePortsToCheck)
        {
            const int MaxAttempts = 10;

            for (int attempts = 0; attempts < MaxAttempts; attempts++)
            {
                int basePort = ThreadSafeRandom.Next(portStartRange, portEndRange);

                // get ports in buckets, so we don't interfere with parallel runs of this same function
                basePort = basePort - (basePort % consecutivePortsToCheck);
                int endPort = basePort + consecutivePortsToCheck;

                // make sure non of the ports in the sub range are in use
                if (tcpConnInfoArray.All(endpoint => endpoint.Port < basePort || endpoint.Port >= endPort))
                    return basePort;
            }

            throw new InvalidOperationException("Cannot find enough free ports to spin up a cluster");
        }

        internal class AddTestHooksApplicationParts : IClientBuilderConfigurator, ISiloBuilderConfigurator
        {
            public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
            {
                clientBuilder.ConfigureApplicationParts(parts => parts.AddFrameworkPart(typeof(ITestHooksSystemTarget).Assembly));
            }

            public void Configure(ISiloHostBuilder hostBuilder)
            {
                hostBuilder.ConfigureApplicationParts(parts => parts.AddFrameworkPart(typeof(ITestHooksSystemTarget).Assembly));
            }
        }
    }
}


text:
package co.cask.cdap.proto.metadata;

import co.cask.cdap.api.annotation.Beta;

import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Represents metadata (properties and tags) of an entity.
 */
@Beta
public class Metadata {
  private final Map<String, String> properties;
  private final Set<String> tags;

  public Metadata(Map<String, String> properties, Set<String> tags) {
    this.properties = properties;
    this.tags = tags;
  }

  public Map<String, String> getProperties() {
    return properties;
  }

  public Set<String> getTags() {
    return tags;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof Metadata)) {
      return false;
    }
    Metadata that = (Metadata) o;
    return Objects.equals(properties, that.properties) &&
      Objects.equals(tags, that.tags);
  }

  @Override
  public int hashCode() {
    return Objects.hash(properties, tags);
  }

  @Override
  public String toString() {
    return "Metadata{" +
      "properties=" + properties +
      ", tags=" + tags +
      '}';
  }
}


text:
/**
 * @file SizeTag
 * @author peter.szocs
 * @version 1.0
 *
 * Print the size of the collection.
 */

package com.vh.manchester.taglib;

import java.util.Collection;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;

import org.apache.strutsel.taglib.utils.EvalHelper;

import com.vh.manchester.util.MessageUtils;

/**
 * The VH Corporation
 *
 * Copyright (c) 2005 The VH Corporation.  All rights reserved.
 * Copying or reproduction without prior written approval is prohibited.
 *
 * @author  Peter.Szocs
 * @version 1.0
 */
public class SizeTag extends TagSupport {
  private static Logger log=Logger.getLogger(SizeTag.class);
  private String collName=null;
  private String scope=null;

  public void setCollection(String string) {
	collName = string;
  }

  public void setScope(String string) {
	scope = string;
  }

  public int doStartTag() throws JspException {
	JspWriter out = pageContext.getOut();
	try {
      EvalHelper.evalString("collection", collName, this, pageContext);
      if((collName!=null) && (!"".equals(collName))) {
        //init theColl (the actual collection)
        Collection theColl=null;
		int theScope=1;
		EvalHelper.evalString("scope", scope, this, pageContext);
		if((scope!=null) && (!"".equals(scope))) {
          if("page".equalsIgnoreCase(scope)) theScope=0;
          else if("session".equalsIgnoreCase(scope)) theScope=2;
		  else if("application".equalsIgnoreCase(scope)) theScope=3;
		}
		switch(theScope) {
          case 0: theColl=(Collection) pageContext.getAttribute(collName); break;
          case 1: theColl=(Collection) pageContext.getRequest().getAttribute(collName); break;
          case 2: theColl=(Collection) pageContext.getSession().getAttribute(collName); break;
          case 3: theColl=(Collection) pageContext.getServletContext().getAttribute(collName); break;
          default:theColl=(Collection) pageContext.getRequest().getAttribute(collName); break;
		}
        //print size
        if(theColl!=null) out.print(theColl.size());
        else out.print("Collection '"+collName+"' cannot be found in '"+scope+"' scope");
      }
	} catch(Exception e) {
      log.error(e.getMessage());
      throw new JspException(e.toString());
	}
	return EVAL_PAGE;
  }

}


text:
import config from 'config';
import knex from 'knex';

export default knex(config.get('database'));


text:
package de.ks.strudel.mustache;

import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import de.ks.strudel.template.TemplateEngine;

import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.StringWriter;

@Singleton
public class MustacheEngine implements TemplateEngine {
  private final MustacheFactory factory;

  @Inject
  public MustacheEngine(MustacheFactory factory) {
    this.factory = factory;
  }

  @Override
  public String render(Object model, String view) throws Exception {
    Mustache mustache = factory.compile(view);
    StringWriter writer = new StringWriter();
    mustache.execute(writer, model);
    String html = writer.toString();
    return html;
  }
}


text:
"""
This is a template script - an example of how a CEA script should be set up.
NOTE: ADD YOUR SCRIPT'S DOCUMENTATION HERE (what, why, include literature references)
"""

import math
import os
from typing import Union

import numpy as np
import osmnx.footprints
from geopandas import GeoDataFrame as Gdf
from geopandas.tools import overlay
from shapely.geometry import Polygon
import pandas as pd

import cea.config
import cea.inputlocator
from cea.datamanagement.databases_verification import COLUMNS_ZONE_TYPOLOGY
from cea.demand import constants
from cea.datamanagement.constants import OSM_BUILDING_CATEGORIES, OTHER_OSM_CATEGORIES_UNCONDITIONED, GRID_SIZE_M, EARTH_RADIUS_M
from cea.utilities.dbf import dataframe_to_dbf
from cea.utilities.standardize_coordinates import get_projected_coordinate_system, get_geographic_coordinate_system

__author__ = "Jimeno Fonseca"
__copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Jimeno Fonseca", "Reynold Mok"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Daren Thomas"
__email__ = "cea@arch.ethz.ch"
__status__ = "Production"

def parse_building_floors(floors):
    """
    Tries to parse string of `building:levels` from OSM data to get the number of floors as a float.
    If the string is a list of numerical values separated by commas or semicolons, it will return the maximum value.
    It returns NaN if it is unable to parse the value.

    :param str floors: String representation of number of floors from OSM
    :return: Number of floors as a float or NaN
    """
    import re
    try:
        parsed_floors = float(floors)  # Try casting string to float
    except ValueError:
        separators = [',', ';']  # Try matching with different separators
        separated_values = r'^(?:\d+(?:\.\d+)?(?:{separator}\s?)?)+$'
        for separator in separators:
            match = re.match(separated_values.format(separator=separator), floors)
            if match:
                return max([float(x.strip() or 0) for x in floors.split(separator)])
        return np.nan
    else:
        return parsed_floors

def assign_attributes(shapefile, buildings_height, buildings_floors, buildings_height_below_ground,
                      buildings_floors_below_ground, key):
    # local variables
    no_buildings = shapefile.shape[0]
    list_of_columns = shapefile.columns
    if buildings_height is None and buildings_floors is None:
        print('Warning! You have not indicated number of floors above ground for the buildings, '
              'we are importing data from Open Street Maps (It might not be accurate at all), '
              'if we do not find data in OSM for a particular building, we get the median in the surroundings, '
              'if we do not get any data we assume 4 floors per building (3 above, 1 below ground)')

        print('Warning! You have not indicated height above ground for the buildings, '
              'we are importing data from Open Street Maps (It might not be accurate at all), '
              'if we do not find data in OSM for a particular building, we estimate it based on the number of floors, '
              'multiplied by a pre-defined floor-to-floor height (set to 3m by default)')

        # Make sure relevant OSM parameters (if available) are passed as floats, not strings
        OSM_COLUMNS = ['building:min_level', 'min_height', 'building:levels', 'height']
        selected_columns = list(set(list_of_columns).intersection(set(OSM_COLUMNS)))
        shapefile[selected_columns] = shapefile[selected_columns] \
            .fillna(1).apply(lambda x: pd.to_numeric(x, errors='coerce'))

        # Make sure relevant OSM parameters (if available) are passed as floats, not strings
        OSM_COLUMNS = ['building:min_level', 'min_height', 'building:levels', 'height']
        shapefile[[c for c in OSM_COLUMNS if c in list_of_columns]] = \
            shapefile[[c for c in OSM_COLUMNS if c in list_of_columns]].fillna(1) \
                .apply(lambda x: pd.to_numeric(x, errors='coerce'))

        # Check which attributes OSM has (sometimes it does not have any) and indicate the data source
        if 'building:levels' not in list_of_columns:
            # if 'building:levels' is not in the database, make an assumption
            shapefile['building:levels'] = [3] * no_buildings
            shapefile['REFERENCE'] = "CEA - assumption"
        elif pd.isnull(shapefile['building:levels']).all():
            # if 'building:levels' are all NaN, make an assumption
            shapefile['building:levels'] = [3] * no_buildings
            shapefile['REFERENCE'] = "CEA - assumption"
        elif 'height' in list_of_columns:
            # if either the 'building:levels' or the building 'height' are available, take them from OSM
            shapefile['REFERENCE'] = ["OSM - as it is" if x else "OSM - median values of all buildings" for x in
                                      (~shapefile['building:levels'].isna()) | (shapefile['height'] > 0)]
        else:
            # if only the 'building:levels' are available, take them from OSM
            shapefile['REFERENCE'] = ["OSM - as it is" if x else "OSM - median values of all buildings" for x in
                                      ~shapefile['building:levels'].isna()]
        if 'roof:levels' not in list_of_columns:
            shapefile['roof:levels'] = 0

        # get the median from the area:
        data_osm_floors1 = shapefile['building:levels'].fillna(0)
        data_osm_floors2 = shapefile['roof:levels'].fillna(0)
        data_floors_sum = [x + y for x, y in zip([parse_building_floors(x) for x in data_osm_floors1],
                                                 [parse_building_floors(y) for y in data_osm_floors2])]
        data_floors_sum_with_nan = [np.nan if x < 1.0 else x for x in data_floors_sum]
        data_osm_floors_joined = math.ceil(
            np.nanmedian(data_floors_sum_with_nan))  # median so we get close to the worse case
        shapefile["floors_ag"] = [int(x) if not np.isnan(x) else data_osm_floors_joined for x in
                                  data_floors_sum_with_nan]

        if 'height' in list_of_columns:
            #  Replaces 'nan' values with CEA assumption
            shapefile["height_ag"] = shapefile["height"].fillna(shapefile["floors_ag"] * constants.H_F).astype(float)
            #  Replaces values of height = 0 with CEA assumption
            # TODO: Check whether buildings with height between 0 and 1 meter are actually mostly underground
            #  These might not be errors, but rather partially or fully underground buildings. This should be verified.
            #  Also, the radiation script cannot process buildings with height 0 m at the moment.
            #  Once the radiation script can process underground buildings, this step might need to be revised.
            shapefile["height_ag"] = shapefile["height_ag"].where(shapefile["height_ag"] != 0,
                                                                  shapefile["floors_ag"] * constants.H_F).astype(float)
        else:
            shapefile["height_ag"] = shapefile["floors_ag"] * constants.H_F

        # add fields for floors and height below ground
        shapefile["height_bg"] = None
        shapefile["floors_bg"] = None

        # Correct levels below ground if a minimum floor level or height is indicated
        if 'building:min_level' in list_of_columns:
            has_min_floor = shapefile["building:min_level"] == shapefile["building:min_level"]
            shapefile[has_min_floor].floors_bg = [- int(x) for x in shapefile[has_min_floor]["building:min_level"]]
            shapefile[has_min_floor].height_bg = shapefile[has_min_floor].floors_bg * constants.H_F
        if 'min_height' in list_of_columns:
            has_min_height = shapefile["min_height"] == shapefile["min_height"]
            shapefile[has_min_height].height_bg = [- int(x) for x in shapefile[has_min_height]["min_height"]]
        # add missing floors and height below ground
        shapefile.loc[shapefile.height_bg.isna(), "height_bg"] = [buildings_height_below_ground] * no_buildings
        shapefile.loc[shapefile.floors_bg.isna(), "floors_bg"] = [buildings_floors_below_ground] * no_buildings
    else:
        shapefile['REFERENCE'] = "User - assumption"
        if buildings_height is None and buildings_floors is not None:
            shapefile["floors_ag"] = [buildings_floors] * no_buildings
            shapefile["height_ag"] = shapefile["floors_ag"] * constants.H_F
        elif buildings_height is not None and buildings_floors is None:
            shapefile["height_ag"] = [buildings_height] * no_buildings
            shapefile["floors_ag"] = [int(math.floor(x)) for x in shapefile["height_ag"] / constants.H_F]
        else:  # both are not none
            shapefile["height_ag"] = [buildings_height] * no_buildings
            shapefile["floors_ag"] = [buildings_floors] * no_buildings
        # add fields for floors and height below ground
        shapefile["height_bg"] = [buildings_height_below_ground] * no_buildings
        shapefile["floors_bg"] = [buildings_floors_below_ground] * no_buildings

    # add description
    if "description" in list_of_columns:
        shapefile["description"] = shapefile['description']
    elif 'addr:housename' in list_of_columns:
        shapefile["description"] = shapefile['addr:housename']
    elif 'amenity' in list_of_columns:
        shapefile["description"] = shapefile['amenity']
    else:
        shapefile["description"] = [np.nan] * no_buildings

    shapefile["category"] = shapefile['building']
    if 'amenity' in list_of_columns:
        # in OSM, "amenities" (where available) supersede "building" categories
        in_categories = shapefile['amenity'].isin(OSM_BUILDING_CATEGORIES.keys())
        shapefile.loc[in_categories, '1ST_USE'] = shapefile[in_categories]['amenity'].map(OSM_BUILDING_CATEGORIES)

    shapefile["Name"] = [key + str(x + 1000) for x in
                         range(no_buildings)]  # start in a big number to avoid potential confusion
    shapefile.reset_index(inplace=True, drop=True)

    return shapefile

def fix_overlapping_geoms(buildings, zone):
    """
    This function eliminates overlapping geometries. To decide which portions of two overlapping geometries to
    eliminate, the functions abides by the following rules:
        1. If two buildings' footprints overlap, check if they also overlap vertically, i.e. height of ground surface
            of building A < height of roof of building B (this is only really relevant for buildings that have
            'floating' elements, e.g. Marina Bay Sands 'boat').
        2. If they also overlap vertically, cut the overlapping portion of the taller building's footprint out of the
            lower building's footprint-polygon.

    As a preprocessing step the OSM-information on "min_heights" and "min_levels" gets assigned to the building's
    height and levels below ground (introduced in the zone-helper.assign_attributes() function) as negative values.
    """
    # PREPROCESSING OF BUILDING ATTRIBUTES
    # get zone's geometry
    geometries = buildings.geometry

    # CREATE GRID TO PARTITION THE BUILDINGS (more efficient - hopefully)
    # calculate grid-parameters based on the zone polygon dimensions
    [[west_bound_long, south_bound_lat, east_bound_long, north_bound_lat]] = zone.bounds.to_numpy()
    [(centroid_long, centroid_lat)] = zone.centroid.get(0).coords[:]
    grid_size_long = 180 * GRID_SIZE_M / (np.pi * EARTH_RADIUS_M * np.cos(centroid_lat * np.pi / 180))
    grid_size_lat = 180 * GRID_SIZE_M / (np.pi * EARTH_RADIUS_M)
    n_grid_cells_long = math.ceil((east_bound_long - west_bound_long) / grid_size_long)
    n_grid_cells_lat = math.ceil((north_bound_lat - south_bound_lat) / grid_size_lat)
    grid_cells = []

    # create 500m * 500m grid
    for i in range(n_grid_cells_lat):
        for j in range(n_grid_cells_long):
            dx_0 = j * grid_size_long
            dx_1 = (j + 1) * grid_size_long
            dy_0 = i * grid_size_lat
            dy_1 = (i+1) * grid_size_lat
            cell_vertices = [(west_bound_long + dx_0, north_bound_lat - dy_0),
                             (west_bound_long + dx_1, north_bound_lat - dy_0),
                             (west_bound_long + dx_1, north_bound_lat - dy_1),
                             (west_bound_long + dx_0, north_bound_lat - dy_1),
                             (west_bound_long + dx_0, north_bound_lat - dy_0)]
            grid_cells.append(Polygon(cell_vertices))
    grid = Gdf(geometry=grid_cells, crs="EPSG:4326")

    # FIX OVERLAYS IN THE BUILDING GEOMETRIES
    # overlay the grid with the zone polygon, retaining the overlapping grid cells, and ...
    grid = zone.overlay(grid, how="intersection")

    # iterate through the grid cells, overlaying them with the buildings, retaining the buildings
    for cell_index in range(grid.geometry.size):
        cell = Gdf(geometry=[grid.geometry[cell_index]], crs="EPSG:4326")
        is_intersecting = geometries.intersects(cell.geometry[0])
        buildings_in_cell = buildings[is_intersecting]

        # check each building for intersections with other buildings - if intersection is found:
        for building_index in buildings_in_cell.index:
            is_overlapping = buildings_in_cell.geometry.intersects(buildings_in_cell.geometry[building_index])
            overlapping_buildings = buildings_in_cell[is_overlapping]
            # check if all overlapping buildings have building use type information from OSM, if not assign mode of all overlapping buildings
            for col in ['building', 'amenity', "description", "category"]:
                if np.any(overlapping_buildings[col].isna()) & ~np.all(overlapping_buildings[col].isna()):
                    buildings.loc[overlapping_buildings.loc[overlapping_buildings[col].isna()].index, col] = \
                        overlapping_buildings[col].dropna().mode()[0]
            # cut out the higher building's footprint-polygon out the lower buildings footprint-polygon
            for ovrlp_bldg_index in overlapping_buildings.index:
                if ovrlp_bldg_index == building_index:
                    pass  # same building -> doesn't count as overlap
                elif (buildings.height_ag[ovrlp_bldg_index] <= -buildings.height_bg[building_index]) or \
                    (buildings.height_ag[building_index] <= -buildings.height_bg[ovrlp_bldg_index]):
                    pass  # no vertical overlap
                elif (buildings.REFERENCE[ovrlp_bldg_index] == "OSM - as it is") & \
                     (buildings.REFERENCE[building_index] != "OSM - as it is"):  # Give OSM priority
                    buildings.geometry[building_index] = \
                        buildings.geometry[building_index].difference(buildings.geometry[ovrlp_bldg_index])
                elif (buildings.REFERENCE[building_index] == "OSM - as it is") & \
                     (buildings.REFERENCE[ovrlp_bldg_index] != "OSM - as it is"):  # Give OSM priority
                    buildings.geometry[ovrlp_bldg_index] = \
                        buildings.geometry[ovrlp_bldg_index].difference(buildings.geometry[building_index])
                elif (buildings.height_ag[building_index] + buildings.height_bg[building_index]) <= \
                        (buildings.height_ag[ovrlp_bldg_index] + buildings.height_bg[ovrlp_bldg_index]):
                    buildings.geometry[building_index] = \
                        buildings.geometry[building_index].difference(buildings.geometry[ovrlp_bldg_index])
                elif (buildings.height_ag[building_index] + buildings.height_bg[building_index]) > \
                        (buildings.height_ag[ovrlp_bldg_index] + buildings.height_bg[ovrlp_bldg_index]):
                    buildings.geometry[ovrlp_bldg_index] = \
                        buildings.geometry[ovrlp_bldg_index].difference(buildings.geometry[building_index])

    return buildings

def zone_helper(locator, config):
    """
    This script gets a polygon and calculates the zone.shp and the occupancy.dbf and age.dbf inputs files for CEA
    :param locator:
    :param config:
    :return:
    """
    # local variables:
    poly = Gdf.from_file(locator.get_site_polygon())
    buildings_height = config.zone_helper.height_ag
    buildings_floors = config.zone_helper.floors_ag
    buildings_height_below_ground = config.zone_helper.height_bg
    buildings_floors_below_ground = config.zone_helper.floors_bg
    occupancy_type = config.zone_helper.occupancy_type
    year_construction = config.zone_helper.year_construction
    include_building_parts = config.zone_helper.include_building_parts
    fix_overlapping = config.zone_helper.fix_overlapping_geometries
    zone_output_path = locator.get_zone_geometry()
    typology_output_path = locator.get_building_typology()

    # ensure folders exist
    locator.ensure_parent_folder_exists(zone_output_path)
    locator.ensure_parent_folder_exists(typology_output_path)

    # get zone.shp file and save in folder location
    zone_df = polygon_to_zone(buildings_floors, buildings_floors_below_ground, buildings_height,
                              buildings_height_below_ground,
                              fix_overlapping, include_building_parts,
                              poly, zone_output_path)

    # USE_A zone.shp file contents to get the contents of occupancy.dbf and age.dbf
    calculate_typology_file(locator, zone_df, year_construction, occupancy_type, typology_output_path)

def calc_category(standard_db, year_array):
    def category_assignment(year):
        within_year = (standard_db['YEAR_START'] <= year) & (standard_db['YEAR_END'] >= year)
        standards = standard_db.STANDARD.values

        # Filter standards if found
        if within_year.any():
            standards = standards[within_year]

        # Just return first value
        return standards[0]

    category = np.array([category_assignment(y) for y in year_array])
    return category

def calculate_typology_file(locator, zone_df, year_construction, occupancy_type, occupancy_output_path):
    """
    This script fills in the typology.dbf file with one occupancy type
    :param zone_df:
    :param occupancy_type:
    :param occupancy_output_path:
    :return:
    """
    # calculate construction year
    typology_df = calculate_age(zone_df, year_construction)

    # calculate the most likely construction standard
    standard_database = pd.read_excel(locator.get_database_construction_standards(), sheet_name='STANDARD_DEFINITION')
    typology_df['STANDARD'] = calc_category(standard_database, typology_df['YEAR'].values)

    # Calculate the most likely use type
    typology_df['1ST_USE'] = "NONE"
    typology_df['1ST_USE_R'] = 1.0
    typology_df['2ND_USE'] = "NONE"
    typology_df['2ND_USE_R'] = 0.0
    typology_df['3RD_USE'] = "NONE"
    typology_df['3RD_USE_R'] = 0.0
    if occupancy_type == "Get it from open street maps":
        # for OSM building/amenity types with a clear CEA use type, this use type is assigned
        in_categories = zone_df['category'].isin(OSM_BUILDING_CATEGORIES.keys())
        zone_df.loc[in_categories, '1ST_USE'] = zone_df[in_categories]['category'].map(OSM_BUILDING_CATEGORIES)
        if 'amenity' in zone_df.columns:
            # assign use type by building category first, then by amenity (more specific)
            in_categories = zone_df['amenity'].isin(OSM_BUILDING_CATEGORIES.keys())
            zone_df.loc[in_categories, '1ST_USE'] = zone_df[in_categories]['amenity'].map(OSM_BUILDING_CATEGORIES)

        # for un-conditioned OSM building categories without a clear CEA use type, "PARKING" is assigned
        if 'amenity' in zone_df.columns:
            in_unconditioned_categories = zone_df['category'].isin(OTHER_OSM_CATEGORIES_UNCONDITIONED) | zone_df['amenity'].isin(OTHER_OSM_CATEGORIES_UNCONDITIONED)
        else:
            in_unconditioned_categories = zone_df['category'].isin(OTHER_OSM_CATEGORIES_UNCONDITIONED)
        zone_df.loc[in_unconditioned_categories, '1ST_USE'] = "PARKING"

    # all remaining building use types are assigned by the mode of the use types in the entire case study
    typology_df.loc[typology_df['1ST_USE'] == "NONE", '1ST_USE'] = \
        typology_df.loc[~typology_df['1ST_USE'].isin(['NONE', 'PARKING']), '1ST_USE'].mode()[0]

    # export typology.dbf
    fields = COLUMNS_ZONE_TYPOLOGY
    dataframe_to_dbf(typology_df[fields + ['REFERENCE']], occupancy_output_path)

def parse_year(year: Union[str, int]) -> int:
    import re
    # `start-date` formats can be found here https://wiki.openstreetmap.org/wiki/Key:start_date#Formatting
    if type(year) == str:
        # For year in "century" format e.g. `C19`
        century_year = re.search(r'C(\d{2})', year)
        if century_year:
            return int(f"{century_year.group(1)}00")

        # For any four digits in a string e.g. `1860s` or `late 1920s`
        four_digit = re.search(r'\d{4}', year)
        if four_digit:
            return int(four_digit.group(0))

        # Finally try to cast string to int
        try:
            return int(year)
        except ValueError:
            # Raise error later
            pass

        raise ValueError(f"Invalid year format found `{year}`")
    else:
        return year

def calculate_age(zone_df, year_construction):
    """
    This script fills in the age.dbf file with one year of construction
    :param zone_df:
    :param year_construction:
    :param age_output_path:
    :return:
    """
    if year_construction is None:
        print('Warning! you have not indicated a year of construction for the buildings, '
              'we are importing data from Open Street Maps (It might not be accurate at all), '
              'if we do not find data in OSM for a particular building, we get the median in the surroundings, '
              'if we do not get any data we assume all buildings being constructed in the year 2000')
        list_of_columns = zone_df.columns
        if "start_date" not in list_of_columns:  # this field describes the construction year of buildings
            zone_df["start_date"] = 2000
            zone_df['REFERENCE'] = "CEA - assumption"
        else:
            zone_df['REFERENCE'] = ["OSM - median" if x is np.nan else "OSM - as it is" for x in zone_df['start_date']]

        data_age = [np.nan if x is np.nan else parse_year(x) for x in zone_df['start_date']]
        data_osm_floors_joined = int(math.ceil(np.nanmedian(data_age)))  # median so we get close to the worse case
        zone_df["YEAR"] = [int(x) if x is not np.nan else data_osm_floors_joined for x in data_age]
    else:
        zone_df['YEAR'] = year_construction
        zone_df['REFERENCE'] = "CEA - assumption"

    return zone_df

def polygon_to_zone(buildings_floors, buildings_floors_below_ground, buildings_height, buildings_height_below_ground,
                    fix_overlapping, include_building_parts, poly, zone_out_path):
    poly = poly.to_crs(get_geographic_coordinate_system())
    lon = poly.geometry[0].centroid.coords.xy[0][0]
    lat = poly.geometry[0].centroid.coords.xy[1][0]
    # get all footprints in the district tagged as 'building' or 'building:part' in OSM
    shapefile = osmnx.footprints.footprints_from_polygon(polygon=poly['geometry'].values[0], footprint_type='building')
    if include_building_parts:
        # get all footprints in the district tagged as 'building' or 'building:part' in OSM
        shapefile = pd.concat(
            [shapefile,
             osmnx.footprints.footprints_from_polygon(polygon=poly['geometry'].values[0], footprint_type='building:part')],
            ignore_index=True)
        # using building:part tags requires fixing overlapping polygons
        if not fix_overlapping:
            print('Building parts included, fixing overlapping geometries activated.')
            fix_overlapping = True

    # clean geometries
    shapefile = clean_geometries(shapefile)

    # clean attributes of height, name and number of floors
    shapefile = assign_attributes(shapefile, buildings_height, buildings_floors,
                                 buildings_height_below_ground, buildings_floors_below_ground, key="B")

    # fix geometries of buildings with overlapping polygons
    if fix_overlapping is True:
        print("Fixing overlapping geometries.")
        shapefile = fix_overlapping_geoms(shapefile, poly)

        # Clean up geometries that are no longer in use (i.e. buildings that have empty geometry)
        shapefile = shapefile[~shapefile.geometry.is_empty]
        # Pass the Gdf back to flatten_geometries to split MultiPolygons that might have been created due to one
        # building cutting another one into pieces and remove any unusable geometry types (e.g., LineString)
        shapefile = flatten_geometries(shapefile)
        # reassign building names to account for exploded MultiPolygons
        shapefile["Name"] = ["B" + str(x + 1000) for x in range(shapefile.shape[0])]

    # clean up attributes
    cleaned_shapefile = shapefile[
        ["Name", "height_ag", "floors_ag", "height_bg", "floors_bg", "description", "category", "geometry",
         "REFERENCE"]]
    cleaned_shapefile = cleaned_shapefile.to_crs(get_projected_coordinate_system(float(lat), float(lon)))

    # save shapefile to zone.shp
    cleaned_shapefile.to_file(zone_out_path)

    return shapefile

def clean_geometries(gdf):
    """
    Takes in a GeoPandas DataFrame and making sure all geometries are of type 'Polygon' and remove any entries that do
    not have any geometries
    :param gdf: GeoPandas DataFrame containing geometries
    :return:
    """
    gdf = flatten_geometries(gdf)
    gdf = gdf[gdf.geometry.notnull()]  # remove None geometries

    return gdf

def flatten_geometries(gdf):
    """
    Flatten polygon collections into a single polygon by using their union
    :param gdf: GeoDataFrame
    :return:
    """
    from shapely.ops import unary_union
    import string
    DISCARDED_GEOMETRY_TYPES = ['Point', 'LineString']

    # Explode MultiPolygons and GeometryCollections
    gdf = gdf.explode()
    # Drop geometry types that cannot be processed by CEA
    gdf = gdf.loc[~ gdf.geometry.geom_type.isin(DISCARDED_GEOMETRY_TYPES)]
    # Process individual geometries in MultiPolygon and GeometryCollection data types
    for i in gdf.loc[gdf.index.get_level_values(1) == 1].index.get_level_values(0):
        # if polygons can be joined into one Polygon, keep the joined Polygon
        if unary_union(list(gdf.loc[gdf.index.get_level_values(0) == i].geometry)) == 'Polygon':
            gdf.loc[gdf.index.get_level_values(0) == i].geometry = unary_union(list(
                gdf.loc[gdf.index.get_level_values(0) == i].geometry))
            gdf.drop(gdf.loc[(gdf.index.get_level_values(0) == i) &
                             (gdf.index.get_level_values(1) == 0)].index, inplace=True)
        # else, polygons are joined into a MultiPolygon, keep each individual Polygon as a separate building
    # rename buildings
    gdf = gdf.reset_index(drop=True)

    return gdf

def main(config):
    """
    This script gets a polygon and calculates the zone.shp and the occupancy.dbf and age.dbf inputs files for CEA
    """
    assert os.path.exists(config.scenario), 'Scenario not found: %s' % config.scenario
    locator = cea.inputlocator.InputLocator(config.scenario)

    zone_helper(locator, config)

if __name__ == '__main__':
    main(cea.config.Configuration())


text:
from django.test import TestCase
from test_app.models import MonitorAllFields, MonitorSomeFields

class MonitoredModelRevert(TestCase):
    def test_instance_is_changed___reverted_to_its_original_value(self):
        m = MonitorAllFields(first_field=1)
        m.first_field = 2
        m.revert()

        self.assertEqual(1, m.first_field)

    def test_instance_of_model_with_partially_monitored_fields_change_to_monitored_field___reverted_to_its_original_value(self):
        m = MonitorSomeFields(monitored_field=1)
        m.monitored_field = 2
        m.revert()

        self.assertEqual(1, m.monitored_field)

    def test_instance_of_model_with_partially_monitored_fields_change_to_unmonitored_field___not_reverted_to_its_original_value(self):
        m = MonitorSomeFields(unmonitored_field=1)
        m.unmonitored_field = 2
        m.revert()

        self.assertEqual(2, m.unmonitored_field)


text:
define(
"dojox/editor/plugins/nls/nl/SpellCheck", //begin v1.x content
({
	widgetLabel: "Groepsgewijze spellingcontrole",
	unfound: "Niet gevonden",
	skip: "Overslaan",
	skipAll: "Alle overslaan",
	toDic: "Toevoegen aan woordenboek",
	suggestions: "Suggesties",
	replace: "Vervangen",
	replaceWith: "Vervangen door",
	replaceAll: "Alle vervangen",
	cancel: "Annuleren",
	msg: "Geen spelfouten gevonden",
	iSkip: "Deze overslaan",
	iSkipAll: "Al deze overslaan",
	iMsg: "Geen spellingsuggesties"
})

//end v1.x content
);