text:
[XEP-0030: Service Discovery][Service Discovery] allows you to discover features and items of another XMPP entity.

By enabling an extension (XEP), you automatically support it and it will be listed in the feature list of your service discovery response.

E.g., if you have enabled support for [XEP-0092: Software Version][Software Version] your client automatically includes this XEP in its feature list, when it responds to a query.

Generally speaking all enabled extensions will be added to the feature list of service discovery. If you disable a certain extension, it will be removed.

## Discovering Information

You discover information about another XMPP entity by sending a request to it:

```java
ServiceDiscoveryManager serviceDiscoveryManager = xmppClient.getManager(ServiceDiscoveryManager.class);
InfoNode infoNode = serviceDiscoveryManager.discoverInformation(Jid.of("example.net")).getResult();
```

`infoNode` will contain information about the entity, i.e. its identity and features it supports.

### Determining Feature Support

For most use cases you are probably only interested if another entity supports a specific feature.

Because that use case is specified by nearly every XEP ("determining support"), there's a convenience method for it directly on `XmppClient`, which internally also uses [XEP-0115: Entity Capabilities][Entity Capabilities] (for optimization and caching):

```
boolean supportsChatStates = xmppClient.isSupported(ChatState.NAMESPACE, Jid.of("romeo@example.net/park")).getResult();
```

Note that the passed JID should be a full JID in most cases (if you want to check client capabilities).

This method will first check the cache for entity capabilities. Only if no cache entry is found it will ask the entity via Service Discovery.

## Discovering Items

You can also discover items associated with an XMPP entity.

```
ItemNode node = serviceDiscoveryManager.discoverItems(Jid.of("example.net")).getResult();
List<Item> items = node.getItems();
```

This will discover items at the "root" node, but you can also discover items at another node:

```
ItemNode node = serviceDiscoveryManager.discoverItems(Jid.of("example.net"), "music").getResult();
List<Item> items = node.getItems();
```

### Limited Result Sets

You can request a limited result set like this, which will request the first 20 items:

```
ItemNode itemNode = serviceDiscoveryManager.discoverItems(Jid.of("example.net"), ResultSetManagement.forLimit(20)).getResult();
List<Item> items = itemNode.getItems();
```

For more limited result set options refer to `ResultSetManagement`.

## Discovering Services

The following would discover Multi-User Chat services at your server:

```
serviceDiscoveryManager.discoverServices(Muc.NAMESPACE).getResult();
```

## Providing Items

If you want to publish items yourself (which then can be discovered by other entities), you should set an item provider like this:

```
Collection<Item> myItems = ...;
serviceDiscoveryManager.setItemProvider(new DefaultItemProvider(myItems));
```

The `DefaultItemProvider` keeps the items in memory. If you want to set another source as items (e.g. from a database), create your own implementation of
`ResultSetProvider<Item>` instead.

### Result Set Management

`ResultSetProvider<T>` provides methods which are necessary for enabling support for [XEP-0059: Result Set Management][Result Set Management]:

```
public interface ResultSetProvider<T extends ResultSetItem> {
    List<T> getItems();
    int getItemCount();
    List<T> getItems(int index, int maxSize);
    List<T> getItemsAfter(String itemId, int maxSize);
    List<T> getItemsBefore(String itemId, int maxSize);
    int indexOf(String itemId);
}
```

E.g., speaking in XMPP terms, when your client receives a `disco#items` request with a RSM extension `<set xmlns='http://jabber.org/protocol/rsm'><max>20</max></set>`,
the `getItems(0, 20)` will be called, which should return the first 20 items.

## Identities

An entity in XMPP can have one or more identities, which consists of a category (server, client, gateway, directory, etc.) and a type within that category (IM server, phone vs. handheld client, MSN gateway vs. AIM gateway, user directory vs. chatroom directory, etc.).

This information helps requesting entities to determine the group or "bucket" of services into which the entity is most appropriately placed (e.g., perhaps the entity is shown in a GUI with an appropriate icon).

You can add such identities with:

```
// Adds an identity of category "client" and type "pc":
serviceDiscoveryManager.addIdentity(Identity.clientPc());
```

*client/pc* is also the default identity, if none was added (every entity requires at least one identity), so in most cases you don't need to add one.

[Service Discovery]: http://xmpp.org/extensions/xep-0030.html "XEP-0030: Service Discovery"
[Entity Capabilities]: http://xmpp.org/extensions/xep-0115.html "XEP-0115: Entity Capabilities"
[Software Version]: http://xmpp.org/extensions/xep-0092.html "XEP-0092: Software Version"
[Result Set Management]: http://xmpp.org/extensions/xep-0059.html "XEP-0059: Result Set Management"


text:
struct correct_convolutional {
    const unsigned int *table;  // size 2**order
    size_t rate;                // e.g. 2, 3...
    size_t order;               // e.g. 7, 9...
    unsigned int numstates;     // 2**order
    bit_writer_t *bit_writer;
    bit_reader_t *bit_reader;

    bool has_init_decode;
    distance_t *distances;
    pair_lookup_t pair_lookup;
    soft_measurement_t soft_measurement;
    history_buffer *history_buffer;
    error_buffer_t *errors;
};

correct_convolutional *_correct_convolutional_init(correct_convolutional *conv,
                                                   size_t rate, size_t order,
                                                   const polynomial_t *poly);
void _correct_convolutional_teardown(correct_convolutional *conv);

// portable versions
void _convolutional_decode_init(correct_convolutional *conv, unsigned int min_traceback, unsigned int traceback_length, unsigned int renormalize_interval);
void convolutional_decode_warmup(correct_convolutional *conv, unsigned int sets,
                                 const uint8_t *soft);
void convolutional_decode_inner(correct_convolutional *conv, unsigned int sets,
                                const uint8_t *soft);
void convolutional_decode_tail(correct_convolutional *conv, unsigned int sets,
                               const uint8_t *soft);
#endif

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="origin-trial" content="AsSBpvHAfro0i7R9Hn1JDOTcDk6tHmz9GmFRUQqOAlW2mIAI0SLpjj/OFJVJVlfiZm+J+QGwhC0ZMA1DzcqihAAAAABTeyJvcmlnaW4iOiJodHRwczovL2doYWRlZXJhcy5naXRodWIuaW86NDQzIiwiZmVhdHVyZSI6IldlYkdQVSIsImV4cGlyeSI6MTY3NTIwOTU5OX0=">
        <title>Path Tracing</title>
        <link type="text/css" rel="stylesheet" href="/index.css" />
      </style>

                <canvas id="canvas" width="900px" height="450px" style="cursor: all-scroll; width: 100%; aspect-ratio: 2 / 1;">
                    Your browser seems not to support HTML 5 Canvas!
                </canvas>

Samples Per Pixel	2

Averaging Layers Count	2

Maximum Layers Count	256

Denoising	on

FPS	0

WebGPU Status	😰 ...

Path Tracing

                    This is my first attempt at doing real-time path tracing. There is still plenty of room for improvements.
                    I was inspired by the work of Reinder Nijhoff,
                    specially his demo Wolfenstein: Ray Tracing On using WebGL1,
                    which I find stunning it was implemented with WebGL 1! I am trying to do something similar as an exercise
                    to learn WebGPU and miscellaneous rendering techniques.

Noise

                    In order to experiment with different ways for pseudo-random number generation, I used this
                    toy.
                    I eventually settled on using the XorShift128 algorithm seeded by the coordinates of each fragment
                    and a counter that is incremented with each frame.

The Controls / Key Mappings

	🖱 (drag)	to look around

	🖱 (wheel)	to change focal length

	1 ... 8	to change the number of samples per pixel

ALT + 	1 ... 8	to change the minimum number of layers

	W  /  S	to move forward/backward

	D  /  A	to move right/left

	E  /  C	to move up/down

	L	to toggle maximum layering

	N	to toggle denoising

	R	to start/stop recording


text:
<?php

namespace Google\Service\CloudMachineLearningEngine;

class GoogleApiHttpBody extends \Google\Collection
{
  protected $collection_key = 'extensions';
  /**
   * @var string
   */
  public $contentType;
  /**
   * @var string
   */
  public $data;
  /**
   * @var array[]
   */
  public $extensions;

  /**
   * @param string
   */
  public function setContentType($contentType)
  {
    $this->contentType = $contentType;
  }
  /**
   * @return string
   */
  public function getContentType()
  {
    return $this->contentType;
  }
  /**
   * @param string
   */
  public function setData($data)
  {
    $this->data = $data;
  }
  /**
   * @return string
   */
  public function getData()
  {
    return $this->data;
  }
  /**
   * @param array[]
   */
  public function setExtensions($extensions)
  {
    $this->extensions = $extensions;
  }
  /**
   * @return array[]
   */
  public function getExtensions()
  {
    return $this->extensions;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleApiHttpBody::class, 'Google_Service_CloudMachineLearningEngine_GoogleApiHttpBody');


text:
// Test that an iframe with the |mozbrowser| attribute does bubble some
// whitelisted key events.
"use strict";

let Ci = SpecialPowers.Ci;

let whitelistedEvents = [
  Ci.nsIDOMKeyEvent.DOM_VK_ESCAPE,   // Back button.
  Ci.nsIDOMKeyEvent.DOM_VK_SLEEP,    // Power button
  Ci.nsIDOMKeyEvent.DOM_VK_CONTEXT_MENU,
  Ci.nsIDOMKeyEvent.DOM_VK_F5,       // Search button.
  Ci.nsIDOMKeyEvent.DOM_VK_PAGE_UP,  // Volume up.
  Ci.nsIDOMKeyEvent.DOM_VK_PAGE_DOWN // Volume down.
];

SimpleTest.waitForExplicitFinish();

browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();

// Number of expected events at which point we will consider the test as done.
var nbEvents = whitelistedEvents.length * 3;

var iframe;
var finished = false;
function runTest() {
  iframe = document.createElement('iframe');
  SpecialPowers.wrap(iframe).mozbrowser = true;
  iframe.src = browserElementTestHelpers.focusPage;
  document.body.appendChild(iframe);

  SimpleTest.waitForFocus(function() {
    iframe.focus();
    SimpleTest.executeSoon(test2);
  });
}

function eventHandler(e) {
  ok(((e.type == 'keydown' || e.type == 'keypress' || e.type == 'keyup') &&
      !e.defaultPrevented &&
      (whitelistedEvents.indexOf(e.keyCode) != -1)),
      "[ " + e.type + "] Handled event should be a non prevented key event in the white list.");

  nbEvents--;

  if (nbEvents == 0) {
    SimpleTest.finish();
    return;
  }

  if (nbEvents < 0 && !finished) {
    ok(false, "got an unexpected event! " + e.type + " " + e.keyCode);
    SimpleTest.finish();
    return;
  }
}

function test2() {
  is(document.activeElement, iframe, "iframe should be focused");

  addEventListener('keydown', eventHandler);
  addEventListener('keypress', eventHandler);
  addEventListener('keyup', eventHandler);

  // Those event should not be received because not whitelisted.
  synthesizeKey("VK_A", {});
  synthesizeKey("VK_B", {});

  // Those events should not be received because prevent default is called.
  synthesizeKey("VK_ESCAPE", {});

  // Those events should be received.
  synthesizeKey("VK_F5", {}); // F5 key is going to be canceled by ESC key.
  synthesizeKey("VK_ESCAPE", {});
  synthesizeKey("VK_PAGE_UP", {});   // keypress is ignored because .preventDefault() will be called.
  synthesizeKey("VK_PAGE_DOWN", {}); // keypress is ignored because .preventDefault() will be called.
  synthesizeKey("VK_CONTEXT_MENU", {});
  synthesizeKey("VK_SLEEP", {});
  finished = true;
}

addEventListener('testready', runTest);


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

namespace UnitySampleSimpleServer
{
    class Program
    {
        static void Main(string[] args)
        {
            GameServer server = new GameServer();
            server.Start();
        }
    }
}


text:
require 'spec_helper'

feature 'china city', js: true do
  scenario 'select' do
    visit '/china_city'
    within '.rails-helper' do
      select '广东省'
      select '深圳市'
      select '南山区'
    end
    within '.html-tag' do
      select '广东省'
      select '深圳市'
      select '南山区'
    end
  end

  describe 'clean' do
    before do
      visit '/china_city'
      within '.rails-helper' do
        select '广东省'
        select '深圳市'
        select '南山区'
      end
    end
    context 'select empty parent' do
      scenario 'city and district' do
        within '.rails-helper' do
          select '--省份--'
          expect(find('.city-city').value).to be_blank
          expect(find('.city-district').value).to be_blank
          sleep 2
          expect(all('.city-city option').size).to eql 1
          expect(all('.city-district option').size).to eql 1
        end
      end
      scenario 'district' do
        within '.rails-helper' do
          select '--城市--'
          expect(find('.city-district').value).to be_blank
          sleep 2
          expect(all('.city-district option').size).to eql 1
        end
      end
    end
    context 'select other parent' do
      scenario 'city and district' do
        within '.rails-helper' do
          select '江苏省'
          expect(find('.city-city').value).to be_blank
          expect(find('.city-district').value).to be_blank
          sleep 2
          expect(all('.city-city option').size).to eql 14
          expect(all('.city-district option').size).to eql 1
        end
      end
      scenario 'district' do
        within '.rails-helper' do
          select '广州市'
          expect(find('.city-district').value).to be_blank
          sleep 2
          expect(all('.city-district option').size).to eql 14
        end
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Qi4CS.Core.API.Model;
using System.Threading;
using Qi4CS.Core.API.Instance;

namespace Qi4CS.Samples.Qi4CSDocumentation
{
#pragma warning disable 649,169

   #region PassivationTokenCode1
   public interface MyServiceWithBackgroundThread
   {
   }

   public class MyServiceWithBackgroundThreadMixin : MyServiceWithBackgroundThread
   {
      [Structure]
      private Application _application;

      [Activate]
      protected void Activate()
      {
         new Thread( this.ThreadMainMethod ).Start();
      }

      private void ThreadMainMethod()
      {
         // do some constant task in while loop
      }
   }
   #endregion

   public class Dummy1
   {
      private Application _application;

      #region PassivationTokenCode2
      private void ThreadMainMethod()
      {
         while ( this._application.Active )
         {
            // Do something
         }
      }
      #endregion
   }

   public class Dummy2
   {
      private Application _application;

      #region PassivationTokenCode3
      private void ThreadMainMethod()
      {
         while ( !this._application.PassivationToken.IsCancellationRequested )
         {
            // Do something
         }
      }
      #endregion
   }
   namespace Dummeh
   {
      #region PassivationTokenCode4
      public class MyServiceWithBackgroundThreadMixin : MyServiceWithBackgroundThread
      {
         [Structure]
         private Application _application;

         [Activate]
         protected void Activate()
         {
            var token = this._application.PassivationToken;
            new Thread( () => this.ThreadMainMethod( token ) ).Start();
         }

         private void ThreadMainMethod( CancellationToken token )
         {
            while ( !token.IsCancellationRequested )
            {
               // Do something
            }
         }
      }
      #endregion
   }

#pragma warning restore 649,169
}


text:
package org.apache.hadoop.hive.metastore.events;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hive.metastore.IHMSHandler;
import org.apache.hadoop.hive.metastore.api.Table;

@InterfaceAudience.Public
@InterfaceStability.Stable
public class PreDropTableEvent extends PreEventContext {

  private final Table table;
  private final boolean deleteData;

  public PreDropTableEvent(Table table, boolean deleteData, IHMSHandler handler) {
    super(PreEventType.DROP_TABLE, handler);
    this.table = table;
    // In HiveMetaStore, the deleteData flag indicates whether DFS data should be
    // removed on a drop.
    this.deleteData = deleteData;
  }

  /**
   * @return the table
   */
  public Table getTable() {
    return table;
  }

  /**
   * @return the deleteData flag
   */
  public boolean getDeleteData() {
    return deleteData;
  }

}


text:
This library requires Spark 1.3+

## Linking
You can link against this library in your program at the following coordinates:

### Scala 2.10
```
groupId: com.databricks
artifactId: tpcds-spark_2.10
version: 1.2.0
```
### Scala 2.11
```
groupId: com.databricks
artifactId: tpcds-spark_2.11
version: 1.2.0
```

## Using with Spark shell
Make sure to build spark with the hive profile.

```
bin/spark-shell --jars <PATH to JAR>

scala> import com.databricks.spark.tpcds._
scala> val tpcds = new TpcdsBenchmark(sqlContext)
scala> tpcds.registerTables()
scala> val df = sql(tpcds.getQuery(3))
scala> df.explain
```

## Running with data.
To generate the data, download and run the tpcds-kit. This tool expects the data to be generated
as output by the tool. That is <root_dir>/<t1>, root_dir>/<t2>, etc. The steps to run load these
are:

```
bin/spark-shell --jars <PATH to JAR>

scala> import com.databricks.spark.tpcds._
scala> val tpcds = new TpcdsBenchmark(sqlContext)
scala> tpcds.registerTables(<path to root_dir>)
scala> val df = sql(tpcds.getQuery(3))
scala> df.explain
scala> df.show
```

## Building From Source
This library is built with [SBT](http://www.scala-sbt.org/0.13/docs/Command-Line-Reference.html), which is automatically downloaded by the included shell script. To build a JAR file simply run `sbt/sbt package` from the project root. The build configuration includes support for both Scala 2.10 and 2.11.


text:
<?php

namespace Downloader\Validate;

use Downloader;

/**
 * Class Host
 * validate input param host
 * @package WayBack Downloader
 * @author Pavel Novitsky <mail@pavel-novitsky.com>
 */
class Host extends Downloader\Validate
{
    /**
     * @return bool
     * @throws \UnexpectedValueException
     */
    public function process()
    {
        if ($this->isEmpty($this->value)) {
            throw new \UnexpectedValueException('Hostname can not be empty');
        }

        if (!$this->isUrl()) {
            throw new \UnexpectedValueException(sprintf('Hostname required (%s)', $this->value));
        }

        return true;
    }

    /**
     * @return bool
     */
    public function isUrl()
    {
        return (bool) filter_var($this->value, FILTER_VALIDATE_URL);
    }
}


text:
goog.provide('forest.ForestDetailPanel');

/**
 * <forest-detail-panel> is the destination detail panel element.
 */
forest.ForestDetailPanel = Polymer({
  is: 'forest-detail-panel',

  properties: {
    /** @type {forest.ForestPickerPanel.DestintationDetails} */
    curDestinationDetails: {
      type: Object,
      observer: 'showDetails_',
    },

    /** @private {boolean} */
    hasQuestion_: Boolean,
  },

  ready: function() { this.setLoadingMode_(false); },

  /**
   * Toggles whether the panel is in loading mode.
   * @param {boolean} enabled
   * @private
   */
  setLoadingMode_: function(enabled) {
    this.enableButtons_(!enabled);
    this.toggleClass('loading', enabled);
    this.$.contentSpinner.active = enabled;
  },

  /**
   * Shows content in the details panel when the destination changes.
   * @param {!Object} curDestinationDetails
   * @private
   */
  showDetails_: function(curDestinationDetails) {
    this.hasQuestion_ = 'correctChoice' in curDestinationDetails;
    this.setLoadingMode_(false);
  },

  /**
   * Enables the navigation buttons.
   * @param {boolean} enabled Whether to enable or disable the buttons.
   * @private
   */
  enableButtons_: function(enabled) {
    var buttons = Polymer.dom(this).querySelectorAll('paper-icon-button');
    buttons.forEach(function(button) {
      button.disabled = !enabled;
    });
  },

  /**
   * Notifies listeners when the left arrow is tapped.
   * @private
   */
  handleLeftTap_: function() { this.fire('left-tap'); },

  /**
   * Notifies listeners when the right arrow is tapped.
   * @private
   */
  handleRightTap_: function() { this.fire('right-tap'); },
});


text: module.exports = require('./dist/cjs/mdx/mdx-compiler-plugin');


text:
package com.digirati.elucidate.web.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.digirati.elucidate.common.infrastructure.constants.URLConstants;
import com.digirati.elucidate.model.ServiceResponse;
import com.digirati.elucidate.model.ServiceResponse.Status;
import com.digirati.elucidate.model.statistics.AbstractStatisticsPage;
import com.digirati.elucidate.service.statistics.AbstractAnnotationStatisticsPageService;

public abstract class AbstractAnnotationStatisticsController<S extends AbstractStatisticsPage> {

    private static final String REQUEST_PATH_BODY = "/services/stats/body";
    private static final String REQUEST_PATH_TARGET = "/services/stats/target";

    private AbstractAnnotationStatisticsPageService<S> statisticsPageService;

    protected AbstractAnnotationStatisticsController(AbstractAnnotationStatisticsPageService<S> statisticsPageService) {
        this.statisticsPageService = statisticsPageService;
    }

    @RequestMapping(value = REQUEST_PATH_BODY, method = RequestMethod.GET)
    public ResponseEntity<S> getBodyStatistics(@RequestParam(value = URLConstants.PARAM_FIELD, required = true) String field, @RequestParam(value = URLConstants.PARAM_PAGE, required = false, defaultValue = "0") Integer page) {

        ServiceResponse<S> serviceResponse = statisticsPageService.buildBodyStatisticsPage(field, page);
        return getStatistics(serviceResponse);
    }

    @RequestMapping(value = REQUEST_PATH_TARGET, method = RequestMethod.GET)
    public ResponseEntity<S> getTargetStatistics(@RequestParam(value = URLConstants.PARAM_FIELD, required = true) String field, @RequestParam(value = URLConstants.PARAM_PAGE, required = false, defaultValue = "0") Integer page) {

        ServiceResponse<S> serviceResponse = statisticsPageService.buildTargetStatisticsPage(field, page);
        return getStatistics(serviceResponse);
    }

    private ResponseEntity<S> getStatistics(ServiceResponse<S> serviceResponse) {

        Status status = serviceResponse.getStatus();

        if (status.equals(Status.NON_CONFORMANT)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }

        if (!status.equals(Status.OK)) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }

        return ResponseEntity.ok(serviceResponse.getObj());
    }
}


text:
<?php
//mantis bug tracker database conection info - this tool only reads.
$host    = '127.0.0.1'; //change if not localhost
$db      = 'mantisbt'; //changeme
$charset = 'utf8';

$M2P_CONFIG = array(
    'mbt_db_dsn' => "mysql:host=$host;dbname=$db;charset=$charset",
    'mbt_db_username' => 'mantisbt', //changeme
    'mbt_db_password' => 'mantisbt', //changeme
    'mbt_db_opt' => array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ),
    //set the next line the base url of your mantis install if you want
    //  links to the mantis system to be made in the imported tickets
    //end it with trailing slash. - Set to '' to disable links.
    'mbt_linkback_url' => 'https://mymantisurl.com/any/subfolders/', //changeme
);


text:
package dev.gigaherz.enderrift.automation.browser;

import com.google.common.collect.Lists;
import dev.gigaherz.enderrift.EnderRiftMod;
import dev.gigaherz.enderrift.common.slots.SlotFake;
import dev.gigaherz.enderrift.automation.AutomationHelper;
import dev.gigaherz.enderrift.network.SendSlotChanges;
import dev.gigaherz.enderrift.network.SetVisibleSlots;
import joptsimple.internal.Strings;
import net.minecraft.world.inventory.*;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
import net.minecraft.core.NonNullList;
import net.minecraft.network.chat.Component;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.IItemHandlerModifiable;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class AbstractBrowserContainer extends AbstractContainerMenu
{
    protected final static int LEFT = 8;
    protected final static int TOP = 18;
    protected final static int SLOT_WIDTH = 18;
    protected final static int SLOT_HEIGHT = 18;

    protected final static int SCROLL_ROWS = 3;
    protected final static int SCROLL_COLUMNS = 9;
    protected final static int SCROLL_SLOTS = SCROLL_ROWS * SCROLL_COLUMNS;

    protected final static int PLAYER_ROWS = 4;
    protected final static int PLAYER_COLUMNS = 9;
    protected final static int PLAYER_SLOTS = PLAYER_ROWS * PLAYER_COLUMNS;

    private NonNullList<ItemStack> currentStacks = NonNullList.create();
    private final Player player;
    private int prevChangeCount;
    private ItemStack stackInCursor = ItemStack.EMPTY;

    @Nullable
    protected BrowserBlockEntity tile;

    public final IItemHandlerModifiable scrollInventory;
    public int scroll;
    public SortMode sortMode = SortMode.STACK_SIZE;
    public String filterText = "";

    private DataSlot isLowOnPower = new DataSlot()
    {
        boolean value = false;

        @Override
        public int get()
        {
            return (isClient() ? value : tile.isLowOnPower()) ? 1 : 0;
        }

        @Override
        public void set(int value)
        {
            this.value = value != 0;
        }
    };

    public final boolean isClient()
    {
        return tile == null;
    }

    public ClientScrollInventory getClient()
    {
        if (!isClient())
            throw new IllegalStateException("Attempted to get client inventory on the server");
        return (ClientScrollInventory) scrollInventory;
    }

    public ServerScrollInventory getServer()
    {
        if (isClient())
            throw new IllegalStateException("Attempted to get server inventory on the client");
        return (ServerScrollInventory) scrollInventory;
    }

    protected AbstractBrowserContainer(MenuType<? extends AbstractBrowserContainer> type, int id, @Nullable BrowserBlockEntity tileEntity, Inventory playerInventory)
    {
        super(type, id);

        this.player = playerInventory.player;
        boolean isClient = player.level.isClientSide;

        if (isClient)
        {
            this.tile = null;
            scrollInventory = new ClientScrollInventory();
        }
        else
        {
            this.tile = Objects.requireNonNull(tileEntity);
            scrollInventory = new ServerScrollInventory(tile);
        }

        for (int y = 0; y < SCROLL_ROWS; y++)
        {
            for (int x = 0; x < SCROLL_COLUMNS; x++)
            {
                addSlot(new SlotFake(scrollInventory, x + y * SCROLL_COLUMNS,
                        LEFT + x * SLOT_WIDTH, TOP + y * SLOT_HEIGHT));
            }
        }

        bindPlayerInventory(playerInventory);

        addDataSlot(isLowOnPower);
    }

    protected void bindPlayerInventory(Inventory playerInventory)
    {
        bindPlayerInventory(playerInventory, TOP + SCROLL_ROWS * SLOT_HEIGHT + 14);
    }

    protected void bindPlayerInventory(Inventory playerInventory, int top)
    {
        for (int y = 0; y < 3; y++)
        {
            for (int x = 0; x < 9; x++)
            {
                addSlot(new Slot(playerInventory,
                        x + y * 9 + 9,
                        LEFT + x * SLOT_WIDTH, top + y * SLOT_HEIGHT));
            }
        }

        top += 3 * SLOT_HEIGHT + 4;
        for (int x = 0; x < 9; x++)
        {
            addSlot(new Slot(playerInventory, x, LEFT + x * SLOT_WIDTH, top));
        }
    }

    @Override
    public boolean stillValid(Player player)
    {
        return true;
    }

    @Override
    public void broadcastChanges()
    {
        if (isClient())
            return;

        ServerScrollInventory serverInv = getServer();
        if (prevChangeCount != tile.getChangeCount())
        {
            serverInv.refresh();
            prevChangeCount = tile.getChangeCount();
        }

        int oldLength = currentStacks.size();
        int newLength;
        List<Integer> indicesChanged = Lists.newArrayList();
        List<ItemStack> stacksChanged = Lists.newArrayList();

        newLength = serverInv.getRealSizeInventory();
        if (newLength != oldLength)
        {
            changeSize(oldLength, newLength);
        }

        for (int i = 0; i < newLength; ++i)
        {
            ItemStack newStack = serverInv.getStack(i);
            ItemStack current = currentStacks.get(i);

            if (!ItemStack.matches(current, newStack))
            {
                current = newStack.copy();
                currentStacks.set(i, current);

                indicesChanged.add(i);
                stacksChanged.add(current);
            }
        }

        for (int i = SCROLL_SLOTS; i < this.slots.size(); ++i)
        {
            ItemStack inSlot = slots.get(i).getItem();
            ItemStack inCache = lastSlots.get(i);

            if (!ItemStack.matches(inCache, inSlot))
            {
                inCache = inSlot.copy();
                this.lastSlots.set(i, inCache);

                for (ContainerListener crafter : this.containerListeners)
                {
                    crafter.slotChanged(this, i, inCache);
                }
            }
        }

        if (player instanceof ServerPlayer crafter)
        {
            if (newLength != oldLength || indicesChanged.size() > 0)
            {
                EnderRiftMod.CHANNEL.sendTo(new SendSlotChanges(containerId, newLength, indicesChanged, stacksChanged), crafter.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT);
            }

            ItemStack newStack = getCarried();

            if (!ItemStack.matches(stackInCursor, newStack))
            {
                sendStackInCursor(crafter, newStack);
            }
        }

        if (newLength != oldLength || indicesChanged.size() > 0)
        {
            serverInv.resetVisible();
        }
    }

    private void changeSize(int oldLength, int newLength)
    {
        NonNullList<ItemStack> oldStacks = currentStacks;
        currentStacks = NonNullList.withSize(newLength, ItemStack.EMPTY);
        for (int i = 0; i < Math.min(newLength, oldLength); i++)
        { currentStacks.set(i, oldStacks.get(i)); }
    }

    private void sendStackInCursor(ServerPlayer player, ItemStack newStack)
    {
        stackInCursor = newStack.copy();

        player.connection.send(new ClientboundContainerSetSlotPacket(-1, incrementStateId(), -1, newStack));
    }

    public void slotsChanged(int slotCount, List<Integer> indices, List<ItemStack> stacks)
    {
        if (slotCount != currentStacks.size())
        {
            changeSize(currentStacks.size(), slotCount);
        }

        for (int i = 0; i < indices.size(); i++)
        {
            int slot = indices.get(i);
            ItemStack stack = stacks.get(i);

            currentStacks.set(slot, stack);
        }

        ClientScrollInventory clientInv = getClient();
        clientInv.setArray(currentStacks);

        setVisibleSlots(clientInv.getIndices());
    }

    @Override
    public void initializeContents(int p_182411_, List<ItemStack> p_182412_, ItemStack p_182413_)
    {
        super.initializeContents(p_182411_, List.of(), p_182413_);
    }

    public void setVisibleSlots(int[] visible)
    {
        if (isClient())
        {
            EnderRiftMod.CHANNEL.sendToServer(new SetVisibleSlots(containerId, visible));
        }
        else
        {
            getServer().setVisible(visible);
        }
    }

    public void setScrollPos(int scroll)
    {
        this.scroll = scroll;

        setVisibleSlots(getClient().getIndices());
    }

    public void setSortMode(SortMode sortMode)
    {
        this.sortMode = sortMode;
        this.scroll = 0;

        ClientScrollInventory clientInv = getClient();
        clientInv.setArray(currentStacks);

        setVisibleSlots(clientInv.getIndices());
    }

    public void setFilterText(String text)
    {
        this.filterText = text.toLowerCase();
        this.scroll = 0;

        ClientScrollInventory clientInv = getClient();
        clientInv.setArray(currentStacks);

        setVisibleSlots(clientInv.getIndices());
    }

    @Override
    public void setItem(int slotID, int stateId, ItemStack stack)
    {
        super.setItem(slotID, stateId, stack);
    }

    @Override
    public void clicked(int slotId, int clickedButton, ClickType mode, Player playerIn)
    {
        if (slotId >= 0 && slotId < SCROLL_SLOTS)
        {
            IItemHandler parent = getTileInventory();

            Slot slot = this.slots.get(slotId);
            ItemStack existing = slot.getItem();
            int existingSize = isClient() ? getClient().getStackSizeForSlot(slotId) : existing.getCount();

            if (mode == ClickType.PICKUP)
            {
                ItemStack dropping = getCarried();

                if (dropping.getCount() > 0)
                {
                    if (clickedButton == 0)
                    {
                        ItemStack remaining = insertItemsSided(parent, dropping);
                        if (remaining.getCount() > 0)
                        {
                            if (dropping.getCount() != remaining.getCount())
                                markTileDirty();

                            if (player instanceof ServerPlayer crafter)
                            {
                                sendStackInCursor(crafter, remaining);
                            }
                        }
                        else
                        {
                            markTileDirty();
                        }
                        setCarried(remaining);
                    }
                    else
                    {
                        int amount = 1;

                        ItemStack push = dropping.copy();
                        push.setCount(amount);
                        ItemStack remaining = insertItemsSided(parent, push);

                        dropping.shrink(push.getCount());

                        if (remaining.getCount() > 0)
                        {
                            if (push.getCount() != remaining.getCount())
                                markTileDirty();
                            dropping.grow(remaining.getCount());

                            if (player instanceof ServerPlayer crafter)
                            {
                                sendStackInCursor(crafter, remaining);
                            }
                        }
                        else
                        {
                            markTileDirty();
                        }

                        if (dropping.getCount() <= 0)
                            dropping = ItemStack.EMPTY;

                        setCarried(dropping);
                    }
                }
                else if (existingSize > 0)
                {
                    int amount = clickedButton == 0
                            ? existing.getMaxStackSize()
                            : existing.getMaxStackSize() / 2;

                    ItemStack extracted = extractItemsSided(parent, existing, existingSize, amount, false);
                    if (extracted.getCount() > 0)
                    {
                        markTileDirty();
                    }
                    else
                    {

                        if (player instanceof ServerPlayer crafter)
                        {
                            sendStackInCursor(crafter, extracted);
                        }
                    }
                    setCarried(extracted);
                }

                broadcastChanges();
                return;
            }
            else if (mode == ClickType.QUICK_MOVE && existingSize > 0)
            {
                int amount = existing.getMaxStackSize();
                if (clickedButton != 0 && amount > 1)
                    amount /= 2;

                if (amount == 0)
                    return;

                ItemStack remaining = simulateAddToPlayer(existing, amount);

                if (remaining.getCount() > 0)
                    amount -= remaining.getCount();

                if (amount > 0)
                {
                    ItemStack finalExtract = extractItemsSided(parent, existing, existingSize, amount, false);

                    if (finalExtract.getCount() > 0)
                    {
                        addToPlayer(finalExtract);

                        markTileDirty();
                        broadcastChanges();
                    }
                }
            }

            if (mode != ClickType.CLONE)
                return;
        }

        super.clicked(slotId, clickedButton, mode, playerIn);
    }

    @Nullable
    private IItemHandler getTileInventory()
    {
        return isClient() ? null : tile.getCombinedInventory();
    }

    private void markTileDirty()
    {
        if (!isClient())
            tile.setChanged();
    }

    private ItemStack extractItemsSided(@Nullable IItemHandler parent, ItemStack existing, int existingSize, int amount, boolean simulate)
    {
        if (isClient() || parent == null)
        {
            var copy = existing.copy();
            copy.setCount(Math.min(existingSize, amount));
            return copy;
        }
        return AutomationHelper.extractItems(parent, existing, amount, simulate);
    }

    private ItemStack insertItemsSided(@Nullable IItemHandler parent, ItemStack dropping)
    {
        if (isClient() || parent == null)
            return ItemStack.EMPTY;
        return AutomationHelper.insertItems(parent, dropping);
    }

    private ItemStack simulateAddToPlayer(ItemStack stack, int amount)
    {
        int startIndex = SCROLL_SLOTS;
        int endIndex = startIndex + PLAYER_SLOTS;

        ItemStack stackCopy = stack.copy();
        stackCopy.setCount(amount);

        if (!this.simulateInsertStack(stackCopy, startIndex, endIndex))
        {
            return stackCopy;
        }

        if (stackCopy.getCount() <= 0)
        {
            return ItemStack.EMPTY;
        }

        return stackCopy;
    }

    protected boolean simulateInsertStack(ItemStack stack, int startIndex, int endIndex)
    {
        boolean canInsert = false;

        if (stack.isStackable())
        {
            for (int i = startIndex; stack.getCount() > 0 && i < endIndex; i++)
            {
                Slot slot = this.slots.get(i);
                ItemStack stackInSlot = slot.getItem();

                if (stackInSlot.getCount() < stackInSlot.getMaxStackSize()
                        && ItemStack.isSame(stackInSlot, stack)
                        && ItemStack.tagMatches(stack, stackInSlot))
                {
                    int j = stackInSlot.getCount() + stack.getCount();

                    if (j <= stack.getMaxStackSize())
                    {
                        stack.setCount(0);
                        canInsert = true;
                    }
                    else
                    {
                        stack.shrink(stack.getMaxStackSize() - stackInSlot.getCount());
                        canInsert = true;
                    }
                }
            }
        }

        if (stack.getCount() > 0)
        {
            for (int i = startIndex; i < endIndex; i++)
            {
                Slot slot = this.slots.get(i);
                ItemStack stackInSlot = slot.getItem();

                if (stackInSlot.getCount() <= 0 && slot.mayPlace(stack))
                {
                    stack.setCount(0);
                    canInsert = true;
                    break;
                }
            }
        }

        return canInsert;
    }

    public ItemStack addToPlayer(ItemStack stack)
    {
        int startIndex = SCROLL_SLOTS;
        int endIndex = startIndex + PLAYER_SLOTS;

        ItemStack stackCopy = stack.copy();

        if (!this.moveItemStackTo(stackCopy, startIndex, endIndex, false))
        {
            return stackCopy;
        }

        if (stackCopy.getCount() <= 0)
        {
            return ItemStack.EMPTY;
        }

        return stackCopy;
    }

    @Override
    public ItemStack quickMoveStack(Player player, int slotIndex)
    {
        Slot slot = this.slots.get(slotIndex);

        if (slot == null || !slot.hasItem())
        {
            return ItemStack.EMPTY;
        }

        if (slotIndex < SCROLL_SLOTS)
        {
            // Shouldn't even happen, handled above.
            return ItemStack.EMPTY;
        }
        else
        {
            ItemStack stack = slot.getItem();
            ItemStack stackCopy = stack.copy();

            ItemStack remaining = insertItemsSided(getTileInventory(), stack);
            if (remaining.getCount() > 0)
            {
                if (player instanceof ContainerListener)
                {
                    ((ContainerListener) player).slotChanged(this, slotIndex, remaining);
                }

                if (remaining.getCount() == stackCopy.getCount())
                {
                    return ItemStack.EMPTY;
                }

                markTileDirty();
                stack.setCount(remaining.getCount());
                slot.setChanged();
            }
            else
            {
                markTileDirty();
                stack.setCount(0);
                slot.set(ItemStack.EMPTY);
            }

            slot.onTake(player, stack);
            return stackCopy;
        }
    }

    public int getActualSlotCount()
    {
        return scrollInventory.getSlots();
    }

    public boolean isLowOnPower()
    {
        return isLowOnPower.get() != 0;
    }

    public static class ServerScrollInventory implements IItemHandlerModifiable
    {
        final BrowserBlockEntity tile;
        final List<ItemStack> slots = Lists.newArrayList();
        private int[] visible = new int[0];

        public ServerScrollInventory(BrowserBlockEntity tile)
        {
            this.tile = tile;
        }

        public void setVisible(int[] visible)
        {
            this.visible = visible;
        }

        public void resetVisible()
        {
            visible = new int[0];
        }

        public void refresh()
        {
            IItemHandler inv = tile.getCombinedInventory();

            final List<ItemStack> slotsSeen = Lists.newArrayList();

            slots.clear();

            if (inv == null)
                return;

            int invSlots = inv.getSlots();
            for (int j = 0; j < invSlots; j++)
            {
                ItemStack invStack = inv.getStackInSlot(j);
                if (invStack.getCount() <= 0)
                    continue;

                boolean found = false;

                for (ItemStack cachedStack : slotsSeen)
                {
                    if (ItemStack.isSame(cachedStack, invStack) && ItemStack.tagMatches(cachedStack, invStack))
                    {
                        cachedStack.grow(invStack.getCount());
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    ItemStack stack = invStack.copy();
                    slotsSeen.add(stack);

                    slots.add(stack);
                }
            }
        }

        public int getRealSizeInventory()
        {
            return slots.size();
        }

        @Override
        public int getSlots()
        {
            return visible.length;
        }

        @Override
        public ItemStack getStackInSlot(int index)
        {
            if (index >= visible.length)
                return ItemStack.EMPTY;
            int i = visible[index];
            if (i >= slots.size())
                return ItemStack.EMPTY;
            return slots.get(visible[index]);
        }

        public ItemStack getStack(int index)
        {
            return slots.get(index);
        }

        @Override
        public ItemStack insertItem(int slot, ItemStack stack, boolean simulate)
        {
            return ItemStack.EMPTY;
        }

        @Override
        public ItemStack extractItem(int slot, int amount, boolean simulate)
        {
            return ItemStack.EMPTY;
        }

        @Override
        public int getSlotLimit(int slot)
        {
            return 64;
        }

        @Override
        public boolean isItemValid(int slot, @Nonnull ItemStack stack)
        {
            return true;
        }

        @Override
        public void setStackInSlot(int slot, ItemStack stack)
        {
        }
    }

    public class ClientScrollInventory implements IItemHandlerModifiable
    {
        private int[] indices;
        private NonNullList<ItemStack> stacks;

        public ClientScrollInventory()
        {
        }

        public void setArray(final NonNullList<ItemStack> stacks)
        {
            this.stacks = stacks;

            final List<Integer> indices = Lists.newArrayList();

            final List<Component> itemData = Lists.newArrayList();

            int indexx = 0;
            for (ItemStack invStack : stacks)
            {
                ItemStack stack = invStack.copy();

                boolean matchesSearch = true;
                if (!Strings.isNullOrEmpty(filterText))
                {
                    itemData.clear();
                    Item item = invStack.getItem();
                    itemData.add(stack.getHoverName());
                    itemData.add(Component.literal(ForgeRegistries.ITEMS.getKey(item).toString()));
                    item.appendHoverText(stack, player.level, itemData, TooltipFlag.Default.NORMAL);
                    matchesSearch = false;
                    for (Component s : itemData)
                    {
                        if (StringUtils.containsIgnoreCase(s.getString(), filterText))
                        {
                            matchesSearch = true;
                            break;
                        }
                    }
                }

                if (matchesSearch)
                {
                    indices.add(indexx);
                }
                indexx++;
            }

            if (sortMode != null)
            {
                switch (sortMode)
                {
                    case ALPHABETIC:
                        indices.sort((ia, ib) ->
                        {
                            ItemStack a = stacks.get(ia);
                            ItemStack b = stacks.get(ib);
                            return a.getHoverName().getString().compareToIgnoreCase(b.getHoverName().getString());
                        });
                        break;
                    case STACK_SIZE:
                        indices.sort((ia, ib) ->
                        {
                            ItemStack a = stacks.get(ia);
                            ItemStack b = stacks.get(ib);
                            int diff = a.getCount() - b.getCount();
                            if (diff > 0) return -1;
                            if (diff < 0) return 1;
                            return a.getHoverName().getString().compareToIgnoreCase(b.getHoverName().getString());
                        });
                        break;
                }
            }

            this.indices = new int[indices.size()];
            for (int i = 0; i < this.indices.length; i++)
            {
                this.indices[i] = indices.get(i);
            }
        }

        @Override
        public int getSlots()
        {
            return indices.length;
        }

        @Override
        public ItemStack getStackInSlot(int slot)
        {
            if ((slot + scroll) >= indices.length)
                return ItemStack.EMPTY;
            ItemStack stack = stacks.get(indices[slot + scroll]);
            stack = stack.copy();
            stack.setCount(1);
            return stack;
        }

        @Override
        public ItemStack insertItem(int slot, ItemStack stack, boolean simulate)
        {
            return ItemStack.EMPTY;
        }

        @Override
        public ItemStack extractItem(int slot, int amount, boolean simulate)
        {
            return ItemStack.EMPTY;
        }

        @Override
        public int getSlotLimit(int slot)
        {
            return 64;
        }

        @Override
        public boolean isItemValid(int slot, @Nonnull ItemStack stack)
        {
            return true;
        }

        @Override
        public void setStackInSlot(int slot, ItemStack stack)
        {
            if ((slot + scroll) < indices.length)
                stacks.set(indices[slot + scroll], stack);
        }

        public int getStackSizeForSlot(int slot)
        {
            if ((slot + scroll) >= indices.length)
                return 0;
            return stacks.get(indices[slot + scroll]).getCount();
        }

        public int[] getIndices()
        {
            int from = Math.max(0, Math.min(scroll, indices.length - 1));
            int to = Math.min(from + SCROLL_SLOTS, indices.length);
            return Arrays.copyOfRange(indices, from, to);
        }
    }
}


text:
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Driver;

namespace SQLAzureDemo.App_Start.NHibernate
{
    public class NHibernateConfiguration<TDriver>
        where TDriver : IDriver
    {
        private readonly IPersistenceConfigurer _databaseConfig;

        public NHibernateConfiguration(string connectionString)
        {
            _databaseConfig = MsSqlConfiguration.MsSql2008
                .ConnectionString(connectionString)
                .Driver<TDriver>();
        }

        public ISessionFactory GetSessionFactory()
        {
            var config = Fluently.Configure()
                .Database(_databaseConfig)
                .Mappings(x => x.AutoMappings.Add(
                    AutoMap.Assembly(GetType().Assembly)
                    .Where(type => type.Namespace != null && type.Namespace.EndsWith("Database.Models"))
                ));

            return config.BuildSessionFactory();
        }
    }
}


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Describes properties of a Dedicated Host.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class HostProperties implements Serializable, Cloneable {

    /**
     *

     * The number of cores on the Dedicated Host.
     *

     */
    private Integer cores;
    /**
     *

     * The instance type size that the Dedicated Host supports (for example, m3.medium).
     *

     */
    private String instanceType;
    /**
     *

     * The number of sockets on the Dedicated Host.
     *

     */
    private Integer sockets;
    /**
     *

     * The number of vCPUs on the Dedicated Host.
     *

     */
    private Integer totalVCpus;

    /**
     *

     * The number of cores on the Dedicated Host.
     *

     *
     * @param cores
     *        The number of cores on the Dedicated Host.
     */

    public void setCores(Integer cores) {
        this.cores = cores;
    }

    /**
     *

     * The number of cores on the Dedicated Host.
     *

     *
     * @return The number of cores on the Dedicated Host.
     */

    public Integer getCores() {
        return this.cores;
    }

    /**
     *

     * The number of cores on the Dedicated Host.
     *

     *
     * @param cores
     *        The number of cores on the Dedicated Host.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public HostProperties withCores(Integer cores) {
        setCores(cores);
        return this;
    }

    /**
     *

     * The instance type size that the Dedicated Host supports (for example, m3.medium).
     *

     *
     * @param instanceType
     *        The instance type size that the Dedicated Host supports (for example, m3.medium).
     */

    public void setInstanceType(String instanceType) {
        this.instanceType = instanceType;
    }

    /**
     *

     * The instance type size that the Dedicated Host supports (for example, m3.medium).
     *

     *
     * @return The instance type size that the Dedicated Host supports (for example, m3.medium).
     */

    public String getInstanceType() {
        return this.instanceType;
    }

    /**
     *

     * The instance type size that the Dedicated Host supports (for example, m3.medium).
     *

     *
     * @param instanceType
     *        The instance type size that the Dedicated Host supports (for example, m3.medium).
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public HostProperties withInstanceType(String instanceType) {
        setInstanceType(instanceType);
        return this;
    }

    /**
     *

     * The number of sockets on the Dedicated Host.
     *

     *
     * @param sockets
     *        The number of sockets on the Dedicated Host.
     */

    public void setSockets(Integer sockets) {
        this.sockets = sockets;
    }

    /**
     *

     * The number of sockets on the Dedicated Host.
     *

     *
     * @return The number of sockets on the Dedicated Host.
     */

    public Integer getSockets() {
        return this.sockets;
    }

    /**
     *

     * The number of sockets on the Dedicated Host.
     *

     *
     * @param sockets
     *        The number of sockets on the Dedicated Host.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public HostProperties withSockets(Integer sockets) {
        setSockets(sockets);
        return this;
    }

    /**
     *

     * The number of vCPUs on the Dedicated Host.
     *

     *
     * @param totalVCpus
     *        The number of vCPUs on the Dedicated Host.
     */

    public void setTotalVCpus(Integer totalVCpus) {
        this.totalVCpus = totalVCpus;
    }

    /**
     *

     * The number of vCPUs on the Dedicated Host.
     *

     *
     * @return The number of vCPUs on the Dedicated Host.
     */

    public Integer getTotalVCpus() {
        return this.totalVCpus;
    }

    /**
     *

     * The number of vCPUs on the Dedicated Host.
     *

     *
     * @param totalVCpus
     *        The number of vCPUs on the Dedicated Host.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public HostProperties withTotalVCpus(Integer totalVCpus) {
        setTotalVCpus(totalVCpus);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getCores() != null)
            sb.append("Cores: ").append(getCores()).append(",");
        if (getInstanceType() != null)
            sb.append("InstanceType: ").append(getInstanceType()).append(",");
        if (getSockets() != null)
            sb.append("Sockets: ").append(getSockets()).append(",");
        if (getTotalVCpus() != null)
            sb.append("TotalVCpus: ").append(getTotalVCpus());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof HostProperties == false)
            return false;
        HostProperties other = (HostProperties) obj;
        if (other.getCores() == null ^ this.getCores() == null)
            return false;
        if (other.getCores() != null && other.getCores().equals(this.getCores()) == false)
            return false;
        if (other.getInstanceType() == null ^ this.getInstanceType() == null)
            return false;
        if (other.getInstanceType() != null && other.getInstanceType().equals(this.getInstanceType()) == false)
            return false;
        if (other.getSockets() == null ^ this.getSockets() == null)
            return false;
        if (other.getSockets() != null && other.getSockets().equals(this.getSockets()) == false)
            return false;
        if (other.getTotalVCpus() == null ^ this.getTotalVCpus() == null)
            return false;
        if (other.getTotalVCpus() != null && other.getTotalVCpus().equals(this.getTotalVCpus()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getCores() == null) ? 0 : getCores().hashCode());
        hashCode = prime * hashCode + ((getInstanceType() == null) ? 0 : getInstanceType().hashCode());
        hashCode = prime * hashCode + ((getSockets() == null) ? 0 : getSockets().hashCode());
        hashCode = prime * hashCode + ((getTotalVCpus() == null) ? 0 : getTotalVCpus().hashCode());
        return hashCode;
    }

    @Override
    public HostProperties clone() {
        try {
            return (HostProperties) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
"""
 mbed
 Copyright (c) 2017-2020 ARM Limited

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

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

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
"""
# How to run this test?
#
# Note! You  must be in the mbed-os -folder!
#
# python -m pytest tools/test/targets/target_test.py
#
import os
import sys
import shutil
import tempfile
from os.path import join, abspath, dirname
from contextlib import contextmanager
import pytest

from tools.targets import TARGETS, TARGET_MAP, Target, update_target_data, find_secure_image
from tools.arm_pack_manager import Cache
from tools.notifier.mock import MockNotifier
from tools.resources import Resources, FileType

def test_device_name():
    """Assert device name is in a pack"""
    cache = Cache(True, True)
    named_targets = (target for target in TARGETS if
                     hasattr(target, "device_name"))
    for target in named_targets:
        assert target.device_name in cache.index,\
            ("Target %s contains invalid device_name %s" %
             (target.name, target.device_name))

def test_bl_has_sectors():
    """Assert a bootloader supporting pack has sector information"""
    # ToDo: validity checks for the information IN the sectors!
    cache = Cache(True, True)
    named_targets = (
        target for target in TARGETS if
        (hasattr(target, "device_name") and getattr(target, "bootloader_supported", False))
    )
    for target in named_targets:
        assert target.device_name in cache.index,\
            ("Target %s contains invalid device_name %s" %
             (target.name, target.device_name))
        assert "sectors" in cache.index[target.device_name],\
            ("Target %s does not have sectors" %
             (target.name))
        assert cache.index[target.device_name]["sectors"],\
            ("Device name %s is misssing sector information" %
             (target.device_name))

@contextmanager
def temp_target_file(extra_target, json_filename='custom_targets.json'):
    """Create an extra targets temp file in a context manager

    :param extra_target: the contents of the extra targets temp file
    """
    tempdir = tempfile.mkdtemp()
    try:
        targetfile = os.path.join(tempdir, json_filename)
        with open(targetfile, 'w') as f:
            f.write(extra_target)
        yield tempdir
    finally:
        # Reset extra targets
        Target.set_targets_json_location()
        # Delete temp files
        shutil.rmtree(tempdir)

def test_add_extra_targets():
    """Search for extra targets json in a source folder"""
    test_target_json = """
    {
        "Test_Target": {
            "inherits": ["Target"]
        }
    }
    """
    with temp_target_file(test_target_json) as source_dir:
        Target.add_extra_targets(source_dir=source_dir)
        update_target_data()

        assert 'Test_Target' in TARGET_MAP
        assert TARGET_MAP['Test_Target'].core is None, \
            "attributes should be inherited from Target"

def test_modify_existing_target():
    """Set default targets file, then override base Target definition"""
    initial_target_json = """
    {
        "Target": {
            "core": null,
            "default_toolchain": "ARM",
            "supported_toolchains": null,
            "extra_labels": [],
            "is_disk_virtual": false,
            "macros": [],
            "device_has": [],
            "features": [],
            "detect_code": [],
            "public": false,
            "c_lib": "std",
            "supported_c_libs": {
                "arm": ["std"],
                "gcc_arm": ["std", "small"],
                "iar": ["std"]
            },
            "bootloader_supported": false
        },
        "Test_Target": {
            "inherits": ["Target"],
            "core": "Cortex-M4",
            "supported_toolchains": ["ARM"]
        }
    }"""

    test_target_json = """
    {
        "Target": {
            "core": "Cortex-M0",
            "default_toolchain": "GCC_ARM",
            "supported_toolchains": null,
            "extra_labels": [],
            "is_disk_virtual": false,
            "macros": [],
            "device_has": [],
            "features": [],
            "detect_code": [],
            "public": false,
            "c_lib": "std",
            "supported_c_libs": {
                "arm": ["std"],
                "gcc_arm": ["std", "small"],
                "iar": ["std"]
            },
            "bootloader_supported": true
        }
    }
    """

    with temp_target_file(initial_target_json, json_filename="targets.json") as targets_dir:
        Target.set_targets_json_location(os.path.join(targets_dir, "targets.json"))
        update_target_data()
        assert TARGET_MAP["Test_Target"].core == "Cortex-M4"
        assert TARGET_MAP["Test_Target"].default_toolchain == 'ARM'
        assert TARGET_MAP["Test_Target"].bootloader_supported == False

        with temp_target_file(test_target_json) as source_dir:
            Target.add_extra_targets(source_dir=source_dir)
            update_target_data()

            assert TARGET_MAP["Test_Target"].core == "Cortex-M4"
            # The existing target should not be modified by custom targets
            assert TARGET_MAP["Test_Target"].default_toolchain != 'GCC_ARM'
            assert TARGET_MAP["Test_Target"].bootloader_supported != True

def test_find_secure_image():
    mock_notifier = MockNotifier()
    mock_resources = Resources(mock_notifier)
    ns_image_path = os.path.join('BUILD', 'TARGET_NS', 'app.bin')
    ns_test_path = os.path.join('BUILD', 'TARGET_NS', 'test.bin')
    config_s_image_name = 'target_config.bin'
    default_bin = os.path.join('prebuilt', config_s_image_name)
    test_bin = os.path.join('prebuilt', 'test.bin')

    with pytest.raises(Exception, match='ns_image_path and configured_s_image_path are mandatory'):
        find_secure_image(mock_notifier, mock_resources, None, None, FileType.BIN)
        find_secure_image(mock_notifier, mock_resources, ns_image_path, None, FileType.BIN)
        find_secure_image(mock_notifier, mock_resources, None, config_s_image_name, FileType.BIN)

    with pytest.raises(Exception, match='image_type must be of type BIN or HEX'):
        find_secure_image(mock_notifier, mock_resources, ns_image_path, config_s_image_name, None)
        find_secure_image(mock_notifier, mock_resources, ns_image_path, config_s_image_name, FileType.C_SRC)

    with pytest.raises(Exception, match='No image files found for this target'):
        find_secure_image(mock_notifier, mock_resources, ns_image_path, config_s_image_name, FileType.BIN)

    dummy_bin = os.path.join('path', 'to', 'dummy.bin')
    mock_resources.add_file_ref(FileType.BIN, dummy_bin, dummy_bin)

    with pytest.raises(Exception, match='Required secure image not found'):
        find_secure_image(mock_notifier, mock_resources, ns_image_path, config_s_image_name, FileType.BIN)

    mock_resources.add_file_ref(FileType.BIN, default_bin, default_bin)
    mock_resources.add_file_ref(FileType.BIN, test_bin, test_bin)
    secure_image = find_secure_image(mock_notifier, mock_resources, ns_image_path, config_s_image_name, FileType.BIN)
    assert secure_image == default_bin

    secure_image = find_secure_image(mock_notifier, mock_resources, ns_test_path, config_s_image_name, FileType.BIN)
    assert secure_image == test_bin


text:
package main

import (
	"flag"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"time"

	"github.com/jtmelton/appsensor-reverse-proxy/blocks"
	"github.com/jtmelton/appsensor-reverse-proxy/connections"
	"github.com/jtmelton/appsensor-reverse-proxy/ids"
	"github.com/jtmelton/appsensor-reverse-proxy/middleware"

	"github.com/jtmelton/appsensor-reverse-proxy/Godeps/_workspace/src/github.com/golang/glog"
	"github.com/jtmelton/appsensor-reverse-proxy/Godeps/_workspace/src/github.com/gorilla/context"
	"github.com/jtmelton/appsensor-reverse-proxy/Godeps/_workspace/src/github.com/justinas/alice"
)

type Prox struct {
	target *url.URL
	proxy  *httputil.ReverseProxy
}

func New(target string) *Prox {
	url, _ := url.Parse(target)

	return &Prox{target: url, proxy: httputil.NewSingleHostReverseProxy(url)}
}

func (p *Prox) handle(w http.ResponseWriter, r *http.Request) {
	glog.Info("saw a request for ", r.URL)

	p.proxy.ServeHTTP(w, r)
}

func doEvery(d time.Duration, f func()) {
	for {
		time.Sleep(d)
		f()
	}
}

func parseFlags() (*bool, *string, *string, *string, http.Handler) {

	const (
		defaultPort                     = ":8080"
		defaultPortUsage                = "default server port, ':80', ':8080'..."
		defaultTarget                   = "http://127.0.0.1:8090"
		defaultTargetUsage              = "default redirect url, 'http://127.0.0.1:8080'"
		defaultBooleanUsage             = "true or false"
		defaultRefreshUsage             = "number of seconds between block refreshes"
		defaultExpireUsage              = "number of seconds between expiration sweeps"
		defaultBlocksRefreshUrl         = "block refresh url, 'http://localhost:8090/api/v1.0/blocks'"
		defaultCertFile                 = "cert file (e.g. cert.pem)"
		defaultKeyFile                  = "key file (e.g. key.pem)"
		defaultResourceVerbsMappingFile = "resource verbs mapping file (e.g. resource-verbs-mapping.yml)"
		defaultResourcesFile            = "resources file (e.g. resources.yml)"
	)

	// flags
	port := flag.String("port", defaultPort, defaultPortUsage)
	url := flag.String("url", defaultTarget, defaultTargetUsage)

	// for running in TLS mode
	enableTls := flag.Bool("enable-tls", false, defaultBooleanUsage)
	certFile := flag.String("cert-file", "cert.pem", defaultCertFile)
	keyFile := flag.String("key-file", "key.pem", defaultKeyFile)

	// related to trend detection
	enableTrends := flag.Bool("enable-trend-tracking", false, defaultBooleanUsage)

	// related to blocking
	enableBlocking := flag.Bool("enable-blocking", false, defaultBooleanUsage)
	refreshSeconds := flag.Int("blocking-refresh-rate-seconds", 30, defaultRefreshUsage)
	expireSeconds := flag.Int("blocking-expire-rate-seconds", 30, defaultExpireUsage)
	blocksRefreshUrl := flag.String("blocking-blocks-refresh-url", "http://localhost", defaultBlocksRefreshUrl)

	// for redis, if used
	redisAddress := flag.String("redis-address", ":6379", "Address to the Redis server")
	maxRedisConnections := flag.Int("max-redis-connections", 10, "Max connections to Redis")

	// related to invalid http verbs
	// (instead of GET, POST, HEAD ... you receive DOG, SHOE, FOREST, etc.)
	enableInvalidVerbs := flag.Bool("enable-invalid-verb-checking", false, defaultBooleanUsage)

	// related to unexpected http verbs
	// requires config file
	// config file states this file reachable over GET or HEAD, and you get a POST
	enableUnexpectedVerbs := flag.Bool("enable-unexpected-verb-checking", false, defaultBooleanUsage)
	resourceVerbsMappingFile := flag.String("resource-verbs-mapping-file", "resource-verbs-mapping.yml", defaultResourceVerbsMappingFile)

	// related to unexpected resources
	// requires config file
	// config file states all resources expected in the app (think site-map)
	// this analysis should help detect scanners probing for non-existent resources
	enableUnexpectedResources := flag.Bool("enable-unexpected-resource-checking", false, defaultBooleanUsage)
	resourcesFile := flag.String("resources-file", "resources.yml", defaultResourcesFile)

	flag.Parse()

	glog.Info("------------------------------------------------")
	glog.Infof("Settings:")
	glog.Infof("\tServer port %s", *port)
	glog.Infof("\tProxy url: %s", *url)
	glog.Infof("\tEnable TLS: %t", *enableTls)
	glog.Infof("\t\tCert File: %s", *certFile)
	glog.Infof("\t\tKey File: %s", *keyFile)
	glog.Infof("\tEnable trend tracking: %t", *enableTrends)
	glog.Infof("\tEnable blocking: %t", *enableBlocking)
	glog.Infof("\t\tRefresh rate (seconds): %d", *refreshSeconds)
	glog.Infof("\t\tExpire rate (seconds): %d", *expireSeconds)
	glog.Infof("\t\tBlock refresh url: %s", *blocksRefreshUrl)
	glog.Infof("\tEnable invalid verbs: %t", *enableInvalidVerbs)
	glog.Infof("\tEnable unexpected verbs: %t", *enableUnexpectedVerbs)
	glog.Infof("\t\tResource verbs mapping file: %s", *resourceVerbsMappingFile)
	glog.Infof("\tEnable unexpected resources: %t", *enableUnexpectedResources)
	glog.Infof("\t\tResources file: %s", *resourcesFile)
	glog.Info("------------------------------------------------")

	// proxy
	proxy := New(*url)

	proxyHandler := http.HandlerFunc(proxy.handle)

	// chain default handlers (clear context, recovery, and log execution time)
	chain := alice.New(
		context.ClearHandler,
		middleware.Recovery,
		middleware.LogExecutionTime)

	// if blocking is enabled, add it to alice chain
	if *enableBlocking {
		chain = chain.Append(middleware.Block)
		go doEvery((time.Duration(*refreshSeconds) * time.Second), func() { blocks.RefreshBlocks(blocksRefreshUrl) })
		go doEvery((time.Duration(*expireSeconds) * time.Second), blocks.ExpireBlocks)
	}

	// if trending is enabled, add it to alice chain
	if *enableTrends {
		chain = chain.Append(middleware.Trend)
	}

	// if invalid verb checking is enabled, add it to alice chain
	if *enableInvalidVerbs {
		chain = chain.Append(middleware.InvalidVerbs)
	}

	// if unexpected verb checking is enabled, add it to alice chain
	if *enableUnexpectedVerbs {
		middleware.PopulateExpectedVerbs(resourceVerbsMappingFile)
		chain = chain.Append(middleware.UnexpectedVerbs)
	}

	// if unexpected resource checking is enabled, add it to alice chain
	if *enableUnexpectedResources {
		middleware.PopulateExpectedResources(resourcesFile)
		chain = chain.Append(middleware.UnexpectedResources)
	}

	// if any of these settings are enabled, connect to redis
	if *enableTrends {
		connections.ConnectRedis(redisAddress, maxRedisConnections)
	}

	// if any of these settings are enabled, setup rest client to appsensor backend
	if *enableInvalidVerbs || *enableTrends ||
		*enableUnexpectedVerbs || *enableUnexpectedResources {
		ids.InitializeAppSensorRestClient()
	}

	// always use reverse proxy as chain target (final)
	chainHandler := chain.Then(proxyHandler)

	return enableTls, port, certFile, keyFile, chainHandler
}

func main() {

	enableTls, port, certFile, keyFile, chainHandler := parseFlags()

	if connections.RedisPool != nil {
		defer connections.RedisPool.Close()
	}

	if *enableTls {

		// serve over https
		// if you want to test this locally, generate a cert and key file using
		// go by running a command similar to :
		// "go run /usr/local/go/src/crypto/tls/generate_cert.go --host localhost"
		// and change the location to wherever go is installed on your system
		err := http.ListenAndServeTLS(*port, *certFile, *keyFile, chainHandler)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		// serve over http (non-secure)
		glog.Infof("WARNING: Running over plaintext http (insecure). " +
			"To enable https, use '-enable-tls'")
		http.ListenAndServe(*port, chainHandler)
	}

}


text:
<?php

namespace Communiverse\Genesis\Physics\Units\SI;

/**
 *
 * @author Steffen Kowalski <scipper@myscipper.de>
 *
 * @since 13.09.2015
 * @namespace Communiverse\Genesis\Physics\Units\SI
 * @package Communiverse\Genesis\Physics\Units\SI
 *
 */
interface SIUnit {

	/**
	 *
	 * @return string
	 */
	public function getUnit();

	/**
	 *
	 * @return string
	 */
	public function getName();

	/**
	 *
	 * @return array[SIUnit]
	 */
	public function getNumerator();

	/**
	 *
	 * @return array[SIUnit]
	 */
	public function getDenominator();

	/**
	 *
	 * @return string
	 */
	public function buildUnit();

}

?>


text:
/*
 * $Id: DOMElementNSImpl.hpp 678709 2008-07-22 10:56:56Z borisk $
 */

#if !defined(XERCESC_INCLUDE_GUARD_DOMELEMENTNSIMPL_HPP)
#define XERCESC_INCLUDE_GUARD_DOMELEMENTNSIMPL_HPP

//
//  This file is part of the internal implementation of the C++ XML DOM.
//  It should NOT be included or used directly by application programs.
//
//  Applications should include the file <xercesc/dom/DOM.hpp> for the entire
//  DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class
//  name is substituded for the *.
//

#include "DOMElementImpl.hpp"

XERCES_CPP_NAMESPACE_BEGIN

class DOMTypeInfoImpl;

class CDOM_EXPORT DOMElementNSImpl: public DOMElementImpl {
protected:
    //Introduced in DOM Level 2
    const XMLCh * fNamespaceURI;     //namespace URI of this node
    const XMLCh * fLocalName;        //local part of qualified name
    const XMLCh * fPrefix;
    const DOMTypeInfoImpl *fSchemaType;

public:
    DOMElementNSImpl(DOMDocument *ownerDoc, const XMLCh *name);
    DOMElementNSImpl(DOMDocument *ownerDoc, //DOM Level 2
                     const XMLCh *namespaceURI,
                     const XMLCh *qualifiedName);
    DOMElementNSImpl(const DOMElementNSImpl &other, bool deep=false);

    // Fast construction without any checks for name validity. Used in
    // parsing.
    //
    DOMElementNSImpl(DOMDocument *ownerDoc,
                     const XMLCh *namespaceURI,
                     const XMLCh *prefix,        // Null or empty - no prefix.
                     const XMLCh *localName,
                     const XMLCh *qualifiedName);

    virtual DOMNode * cloneNode(bool deep) const;
    virtual bool isSupported(const XMLCh *feature, const XMLCh *version) const;
    virtual void* getFeature(const XMLCh* feature, const XMLCh* version) const;

    //Introduced in DOM Level 2
    virtual const XMLCh *getNamespaceURI() const;
    virtual const XMLCh *getPrefix() const;
    virtual const XMLCh *getLocalName() const;
    virtual void         setPrefix(const XMLCh *prefix);
    virtual void         release();

    //Introduced in DOM Level 3
    virtual const DOMTypeInfo * getSchemaTypeInfo() const;

   // helper function for DOM Level 3 renameNode
   virtual DOMNode* rename(const XMLCh* namespaceURI, const XMLCh* name);
   void setName(const XMLCh* namespaceURI, const XMLCh* name);

    //helper function for DOM Level 3 TypeInfo
    virtual void setSchemaTypeInfo(const DOMTypeInfoImpl* typeInfo);

private:
    // -----------------------------------------------------------------------
    // Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    DOMElementNSImpl & operator = (const DOMElementNSImpl &);
};

XERCES_CPP_NAMESPACE_END

#endif


text:
package v1alpha1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// BundleBuilder builds component data. Practically speaking, the BundleBuilder
// builds Bundles, ComponentSets, and Components.
type BundleBuilder struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`

	// SetName for the resulting Bundle and ComponentSet. The combination of
	// SetName and Version should provide a unique identifier for the generate.
	SetName string `json:"setName,omitempty"`

	// Version for the Bundle and ComponentSet. See Bundle.Version for more
	// details. The version is optional for the ComponentBuilder
	Version string `json:"version,omitempty"`

	// ComponentNamePolicy defines how to generate the metadata.name
	// for a Component or ComponentBuilder that does not already have one.
	//  - SetAndComponent generates a name from the set name and version and
	//    component name and version.
	//  - Component (default) generates a name from the component name and version
	ComponentNamePolicy string `json:"componentNamePolicy,omitempty"`

	// ComponentFiles represent ComponentBuilder or Component types that are
	// referenced via file urls.
	ComponentFiles []File `json:"componentFiles,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// ComponentBuilder builds Components.
type ComponentBuilder struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`

	// ComponentName is the canonical name of this component. See
	// ComponentSpec.ComponentName for more details.
	ComponentName string `json:"componentName,omitempty"`

	// Version is the version for this component. See ComponentSpec.Version for
	// more details. The version is optional for the ComponentBuilder.
	Version string `json:"version,omitempty"`

	// Objects that are specified via a File-URL. The process of inlining a
	// component turns object files into objects.  During the inline process, if
	// the file is YAML-formatted and contains multiple objects in the YAML-doc,
	// the objects will be split into separate inline objects. In other words,
	// one object file may result in multiple objects.
	//
	// Each object file must be parsable into a Struct: In other words,
	// it should be representable as either YAML or JSON.
	ObjectFiles []File `json:"objectFiles,omitempty"`

	// TemplateFiles represent templates with a specific template type.
	// The process of inlining a component turns template files into
	// objectTemplates. During the inline process, each templateFileSet
	// which may contain one or multiple template files of the same type,
	// will be built into separate inline objects.
	TemplateFiles []TemplateFileSet `json:"templateFiles,omitempty"`

	// Raw files represent arbitrary string data. Unlike object files,
	// these files don't need to be parsable as YAML or JSON. So, during the
	// inline process, the data is inserted into a generated config map before
	// being added to the objects. A ConfigMap is generated per-filegroup.
	RawTextFiles []FileGroup `json:"rawTextFiles,omitempty"`
}

// TemplateFileSet represents a collection of template files which must be of the
// same template type.
type TemplateFileSet struct {
	// Type indicates how the template files should be detemplatized. It defaults
	// to Go Templates during build if left unspecified.
	TemplateType TemplateType `json:"templateType,omitempty"`

	// UseSafeYAMLTemplater determines whether to use SafeYAMLTemplating. If set,
	// this provides a default value for templates; it doesn't override values set
	// in individual object templates.
	UseSafeYAMLTemplater *bool `json:"useSafeYamlTemplater,omitempty"`

	// Templates files that are specified via a File-URL. During the
	// inline process, if the file is YAML-formatted and contains multiple
	// objects in the YAML-doc, the objects will be split into separate inline
	// objects. In other words, one template file may result in multiple objects.
	Files []File `json:"files,omitempty"`
}

// FileGroup represents a collection of files. When used to create ConfigMaps
// from RawTextFiles, the metadata.name comes from the Name field and data-key
// being the basename of File URL. Thus, if the url is something like
// 'file://foo/bar/biff.txt', the data-key will be 'biff.txt'.
type FileGroup struct {
	// Name of the filegroup. For raw text files, this becomes the name of the.
	Name string `json:"name,omitempty"`

	// AsBinary indicates whether to import this text as Binary data rather than
	// string data. Note that Binary data is only supported for Kubernetes
	// clusters > Kubernetes v1.10.
	AsBinary bool `json:"asBinary"`

	// Annotations to apply to the resulting config map.
	Annotations map[string]string `json:"annotations,omitempty"`

	// Labels to apply to the resulting config map.
	Labels map[string]string `json:"labels,omitempty"`

	// Files that make up this file group.
	Files []File `json:"files,omitempty"`
}

// File represents some sort of file that's specified external to a component or bundle,
// which could be on either a local or remote file system.
type File struct {
	// URL to find this file; the url string must be parsable via Go's net/url
	// library. It is generally recommended that a URI scheme be provided in the
	// URL, but it is not required. If a scheme is not provided, it is assumed
	// that the scheme is a file-scheme.
	//
	// For example, these are all valid:
	// - foo/bar/biff (a relative path)
	// - /foo/bar/biff (an absolute path)
	// - file:///foo/bar/biff (an absolute path with an explicit 'file' scheme)
	// - http://example.com/foo.yaml
	URL string `json:"url,omitempty"`

	// Digest is an optional hash of the file to ensure we are pulling
	// the correct binary/file.
	Digest string `json:"hash,omitempty"`
}


text:
Jag lägger upp en redovisningstext för vardera kursmoment och för att strukturera upp det hela så har jag lagt vardera redovisningstext under en dropdown menu ovanför. Genom den kan du välja specifikt kursmoment som du önskar läsa om.

Jag valde denna uppdelning då jag experimenterade med Anax-MVC och ville se hur jag kunde jobba på olika sätt med ramverket.

[link to dbwebb.se](http://dbwebb.se)


text:
<!--- Copyright (C) 2009-2017 Lightbend Inc. <https://www.lightbend.com> -->
# What's new in Play 2.1?

## Migration to Scala 2.10

The whole runtime API for Play have been migrated to Scala 2.10 allowing your applications to take part of the new great features provided by this new language release.

In the same time we have broken the dependency that was existing between the Scala version used by the _Build system_ (sbt), and the Scala version used at runtime. This way, it makes it easier to build and test Play on experimental or unstable branches of the Scala language.

## Migration to `scala.concurrent.Future`

One of the greatest feature provided by Scala 2.10 is the new standard `scala.concurrent.Future` library for managing asynchronous code in Scala. Play is now based itself on this API, and its great asynchronous HTTP and streaming features are now compatible directly with any other library using the same API.

It makes it even simpler to use Play with Akka, or any upcoming asynchronous datastore driver that will use this new API.

In the same time, we worked to simplify the execution context model, and by providing an easy way to choose for each part of your application, the underlying `ExecutionContext` used to run your code.

## Modularization

The Play project has been split on many sub-projects, allowing you to select the minimal set of dependency needed for your project.

You have to select the exact set of optional dependencies your application need, in the list of:

- `jdbc` : The **JDBC** connection pool and the `play.api.db` API.
- `anorm` : The **Anorm** component.
- `javaCore` : The core **Java** API.
- `javaJdbc` : The Java database API.
- `javaEbean` : The Ebean plugin for Java.
- `javaJpa` : The JPA plugin for Java.
- `filters` : A set of build-in filters for Play (such as the CSRF filter)

The `play` core project has now a very limited set of external dependencies and can be used as a minimal asynchronous, high performance HTTP server without the other components.

## Allow more modularization for your projects

To allow, to compose and reuse components in your own projects further, Play 2.1 supports sub-Router composition.

For example, a sub project can define its own router component, using its own namespace, such as:

In `conf/my.subproject.routes`

```
GET   /                   my.subproject.controllers.Application.index
```

And then, you can integrate this component into your main application, by wiring the Router, such as:

```
# The home page
GET   /                   controllers.Application.index

# Include a sub-project
->    /my-subproject      my.subproject.Routes

# The static assets
GET   /public/*file       controllers.Assets.at(file)
```

In the configuration, at runtime a call to the `/my-subproject` URL will eventually invoke the `my.subproject.controllers.Application.index` Action.

> Note: in order to avoid name collision issues with the main application, always make sure that you define a subpackage within your controller classes that belong to a sub project (i.e. `my.subproject` in this particular example). You'll also need to make sure that the subproject's Assets controller is defined in the same name space.

More information about this feature can be found at [[Working with sub-projects|SBTSubProjects]].

## `Http.Context` propagation in the Java API

In Play 2.0, the HTTP context was lost during the asynchronous callback, since these code fragment are run on different thread than the original one handling the HTTP request.

Consider:

```
public static Result index() {
  return async(
    aServiceSomewhere.getData().map(new Function<String,Result>(data) {
      // Ouch! You try to access the request data in an asynchronous callback
      String user = session().get("user");
      return ok("Here is the result " + user + ": " + data);
    })
  );
}
```

This code wasn't working this way. For really good reason, if you think about the underlying asynchronous architecture, but yet it was really surprising for Java developers.

We eventually found a way to solve this problem and to propagate the `Http.Context` over a stack spanning several threads, so this code is now working this way.

## Better threading model for the Java API

While running asynchronous code over mutable data structures, chances are right that you hit some race conditions if you don't synchronize properly your code. Because Play promotes highly asynchronous and non-blocking code, and because Java data structure are mostly mutable and not thread-safe, it is the responsibility of your code to deal with the synchronization issues.

Consider:

```
public static Result index() {

  final HashMap<String,Integer> result = new HashMap<String,Integer>();

  aService.doSomethingAsync().map(new Function<String,String>(key) {
    Integer i = result.get(key);
    if(i != null) {
      result.set(key, i++);
    }
    return key;
  });

  aService.doSomethingElse().map(new Function<String,String>(key) {
    result.remove(key);
    return null;
  });

  ...
}
```

In this code, chances are really high to hit a race condition if the 2 callbacks are run in the same time on 2 different threads, while accessing each to the share `result` HashMap. And the consequence will be probably some pseudo-deadlock in your application because of the implementation of the underlying Java HashMap.

To avoid any of these problems, we decided to manage the callback execution synchronization at the framework level. Play 2.1 will never run concurrently 2 callbacks for the same `Http.Context`. In this context, all callback execution will be run sequentially (while there is no guarantees that they will run on the same thread).

## Managed Controller classes instantiation

By default Play binds URLs to controller methods statically, that is, no Controller instances are created by the framework and the appropriate static method is invoked depending on the given URL. In certain situations, however, you may want to manage controller creation and that's when the new routing syntax comes handy.

Route definitions starting with @ will be managed by the `Global::getControllerInstance` method, so given the following route definition:

```
GET     /                  @controllers.Application.index()
```

Play will invoke the `getControllerInstance` method which in return will provide an instance of `controllers.Application` (by default this is happening via the default constructor). Therefore, if you want to manage controller class instantiation either via a dependency injection framework or manually you can do so by overriding getControllerInstance in your application's Global class.

As this example [demonstrates it](https://github.com/guillaumebort/play20-spring-demo), it allows to wire any dependency injection framework such as __Spring__ into your Play application.

## New Scala JSON API

The new Scala JSON API provide great features such as transformation and validation of JSON tree. Check the new documentation at the [[Scala Json combinators document|ScalaJsonCombinators]].

## New Filter API and CSRF protection

Play 2.1 provides a new and really powerful filter API allowing to intercept each part of the HTTP request or response, in a fully non-blocking way.

For that, we introduced a new simpler type replacing the old `Action[A]` type, called `EssentialAction` which is defined as:

```
RequestHeader => Iteratee[Array[Byte], Result]
```

As a result, a filter is simply defined as:

```
EssentialAction => EssentialAction
```

> __Note__: The old `Action[A]` type is still available for compatibility.

The `filters` project that is part of the standard Play distribution contain a set of standard filter, such as the `CSRF` providing automatic token management against the CSRF security issue.

## RequireJS

In play 2.0 the default behavior for Javascript was to use google closure's commonJS module support. In 2.1 this was changed to use [requireJS](http://requirejs.org/) instead.

What this means in practice is that by default Play will only minify and combine files in stage, dist, start modes only. In dev mode Play will resolve dependencies client side.

If you wish to use this feature, you will need to add your modules to the settings block of your build file:

```
requireJs := "main.js"
```

More information about this feature can be found on the [[RequireJS documentation page|RequireJS-support]].

## Content negotiation

The support of content negotiation has been improved, for example now controllers automatically choose the most appropriate lang according to the quality values set in the `Accept-Language` request header value.

It is also easier to write Web Services supporting several representations of a same resource and automatically choosing the best according to the `Accept` request header value:

```
val list = Action { implicit request =>
  val items = Item.findAll
  render {
    case Accepts.Html() => Ok(views.html.list(items))
    case Accepts.Json() => Ok(Json.toJson(items))
  }
}
```

More information can be found on the content negotiation documentation pages for [[Scala|ScalaContentNegotiation]] and [[Java|JavaContentNegotiation]].