text:
<?xml version="1.0" encoding="UTF-8"?>
<Export generator="Cache" version="25">
<Class name="iKnow.SetAnalysisPlugin.Relation">
<Super>iKnow.SetAnalysisPlugin</Super>
<TimeCreated>63802,41705.633712</TimeCreated>

<Parameter name="PluginId">
<Description>
ID's 1-999 are reserved, custom plugins start with 1000</Description>
<Default>15</Default>
</Parameter>

<Parameter name="Order">
<Description>
Order in which they appear in dropdown lists</Description>
<Default>15</Default>
</Parameter>

<Parameter name="Name">
<Default>Relation</Default>
</Parameter>

<Parameter name="ShortDescription">
<Default><![CDATA[Returns all iKnow Relations that are found in a CRC with the Concept.
The Concept can be a master (Crc) or a slave (crC) Concept.
.Enter a concept OR an existing Set.]]></Default>
</Parameter>

<Parameter name="LongDescription">
</Parameter>

<Parameter name="InputLabel">
<Default>Concept</Default>
</Parameter>

<Parameter name="InputPlaceholder">
<Default>concept</Default>
</Parameter>

<Parameter name="SetLabel">
<Default>Set</Default>
</Parameter>

<Parameter name="InputSize">
<Default>50</Default>
</Parameter>

<Parameter name="iKnowDomain">
<Default>1</Default>
</Parameter>

<Parameter name="InputSet">
<Default>1</Default>
</Parameter>

<Parameter name="InputPattern">
<Default>1</Default>
</Parameter>

<Parameter name="Metafield">
<Default>1</Default>
</Parameter>

<Parameter name="TermType">
<Default>ENTITY</Default>
</Parameter>

<Parameter name="DisableManualSelection">
<Default>0</Default>
</Parameter>

<Parameter name="PageSize">
<Default>500</Default>
</Parameter>

<Method name="GetPlugin">
<ClassMethod>1</ClassMethod>
<FormalSpec>PluginId:%Integer,ProjectId:%String,Input:%String,InputPattern:%String="",InputSet:%String,objFilter:%String,*resultPtr:%String,Blacklists:%String="",Batch:%Boolean=0,PageSize:%String="500"</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
	#Dim Page as %Integer
	#Dim relation as %String
	Set DomainId=##class(iKnow.SetAnalysis.Projects).GetDomainId(ProjectId)
	Set sc=$$$OK
	Do ..GetPageSize(.Page, .PageSize, Batch, ..#PageSize)
	If $Get(resultPtr)="" Set resultPtr=$i(^iKnow.SetAnalysisTemp)
 	If InputSet'="" {
		Kill result
		Set Input=""
		Do ..GetPublicProjectSet(InputSet, .ProjectId, .InputSet)  //replace if public set
		For  {
			Set Input=$Order(^iKnow.SetAnalysis(ProjectId, InputSet, "E", Input)) If Input="" Quit
			Kill resultInput
			Set sc = ..GetByEntities(.resultInput, DomainId, $lb(Input), Page, PageSize, objFilter)
			Set iCount=""
			For  {
				Set iCount=$Order(resultInput(iCount)) If iCount="" Quit
				Set result($i(result))=resultInput(iCount)
			}
		}
	} else {
		If Input["|" {
			Kill tempresult
			Set result=""
			If $Piece(Input,"|",1)'="" {
				Set sc = ..GetByEntities(.tempresult, DomainId, $ListFromString($Piece(Input,"|",1),","), Page, PageSize, objFilter,$$$USEPOSM)
				Merge result=tempresult
				set result=$Order(result(""),-1)
			}
			If $Piece(Input,"|",2)'="" {
				Set sc = ..GetByEntities(.tempresult, DomainId, $ListFromString($Piece(Input,"|",2),","), Page, PageSize, objFilter,$$$USEPOSS)
				If (result="") {  //all results from 2 are valid
					Merge result=tempresult
				} else {  //AND
					Set iResult="" For {
						Set iResult=$Order(result(iResult)) if iResult="" Quit
						Set Found=0 Set jResult=""
						For {
							Set jResult=$Order(tempresult(jResult)) If jResult="" Quit
							  If $List(tempresult(jResult),1)=$List(result(iResult),1) Set Found=1
						}
						If 'Found Kill result(iResult)
					}
				}
			}
		} else {
			Set sc = ..GetByEntities(.result, DomainId, $ListFromString(Input,","), Page, PageSize, objFilter)
		}
	}

	Set resultEnt=$Get(^iKnow.SetAnalysisTemp(resultPtr),0)
	Kill ^||iKnow.SetAnalysisTemp
	Set iCount="" For {
		Set iCount=$Order(result(iCount),1,data) If iCount="" Quit
		set relation=$list(data,3)
		If InputPattern'="" {
			Set relation=..ReplacePattern($List(data,3),InputPattern)
		}
		If relation="" Continue
		Set frequency=$List(data,5)
		Set ^||iKnow.SetAnalysisTemp(relation)=$Get(^||iKnow.SetAnalysisTemp(relation))+frequency
		Set relationId=##class(%iKnow.Queries.EntityAPI).GetId(DomainId, relation)
		If +relationId'=0 Set ^||iKnow.SetAnalysisTemp(relation,relationId)=$list(data,5)
	}
	Set relation=""
	For {
		Set relation=$Order(^||iKnow.SetAnalysisTemp(relation)) If relation="" Quit
		Set frequency=^||iKnow.SetAnalysisTemp(relation)
		Set sort=" "_$J(99999999-frequency,8)_$ZCVT(relation,"U")
		Set relationId="",relationIdList=""
		For {
			Set relationId=$Order(^||iKnow.SetAnalysisTemp(relation,relationId)) If relationId="" Quit
			Set relationIdList=relationIdList_$ListBuild(relationId)
			Set resultEnt=resultEnt+1
		}
		Set ^iKnow.SetAnalysisTemp(resultPtr,"S",sort,relationIdList)=$ListBuild(relation_" [ "_frequency_" ]")
	}
	Set ^iKnow.SetAnalysisTemp(resultPtr,"S")=resultEnt
	Quit sc
]]></Implementation>
</Method>

<Method name="GetByEntities">
<ClassMethod>1</ClassMethod>
<FormalSpec><![CDATA[&resultInput,DomainId,Input,Page,PageSize,objFilter,Type]]></FormalSpec>
<Implementation><![CDATA[
	If '$Data(Type) Set Type = $$$USEPOSALL
	If PageSize [ "#" {
		Set CutOff = +PageSize
		Set PageSize = 100
		Set iCount = 0, Stop = 0
		For Page=1:1 {
			Set sc = ##class(%iKnow.Queries.CrcAPI).GetByEntities(.resultTemp, DomainId, Input, Page, PageSize, objFilter,,Type)
			If $Order(resultTemp(""))="" Quit
			Set iResult=""
			For {
				Set iResult=$Order(resultTemp(iResult),1,data) If iResult="" Quit
				If $List(data,5) < CutOff Set Stop = 1 Quit
				Set iCount=iCount+1
				Set resultInput(iCount)=data
			}
			If Stop Quit
		}
	}
	else {
		Set sc = ##class(%iKnow.Queries.CrcAPI).GetByEntities(.resultInput, DomainId, Input, Page, PageSize, objFilter,,Type)
	}
	Return sc
]]></Implementation>
</Method>

<Method name="GetPluginValue">
<ClassMethod>1</ClassMethod>
<FormalSpec>ProjectId,resultPtr,Id</FormalSpec>
<ReturnType>%String</ReturnType>
<Implementation><![CDATA[
	Set DomainId=##class(iKnow.SetAnalysis.Projects).GetDomainId(ProjectId)
	Set Value = ##class(%iKnow.Queries.EntityAPI).GetValue(DomainId, Id)
	Quit Value
]]></Implementation>
</Method>

<Method name="GetPluginId">
<ClassMethod>1</ClassMethod>
<FormalSpec>ProjectId,resultPtr,Value</FormalSpec>
<ReturnType>%String</ReturnType>
<Implementation><![CDATA[
	Set DomainId=##class(iKnow.SetAnalysis.Projects).GetDomainId(ProjectId)
	Quit ##class(%iKnow.Queries.EntityAPI).GetId(DomainId, Value)
]]></Implementation>
</Method>

<Method name="SetPluginMembers">
<ClassMethod>1</ClassMethod>
<FormalSpec>ProjectId:%String,resultPtr:%String,SaveSet:%String,TermType:%String</FormalSpec>
<Implementation><![CDATA[
	Set DomainId=##class(iKnow.SetAnalysis.Projects).GetDomainId(ProjectId)
	&sql(Select iKnowMetafield, iKnowMetafieldMethod into :fieldName,:fieldMethod from iKnow_SetAnalysis.Projects Where Id =:ProjectId)
	If fieldName'="" {
		Set fieldId=##class(%iKnow.Queries.MetadataAPI).GetFieldId(DomainId, fieldName, .sc)
	} else {
		Set fieldId=""
	}
	Do ##class(iKnow.SetAnalysis).BuildFilterFromSet(ProjectId, SaveSet,.objFilter)
	Set Value="" For  {
		Set Value=$Order(^iKnow.SetAnalysis(ProjectId, SaveSet, "E", Value),1,id) If Value="" Quit
		If '$ListValid(id) Set entList=$lb(id)
		Set sc = ##class(%iKnow.Queries.SourceAPI).GetByEntityIds(.result, DomainId, entList, 0,,objFilter)
		Do ..StoreMetaValues(TermType,ProjectId,SaveSet,fieldId,fieldName,fieldMethod,entList,.result)
	}
]]></Implementation>
</Method>

<Storage name="Default">
<Type>%Library.CacheStorage</Type>
</Storage>
</Class>
</Export>


text:
/**
 * @file
 * Drupal Image plugin.
 *
 * This alters the existing CKEditor image2 widget plugin to:
 * - require a data-entity-type and a data-entity-uuid attribute (which Drupal
 *   uses to track where images are being used)
 * - use a Drupal-native dialog (that is in fact just an alterable Drupal form
 *   like any other) instead of CKEditor's own dialogs.
 *
 * @see \Drupal\editor\Form\EditorImageDialog
 *
 * @ignore
 */

(function ($, Drupal, CKEDITOR) {

  "use strict";

  CKEDITOR.plugins.add('drupalimage', {
    requires: 'image2',

    beforeInit: function (editor) {
      // Override the image2 widget definition to require and handle the
      // additional data-entity-type and data-entity-uuid attributes.
      editor.on('widgetDefinition', function (event) {
        var widgetDefinition = event.data;
        if (widgetDefinition.name !== 'image') {
          return;
        }

        // Override requiredContent & allowedContent.
        widgetDefinition.requiredContent = 'img[alt,src,width,height,data-entity-type,data-entity-uuid]';
        widgetDefinition.allowedContent.img.attributes += ',!data-entity-type,!data-entity-uuid';
        // We don't allow <figure>, <figcaption>, <div> or <p>  in our downcast.
        delete widgetDefinition.allowedContent.figure;
        delete widgetDefinition.allowedContent.figcaption;
        delete widgetDefinition.allowedContent.div;
        delete widgetDefinition.allowedContent.p;

        // Override the 'link' part, to completely disable image2's link
        // support: http://dev.ckeditor.com/ticket/11341.
        widgetDefinition.parts.link = 'This is a nonsensical selector to disable this functionality completely';

        // Override downcast(): since we only accept <img> in our upcast method,
        // the element is already correct. We only need to update the element's
        // data-entity-uuid attribute.
        widgetDefinition.downcast = function (element) {
          element.attributes['data-entity-uuid'] = this.data['data-entity-uuid'];
        };

        // We want to upcast <img> elements to a DOM structure required by the
        // image2 widget; we only accept an <img> tag, and that <img> tag MAY
        // have a data-entity-type and a data-entity-uuid attribute.
        widgetDefinition.upcast = function (element, data) {
          if (element.name !== 'img') {
            return;
          }
          // Don't initialize on pasted fake objects.
          else if (element.attributes['data-cke-realelement']) {
            return;
          }

          // Parse the data-entity-type attribute.
          data['data-entity-type'] = element.attributes['data-entity-type'];
          // Parse the data-entity-uuid attribute.
          data['data-entity-uuid'] = element.attributes['data-entity-uuid'];

          return element;
        };

        // Protected; keys of the widget data to be sent to the Drupal dialog.
        // Keys in the hash are the keys for image2's data, values are the keys
        // that the Drupal dialog uses.
        widgetDefinition._mapDataToDialog = {
          'src': 'src',
          'alt': 'alt',
          'width': 'width',
          'height': 'height',
          'data-entity-type': 'data-entity-type',
          'data-entity-uuid': 'data-entity-uuid'
        };

        // Protected; transforms widget's data object to the format used by the
        // \Drupal\editor\Form\EditorImageDialog dialog, keeping only the data
        // listed in widgetDefinition._dataForDialog.
        widgetDefinition._dataToDialogValues = function (data) {
          var dialogValues = {};
          var map = widgetDefinition._mapDataToDialog;
          Object.keys(widgetDefinition._mapDataToDialog).forEach(function (key) {
            dialogValues[map[key]] = data[key];
          });
          return dialogValues;
        };

        // Protected; the inverse of _dataToDialogValues.
        widgetDefinition._dialogValuesToData = function (dialogReturnValues) {
          var data = {};
          var map = widgetDefinition._mapDataToDialog;
          Object.keys(widgetDefinition._mapDataToDialog).forEach(function (key) {
            if (dialogReturnValues.hasOwnProperty(map[key])) {
              data[key] = dialogReturnValues[map[key]];
            }
          });
          return data;
        };

        // Protected; creates Drupal dialog save callback.
        widgetDefinition._createDialogSaveCallback = function (editor, widget) {
          return function (dialogReturnValues) {
            var firstEdit = !widget.ready;

            // Dialog may have blurred the widget. Re-focus it first.
            if (!firstEdit) {
              widget.focus();
            }

            editor.fire('saveSnapshot');

            // Pass `true` so DocumentFragment will also be returned.
            var container = widget.wrapper.getParent(true);
            var image = widget.parts.image;

            // Set the updated widget data, after the necessary conversions from
            // the dialog's return values.
            // Note: on widget#setData this widget instance might be destroyed.
            var data = widgetDefinition._dialogValuesToData(dialogReturnValues.attributes);
            widget.setData(data);

            // Retrieve the widget once again. It could've been destroyed
            // when shifting state, so might deal with a new instance.
            widget = editor.widgets.getByElement(image);

            // It's first edit, just after widget instance creation, but before
            // it was inserted into DOM. So we need to retrieve the widget
            // wrapper from inside the DocumentFragment which we cached above
            // and finalize other things (like ready event and flag).
            if (firstEdit) {
              editor.widgets.finalizeCreation(container);
            }

            setTimeout(function () {
              // (Re-)focus the widget.
              widget.focus();
              // Save snapshot for undo support.
              editor.fire('saveSnapshot');
            });

            return widget;
          };
        };
      });

      // Add a widget#edit listener to every instance of image2 widget in order
      // to handle its editing with a Drupal-native dialog.
      // This includes also a case just after the image was created
      // and dialog should be opened for it for the first time.
      editor.widgets.on('instanceCreated', function (event) {
        var widget = event.data;

        if (widget.name !== 'image') {
          return;
        }

        widget.on('edit', function (event) {
          // Cancel edit event to break image2's dialog binding
          // (and also to prevent automatic insertion before opening dialog).
          event.cancel();

          // Open drupalimage dialog.
          editor.execCommand('editdrupalimage', {
            existingValues: widget.definition._dataToDialogValues(widget.data),
            saveCallback: widget.definition._createDialogSaveCallback(editor, widget),
            // Drupal.t() will not work inside CKEditor plugins because CKEditor
            // loads the JavaScript file instead of Drupal. Pull translated
            // strings from the plugin settings that are translated server-side.
            dialogTitle: widget.data.src ? editor.config.drupalImage_dialogTitleEdit : editor.config.drupalImage_dialogTitleAdd
          });
        });
      });

      // Register the "editdrupalimage" command, which essentially just replaces
      // the "image" command's CKEditor dialog with a Drupal-native dialog.
      editor.addCommand('editdrupalimage', {
        allowedContent: 'img[alt,!src,width,height,!data-entity-type,!data-entity-uuid]',
        requiredContent: 'img[alt,src,width,height,data-entity-type,data-entity-uuid]',
        modes: {wysiwyg: 1},
        canUndo: true,
        exec: function (editor, data) {
          var dialogSettings = {
            title: data.dialogTitle,
            dialogClass: 'editor-image-dialog'
          };
          Drupal.ckeditor.openDialog(editor, Drupal.url('editor/dialog/image/' + editor.config.drupal.format), data.existingValues, data.saveCallback, dialogSettings);
        }
      });

      // Register the toolbar button.
      if (editor.ui.addButton) {
        editor.ui.addButton('DrupalImage', {
          label: Drupal.t('Image'),
          // Note that we use the original image2 command!
          command: 'image',
          icon: this.path + '/image.png'
        });
      }
    },

    // Disable image2's integration with the link/drupallink plugins: don't
    // allow the widget itself to become a link. Support for that may be added
    // by an text filter that adds a data- attribute specifically for that.
    afterInit: function (editor) {
      if (editor.plugins.drupallink) {
        var cmd = editor.getCommand('drupallink');
        // Needs to be refreshed on selection changes.
        cmd.contextSensitive = 1;
        // Disable command and cancel event when the image widget is selected.
        cmd.on('refresh', function (evt) {
          var widget = editor.widgets.focused;
          if (widget && widget.name === 'image') {
            this.setState(CKEDITOR.TRISTATE_DISABLED);
            evt.cancel();
          }
        });
      }
    }

  });

})(jQuery, Drupal, CKEDITOR);

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2014 Lockheed Martin Corporation

    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.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>streamflow</groupId>
        <artifactId>streamflow-app</artifactId>
        <version>0.13.0-SNAPSHOT</version>
    </parent>

    <artifactId>streamflow-app-jar</artifactId>
    <name>StreamFlow Application JAR</name>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>streamflow</groupId>
            <artifactId>streamflow-server</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Maven Shade Plugin (Includes all dependencies) -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <createDependencyReducedPom>false</createDependencyReducedPom>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>streamflow.server.StreamflowServer</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <!-- Execution plugin to run the application from the final jar -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.3.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <executable>java</executable>
                    <arguments>
                        <argument>-jar</argument>
                        <argument>${project.build.directory}/${project.build.finalName}.jar</argument>
                    </arguments>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
This page was generated with Wiki Builder. Do not change the format!

## Info
Items like Sacks or Boxes can have items that it shows in-game when you view details that represent the items you can obtain if you use or acquire the item. This defines those categories, and gives some insights into that data's source.

## Schema
* **Schema Type:** Definition
* **Type:** object

## Properties
Name | Type | Description
---- | ---- | -----------
previewVendorHash | [[Destiny.Definitions.DestinyVendorDefinition|Destiny-Definitions-DestinyVendorDefinition]]:integer:uint32 | If the preview data is derived from a fake "Preview" Vendor, this will be the hash identifier for the DestinyVendorDefinition of that fake vendor.
previewActionString | string | If the preview has an associated action (like "Open"), this will be the localized string for that action.
derivedItemCategories | [[DestinyDerivedItemCategoryDefinition|Destiny-Definitions-Items-DestinyDerivedItemCategoryDefinition]]:Definition[] | This is a list of the items being previewed, categorized in the same way as they are in the preview UI.

## Example
```javascript
{
    // Type: [[Destiny.Definitions.DestinyVendorDefinition|Destiny-Definitions-DestinyVendorDefinition]]:integer:uint32
    "previewVendorHash": 0,
    // Type: string
    "previewActionString": "",
    // Type: [[DestinyDerivedItemCategoryDefinition|Destiny-Definitions-Items-DestinyDerivedItemCategoryDefinition]]:Definition[]
    "derivedItemCategories": [
       // Type: [[DestinyDerivedItemCategoryDefinition|Destiny-Definitions-Items-DestinyDerivedItemCategoryDefinition]]:Definition
        {
            // Type: string
            "categoryDescription": "",
            // Type: [[DestinyDerivedItemDefinition|Destiny-Definitions-Items-DestinyDerivedItemDefinition]]:Definition[]
            "items": [
               // Type: [[DestinyDerivedItemDefinition|Destiny-Definitions-Items-DestinyDerivedItemDefinition]]:Definition
                {
                    // Type: integer:uint32:nullable
                    "itemHash": 0,
                    // Type: string
                    "itemName": "",
                    // Type: string
                    "itemDetail": "",
                    // Type: string
                    "itemDescription": "",
                    // Type: string
                    "iconPath": "",
                    // Type: integer:int32
                    "vendorItemIndex": 0
                }
            ]
        }
    ]
}

```

## References
1. https://bungie-net.github.io/multi/schema_Destiny-Definitions-DestinyItemPreviewBlockDefinition.html#schema_Destiny-Definitions-DestinyItemPreviewBlockDefinition


text:
<?php

/** Tests for MediaWiki languages/classes/LanguageHsb.php */
class LanguageHsbTest extends LanguageClassesTestCase {
	/**
	 * @dataProvider providePlural
	 * @covers Language::convertPlural
	 */
	public function testPlural( $result, $value ) {
		$forms = [ 'one', 'two', 'few', 'other' ];
		$this->assertEquals( $result, $this->getLang()->convertPlural( $value, $forms ) );
	}

	/**
	 * @dataProvider providePlural
	 * @covers Language::getPluralRuleType
	 */
	public function testGetPluralRuleType( $result, $value ) {
		$this->assertEquals( $result, $this->getLang()->getPluralRuleType( $value ) );
	}

	public static function providePlural() {
		return [
			[ 'other', 0 ],
			[ 'one', 1 ],
			[ 'one', 101 ],
			[ 'one', 90001 ],
			[ 'two', 2 ],
			[ 'few', 3 ],
			[ 'few', 203 ],
			[ 'few', 4 ],
			[ 'other', 99 ],
			[ 'other', 555 ],
		];
	}
}


text:
package io.airlift.bootstrap;

import javax.annotation.PreDestroy;
import javax.inject.Inject;

public class DestroyExceptionInstance
{
    @Inject
    public DestroyExceptionInstance(DependentInstance ignored)
    {
        // the constructor exists to force injection of the dependent instance
    }

    @PreDestroy
    public void preDestroyExceptionOne()
    {
        TestLifeCycleManager.note("preDestroyExceptionOne");
        throw new IllegalStateException("preDestroyExceptionOne");
    }

    @PreDestroy
    public void preDestroyExceptionTwo()
    {
        TestLifeCycleManager.note("preDestroyExceptionTwo");
        throw new IllegalStateException("preDestroyExceptionTwo");
    }
}


text:
package CellularAutomata;

import Cell.Cell;
import Cell.HexagonalCell;
import Cell.SquareCell;
import Cell.TriangleCell;
import CellContent.FireContent;

import java.util.*;

import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.paint.Color;

public class FireRules extends CellularAutomata {
	private int probCatchesFire;
	private Color burning;
	private Color burnt;
	private Color burnable;
	private int steps, treesAlive;

	public FireRules(int rows, int columns, int wid, int hei, int probCatch, String tile, String edge, Color burningColor,Color burnableColor,Color burntColor, String dir) {
		height = hei;
		width = wid;
		rowCount = rows;
		colCount = columns;
		tileType = tile;
		edgeType = edge;
		probCatchesFire = probCatch;
		useProbType = false;
		useProbEmpty = false;
		burning=burningColor;
		burnt=burntColor;
		burnable=burnableColor;
		neighborDirection=dir;
		steps = 0;
		treesAlive = 0;
		placeCells();
	}

	@Override
	public void update() {
		steps++;
		Map<Integer, Cell> gridClone = cloneGrid(grid);
		Random r = new Random();
		for (int i = 0; i < grid.keySet().size(); i++) {
			if (grid.get(i).getContent().getState() == 2) {
				gridClone.get(i).getContent().setStateandColor(0, burnt);
			} else if (grid.get(i).getContent().getState() == 1 && fireNeighbors(grid.get(i)) > 0
					&& r.nextInt(100) < probCatchesFire) {
				gridClone.get(i).getContent().setStateandColor(2, burning);

			}
		}
		updatePopulationSize();
		grid = gridClone;
	}

	public void createSquareGrid() {
		int w = width / colCount;
		int h = height / rowCount;
		grid = new TreeMap<Integer, Cell>();
		for (int i = 0; i < rowCount; i++) {
			for (int j = 0; j < colCount; j++) {
				int k = i + j * rowCount;
				if (j == 0 || j == colCount - 1 || i == 0 || i == rowCount - 1) {
					grid.put(k, new SquareCell(i * w, j * h, i, j, new FireContent(0, burnt)));
				} else if (i == rowCount / 2 && j == colCount / 2) {
					grid.put(k, new SquareCell(i * w, j * h, i, j, new FireContent(2, burning)));
				} else {
					grid.put(k, new SquareCell(i * w, j * h, i, j, new FireContent(1, burnable)));
					treesAlive++;
				}
			}
		}
	}

	@Override
	public void createTriangleGrid() {
		int w = width / colCount;
		int h = height / rowCount;
		grid = new TreeMap<Integer, Cell>();
		for (int i = 0; i < rowCount; i++) {
			for (int j = 0; j < colCount; j++) {
				int k = i + j * rowCount;
				if ((j == 0 && i % 2 == 0) || (j == colCount - 1 && (rowCount - i) % 2 == 0) || i == 0
						|| i == rowCount - 1) {
					grid.put(k, new TriangleCell(i * w, j * h, w, h, i, j, new FireContent(0, burnt)));
				} else if (i == rowCount / 2 && j == colCount / 2) {
					grid.put(k, new TriangleCell(i * w, j * h, w, h, i, j, new FireContent(2, burning)));
				} else {
					grid.put(k, new TriangleCell(i * w, j * h, w, h, i, j, new FireContent(1, burnable)));
					treesAlive++;
				}
			}
		}
	}

	@Override
	public void createHexagonalGrid() {
		double side = 0;
		if (rowCount % 2 == 0 && colCount % 2 == 0) {
			side = height / (rowCount) / Math.sqrt(3);
		}
		grid = new TreeMap<Integer, Cell>();
		for (int i = 0; i < rowCount; i++) {
			for (int j = 0; j < colCount; j++) {
				int k = i + j * rowCount;
				if ((j == 0 && i % 2 == 0) || (j == colCount - 1 && (rowCount - i) % 2 == 1) || i <= 1
						|| i >= rowCount - 2) {
					grid.put(k, new HexagonalCell(i, j, side, new FireContent(0, burnt)));
				} else if (i == rowCount / 2 && j == colCount / 2) {
					grid.put(k, new HexagonalCell(i, j, side, new FireContent(2, burning)));
				} else {
					grid.put(k, new HexagonalCell(i, j, side, new FireContent(1, burnable)));
					treesAlive++;
				}
			}
		}
	}

	private void updatePopulationSize() {
		int count = 0;
		for (int i = 0; i < grid.keySet().size(); i++) {
			if (grid.get(i).getContent().getState() == 1) {
				count++;
			}
		}
		treesAlive = count;
	}

	private int fireNeighbors(Cell cell) {
		int fire = 0;
		List<Cell> neighbors = checkNeighbors(cell, false);
		for (Cell c : neighbors) {
			if (c.getContent().getState() == 2) {
				fire++;
			}
		}
		return fire;
	}

    public int getProbCatchesFire(){
        return probCatchesFire;
    }
    public void setProbCatchesFire(int f){
        probCatchesFire = f;
    }
	@Override
	public void graphStats(Series<Number, Number> graphLocation) {
		// TODO Auto-generated method stub
		graphLocation.getData().add(new XYChart.Data(steps, treesAlive));
	}

}


text:
package com.opengamma.master.position.impl;

import java.net.URI;

import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import com.opengamma.id.ObjectId;
import com.opengamma.master.position.PositionDocument;
import com.opengamma.master.position.PositionMaster;
import com.opengamma.master.position.PositionSearchRequest;
import com.opengamma.master.position.PositionSearchResult;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.rest.AbstractDataResource;

/**
 * RESTful resource for positions.
 * <p>
 * The positions resource receives and processes RESTful calls to the position master.
 */
@Path("positionMaster")
public class DataPositionMasterResource extends AbstractDataResource {

  /**
   * The position master.
   */
  private final PositionMaster _posMaster;

  /**
   * Creates the resource, exposing the underlying master over REST.
   *
   * @param positionMaster  the underlying position master, not null
   */
  public DataPositionMasterResource(final PositionMaster positionMaster) {
    ArgumentChecker.notNull(positionMaster, "positionMaster");
    _posMaster = positionMaster;
  }

  //-------------------------------------------------------------------------
  /**
   * Gets the position master.
   *
   * @return the position master, not null
   */
  public PositionMaster getPositionMaster() {
    return _posMaster;
  }

  //-------------------------------------------------------------------------
  @GET
  public Response getHateaos(@Context final UriInfo uriInfo) {
    return hateoasResponse(uriInfo);
  }

  @HEAD
  @Path("positions")
  public Response status() {
    // simple HEAD to quickly return, avoiding loading the whole database
    return responseOk();
  }

  @POST
  @Path("positionSearches")
  public Response search(final PositionSearchRequest request) {
    final PositionSearchResult result = getPositionMaster().search(request);
    return responseOkObject(result);
  }

  @POST
  @Path("positions")
  public Response add(@Context final UriInfo uriInfo, final PositionDocument request) {
    final PositionDocument result = getPositionMaster().add(request);
    final URI createdUri = new DataPositionResource().uriVersion(uriInfo.getBaseUri(), result.getUniqueId());
    return responseCreatedObject(createdUri, result);
  }

  //-------------------------------------------------------------------------
  @Path("positions/{positionId}")
  public DataPositionResource findPosition(@PathParam("positionId") final String idStr) {
    final ObjectId id = ObjectId.parse(idStr);
    return new DataPositionResource(this, id);
  }

  @Path("trades/{tradeId}")
  public DataTradeResource findTrade(@PathParam("tradeId") final String idStr) {
    final ObjectId id = ObjectId.parse(idStr);
    return new DataTradeResource(this, id);
  }

}


text:
class TransactionalMemory
{
private:
    int*  memory;
    Rec** ownerships;
    Rec** recs;
    int processCount;

    void initialize(Rec* rec, int** dataSet, int dataSetSize);
    void transaction(Rec* rec, int version, bool isInitiator, int dataSetSize);
    void acquireOwnerships(Rec* rec, int version);
    void agreeOldValues(Rec* rec, int version);
    void updateMemory(Rec* rec, int version, int* newValues);
    void releaseOwnerShips(Rec* rec, int version);

    // LL/SC
    Status ll_status(Status status);
    bool sc_status(Status target, Status status);

    // CalsNewValues
    int* increment(int** oldValues, int dataSetSize);

public:
    TransactionalMemory(int memorySize, int processCount);
    TransactionStatus startTransaction(int** dataSet, int dataSetSize, int recIndex);
    ~TransactionalMemory();
};

#endif // TRANSACTIONAL_MEMORY_H


text:
Using the FileSystem Data Store Programmatically
================================================

Creating a Data Store
---------------------

An instance of a FileSystem data store can be obtained through the normal GeoTools discovery methods, assuming that
the GeoMesa code is on the classpath:

.. code-block:: java

    Map<String, String> parameters = new HashMap<>;
    parameters.put("fs.path", "hdfs://localhost:9000/fs-root/");
    org.geotools.data.DataStore dataStore = org.geotools.data.DataStoreFinder.getDataStore(parameters);

More information on using GeoTools can be found in the `GeoTools user guide <http://docs.geotools.org/stable/userguide/>`_.

.. _fsds_parameters:

FileSystem Data Store Parameters
--------------------------------

The FileSystem data store takes several parameters (required parameters are marked with ``*``):

=============================== ====== ===================================================================================
Parameter                       Type   Description
=============================== ====== ===================================================================================
``fs.path *``                   String The root path to write and read data from (e.g. s3a://mybucket/datastores/testds)
``fs.encoding``                 String The file encoding used when creating a new schema. If not specified here, it must
                                       be configured with ``geomesa.fs.encoding`` in the SimpleFeatureType user data.
                                       Provided implementations are ``parquet`` and ``orc``.
``fs.read-threads``             Int    The number of threads used for queries
``fs.writer.partition.timeout`` String Timeout for closing a partition file after write, e.g. '60 seconds'. This is to
                                       prevent too many open files during large write operations.
``fs.config.paths``             String Additional Hadoop configuration resource files (comma-delimited)
``fs.config.xml``               String Additional Hadoop configuration properties, as a standard XML ``<configuration>``
                                       element
=============================== ====== ===================================================================================


text:
using namespace std;

string::size_type									// see below for info
stringLengthSum(string::size_type sumSoFar,			// on string::size_type
					const string& s)
{
	return sumSoFar + s.size();
}

struct Point {
	Point(double initX, double initY): x(initX), y(initY) {}
	double x, y;
};

class PointAverage:
	public unary_function<Point, void> {			// see Item 40
public:
	PointAverage(): xSum(0), ySum(0), numPoints(0) {}

	void operator()(const Point& p)
	{
		++numPoints;
		xSum += p.x;
		ySum += p.y;
	}

	Point result() const
	{ return Point(xSum/numPoints, ySum/numPoints); }

private:
	size_t numPoints;
	double xSum;
	double ySum;
};

int main()
{
	using namespace std;
	using namespace ESTLUtils;

	string s1("this is a");
	string s2("test of the");
	string s3("emergency broadcast system");

	set<string> ss;						// create container of strings,
										// and populate it

	ss.insert(s1);
	ss.insert(s2);
	ss.insert(s3);

	string::size_type lengthSum =				// set lengthSum to the result
		accumulate(ss.begin(), ss.end(),		// of calling stringLengthSum on
		   string::size_type(0),
		   stringLengthSum);					// each element in ss, using 0
												// as the initial summary value

	cout << "Total of sizes = " << lengthSum << endl;

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

	vector<float> vf;					// create container of floats
										// and populate it

	vf.push_back(.5);
	vf.push_back(1);
	vf.push_back(.5);

	float product =							// set product to the result of
		accumulate(vf.begin(), vf.end(),	// calling times<float> on each
		1.0, multiplies<float>());			// element in vf, using 1 as the
											// initial summary value

	cout << "product of .5 , 1 and .5 = " << product << endl;

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

	list<Point> lp;
	lp.push_back(Point(1.1,2.2));
	lp.push_back(Point(2.2,4.4));
	lp.push_back(Point(4.4,8.8));

	Point avg =	 for_each(lp.begin(), lp.end(), PointAverage()).result();

	cout << "Point avg = (" << avg.x << "," << avg.y << ")" << endl;
	return 0;
}


text:
package com.adria.stage.mytest.belmahi.repository;

import com.adria.stage.mytest.belmahi.model.VirementMultipleBeneficiare;

public interface IVirementMultipleBeneficiaireDao {
	public void addVirementMulitipleBeneficiaire(VirementMultipleBeneficiare virementMultipleBeneficiare);
	public VirementMultipleBeneficiare getVirementMultipleBeneficiaire(Long idVirementMultipleBeneficiaire);
}


text:
package org.cloudfoundry.client.v3.applications;

import org.cloudfoundry.Nullable;
import org.cloudfoundry.client.v3.FilterParameter;
import org.cloudfoundry.client.v3.PaginatedRequest;
import org.immutables.value.Value;

import java.util.List;

/**
 * The request payload for the List Applications operation
 */
@Value.Immutable
abstract class _ListApplicationsRequest extends PaginatedRequest {

    /**
     * The ids
     */
    @FilterParameter("guids")
    abstract List<String> getApplicationIds();

    /**
     * The metadata query
     */
    @FilterParameter("label_selector")
    @Nullable
    abstract String getLabelSelector();

    /**
     * The names
     */
    @FilterParameter("names")
    abstract List<String> getNames();

    /**
     * The organization ids
     */
    @FilterParameter("organization_guids")
    abstract List<String> getOrganizationIds();

    /**
     * The space ids
     */
    @FilterParameter("space_guids")
    abstract List<String> getSpaceIds();

}


text:
<?php

$languageStrings = array(
	'LBL_ADD_RECORD' => 'Nueva Configuración',
	'SMSNotifier' => 'Configuración Proveedor SMS',
	'LBL_ADD_CONFIGURATION' => 'Nueva Configuración',
	'LBL_EDIT_CONFIGURATION' => 'Editar Configuración',
	'LBL_SELECT_ONE' => 'Selecciona uno',

	//Fields
	'providertype' => 'Proveedor',
	'isactive' => 'Activo',
	'username' => 'Nombre Usuario',
	'password' => 'Contraseña',
);

$jsLanguageStrings = array(
	'LBL_DELETE_CONFIRMATION' => '¿Estás seguro que quieres eliminar esta configuración de proveedor SMS?',
	'JS_RECORD_DELETED_SUCCESSFULLY' => 'Se ha eliminado la configuración del proveedor SMS',
	'JS_CONFIGURATION_SAVED' => 'Se ha guardado la configuración del proveedor SMS',
);


text:
Caretaker is responsible for merging PRs into the individual branches and internally at Google.

## Responsibilities

- Draining the queue of PRs ready to be merged. (PRs with [`action: merge`](https://github.com/angular/angular/pulls?q=is%3Aopen+is%3Apr+label%3A%22action%3A+merge%22) label)
- Assigning [new issues](https://github.com/angular/angular/issues?q=is%3Aopen+is%3Aissue+no%3Alabel) to individual component authors.

## Merging the PR

A PR needs to have `action: merge` and `target: *` labels to be considered
ready to merge. Merging is performed by running `ng-dev pr merge` with a PR number to merge.

The tooling automatically verifies the given PR is ready for merge. If the PR passes the tests, the
tool will automatically merge it based on the applied target label.

To merge a PR run:

```
$ yarn ng-dev pr merge <pr number>
```

### Recovering from failed `merge-pr` due to conflicts

The `ng-dev pr merge` tool will automatically restore to the previous git state when a merge fails.


text:
require "livereload_rails"
require "rails/engine"
require "rails/commands/server"
require "rack-livereload"

module LivereloadRails
  class Railtie < ::Rails::Engine
    config.app_middleware.insert_before "Rack::Lock", LivereloadRails::Middleware, assets: config.assets
    config.app_middleware.use Rack::LiveReload, live_reload_port: ::Rails::Server.new.options[:Port]
  end
end


text:
@charset "UTF-8";
/*mailbox custom*/
.app-mailbox .identity {
  white-space: nowrap;
}

.app-mailbox .page-content-actions .btn-group {
  margin-left: 8px;
}

.app-mailbox .page-content-actions .btn-pure.btn-default {
  color: #a3afb7;
}

.app-mailbox .page-content-actions .btn-pure.btn-default.active, .app-mailbox .page-content-actions .btn-pure.btn-default:focus, .app-mailbox .page-content-actions .btn-pure.btn-default:hover {
  color: #76838f;
}

.app-mailbox .checkbox-important {
  margin-bottom: 4px;
  padding: 9px 0 0 14px;
  position: relative;
}

.app-mailbox .checkbox-important input[type="checkbox"] {
  cursor: pointer;
  left: 3px;
  margin: -2px 0 0;
  opacity: 0;
  position: absolute;
  top: 50%;
  z-index: 2;
}

.app-mailbox .checkbox-important input[type="checkbox"]:checked + label:before {
  background-color: transparent;
  color: #f2a654;
}

.app-mailbox .checkbox-important label {
  cursor: pointer;
  line-height: 1.2;
  margin-bottom: 0;
  text-align: left;
  font-weight: normal;
}

.app-mailbox .checkbox-important label:before {
  color: #e4eaec;
  content: "";
  display: inline-block;
  font-family: "Web Icons";
  font-size: 16px;
  height: 16px;
  left: 4px;
  line-height: 1;
  margin-top: -4px;
  position: absolute;
  top: 50%;
  width: 16px;
  font-weight: bold;
}

.app-mailbox .table {
  table-layout: fixed;
  border-collapse: collapse;
}

.app-mailbox .table td {
  vertical-align: middle;
}

.app-mailbox .table .avatar {
  margin-left: 10px;
}

.app-mailbox .table .content > * {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.app-mailbox .table .title {
  color: #526069;
}

.app-mailbox .table .time {
  color: #a3afb7;
}

.app-mailbox .table .identity .icon {
  margin-right: 8px;
}

.app-mailbox .table .unread > td:first-child {
  border-left: 1px solid #62a8ea;
}

.app-mailbox .slidePanel-header {
  background-color: #57c7d4;
}

.app-mailbox .slidePanel-header::after {
  content: "";
  display: table;
  clear: both;
}

.app-mailbox .slidePanel .actions-top {
  position: absolute;
  top: 30px;
  right: 20px;
}

.app-mailbox .slidePanel .actions-bottom {
  position: absolute;
  bottom: 30px;
  right: 20px;
}

.app-mailbox .slidePanel .mail-header {
  position: relative;
  padding-left: 50px;
  margin-bottom: 20px;
}

.app-mailbox .slidePanel .mail-header::after {
  content: "";
  display: table;
  clear: both;
}

.app-mailbox .slidePanel .mail-header-main {
  display: inline-block;
}

.app-mailbox .slidePanel .mail-header-right {
  float: right;
}

.app-mailbox .slidePanel .mail-header .time {
  color: #a3afb7;
}

.app-mailbox .slidePanel .mail-header .avatar {
  position: absolute;
  top: 0;
  left: 0;
}

.app-mailbox .slidePanel .mail-header .identity .icon {
  margin-left: 10px;
  margin-right: 6px;
}

.app-mailbox .slidePanel .mail-content p {
  margin-bottom: 20px;
}

.app-mailbox .slidePanel .mail-content p:last-child {
  margin-bottom: 0;
}

.app-mailbox .slidePanel .mail-content + .mail-attachments {
  margin-top: 40px;
}

.app-mailbox .slidePanel .mail-attachments {
  margin-bottom: 20px;
}

.app-mailbox .slidePanel .mail-attachments .wb-paperclip {
  margin-right: 10px;
}

.app-mailbox .slidePanel .mail-attachments .list-group-item {
  padding: 0;
}

.app-mailbox .select2-container {
  z-index: 1700;
}

@media (max-width: 767px) {
  .app-mailbox .responsive-hide {
    display: none;
  }
}

@media (max-width: 479px) {
  .app-mailbox .page-header .page-header-actions {
    margin-top: 20px;
    position: relative;
    top: 0;
    right: 0;
    -webkit-transform: none;
    -ms-transform: none;
    -o-transform: none;
    transform: none;
  }
  .app-mailbox .page-content-actions .actions-right {
    float: none;
    display: block;
  }
}


text:
#ifndef TENSORFLOW_TSL_PROFILER_CONVERT_POST_PROCESS_SINGLE_HOST_XPLANE_H_
#define TENSORFLOW_TSL_PROFILER_CONVERT_POST_PROCESS_SINGLE_HOST_XPLANE_H_

#include "tsl/platform/types.h"
#include "tsl/profiler/protobuf/xplane.pb.h"

namespace tsl {
namespace profiler {

// Post process XSpaces collected locally from multiple profilers.
void PostProcessSingleHostXSpace(tensorflow::profiler::XSpace* space,
                                 uint64 start_time_ns);

}  // namespace profiler
}  // namespace tsl

#endif  // TENSORFLOW_TSL_PROFILER_CONVERT_POST_PROCESS_SINGLE_HOST_XPLANE_H_


text:
package jeliot.calltree;

/**
 * @author Niko Myller
 */
public class TreeBuilder {

    /**
     * Comment for nodeNumber
     */
    protected int nodeNumber = 0;

    /**
     * Comment for tree
     */
    protected Tree tree;

    /**
     * Comment for currentPosition
     */
    protected TreeNode currentPosition = null;

    /**
     * Builds a random tree.  The build method does the work.
     * @return
     */
    public Tree buildTree() {
        // Create a random binary tree with n external nodes
        nodeNumber = 0;
        tree = new Tree();
        currentPosition = new Node();
        tree.setRoot(currentPosition);
        return tree;
    }

    /**
     * @param node
     * @return
     */
    public boolean insertNode(String node) {
        if (nodeNumber == 0) {
            currentPosition = tree.getRoot();
            currentPosition.setProperty("element", node);
            currentPosition.setProperty("current", new Boolean(true));
        } else {
            if (currentPosition == null) { return false; }

            TreeNode pos = new Node();
            pos.setProperty("element", node);
            currentPosition.addChild(pos);
            currentPosition.destroyProperty("current");
            pos.setProperty("current", new Boolean(true));
            currentPosition = pos;
        }
        nodeNumber++;
        return true;
    }

    /**
     *
     * @param returnValue
     * @return
     */
    public boolean returnNode(String returnValue) {
        if (nodeNumber == 0 || currentPosition == null) {
            return false;
        }

        if (currentPosition == null) {
            return false;
        }

        if (currentPosition.isRoot()) {
            currentPosition.destroyProperty("current");
            currentPosition.setProperty("return", returnValue);
            currentPosition = null;
        } else {
            TreeNode pos = currentPosition.getParent();
            currentPosition.destroyProperty("current");
            currentPosition.setProperty("return", returnValue);
            pos.setProperty("current", new Boolean(true));
            currentPosition = pos;
        }

        return true;
    }
}


text:
import * as React from "react";
import { FunctionComponent, useState } from "react";
import { ConfirmCurrentPassword } from "./ConfirmCurrentPassword";
import {
  ChangePasswordDialog,
  ChangePasswordFormValues,
} from "./ChangePassword";
import { FormikHelpers } from "formik/dist/types";
import { usePrompt } from "../Prompt/PromptDisplayBoundary";
import { usePasswordPolicy } from "./usePasswordPolicy";
import { useStroomApi } from "lib/useStroomApi";
import { ChangePasswordRequest, ChangePasswordResponse } from "api/stroom";
import { PromptType } from "../Prompt/Prompt";

export interface FormValues {
  userId: string;
  password: string;
}

const ChangePasswordManager: FunctionComponent<{
  userId: string;
  onClose: () => void;
}> = (props) => {
  const [state, setState] = useState({
    userId: undefined,
    currentPassword: undefined,
  });

  const passwordPolicyConfig = usePasswordPolicy();
  const { showPrompt } = usePrompt();
  const { exec } = useStroomApi();

  if (!state || !state.currentPassword) {
    const onClose = (userId: string, password: string) => {
      if (userId == null && password == null) {
        props.onClose();
      } else {
        setState({ userId, currentPassword: password });
      }
    };
    return <ConfirmCurrentPassword userId={props.userId} onClose={onClose} />;
  } else {
    const onSubmit = (
      values: ChangePasswordFormValues,
      actions: FormikHelpers<ChangePasswordFormValues>,
    ) => {
      const request: ChangePasswordRequest = {
        userId: values.userId,
        currentPassword: state.currentPassword,
        newPassword: values.password,
        confirmNewPassword: values.confirmPassword,
      };

      exec(
        (api) => api.authentication.changePassword(request),
        (response: ChangePasswordResponse) => {
          if (!response) {
            actions.setSubmitting(false);
          } else if (response.changeSucceeded) {
            showPrompt({
              promptProps: {
                type: PromptType.INFO,
                title: "Success",
                message: "Your password has been changed",
              },
              onCloseDialog: () => props.onClose(),
            });
          } else {
            actions.setSubmitting(false);
            showPrompt({
              promptProps: {
                type: PromptType.ERROR,
                title: "Error",
                message: response.message,
              },
              onCloseDialog: () => {
                // If the user is asked to sign in again then unset the auth state.
                if (response.forceSignIn) {
                  props.onClose();
                }
              },
            });
          }
        },
      );
    };

    const onClose = () => {
      props.onClose();
    };

    return (
      <ChangePasswordDialog
        initialValues={{
          userId: state.userId,
          password: "",
          confirmPassword: "",
        }}
        passwordPolicyConfig={passwordPolicyConfig}
        onSubmit={onSubmit}
        onClose={onClose}
        {...props}
      />
    );
  }
};

export default ChangePasswordManager;


text:
import { StoreModule, combineReducers } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';

import { Reducers } from './reducers';
import { AuthEffects } from './effects/auth';

const combinedReducers = combineReducers(Reducers);

export function reducer(state: any, action: any) {
  return combinedReducers(state, action);
}

let modules = [
  StoreModule.provideStore(reducer),
  EffectsModule.run(AuthEffects)
];

if (localStorage.getItem('debug') === "true") {
  modules.push(StoreDevtoolsModule.instrumentOnlyWithExtension())
}

export const STORE = modules;


text:
table.clsWorksheetDetail {
	border-collapse:collapse;
	font-size:12pt;
}

table.clsWorksheetDetail th {
	font-weight:bold;
	text-align:center;
	border:solid 1px black;
	padding:3x;
}

table.clsWorksheetDetail td {
	border:solid 1px black;
	padding:3x;
}

/* clsWorksheetProduct */

table.clsWorksheetProduct {
	border-collapse:collapse;
	font-size:12pt;
	border:solid 1px black;
}

table.clsWorksheetProduct thead {
	display:table-header-group;
}

table.clsWorksheetProduct tr {
	height:18pt;
}

table.clsWorksheetProduct th {
	font-weight:bold;
	text-align:center;
	border:solid 1px black;
	padding:3x;
}

table.clsWorksheetProduct tbody td {
	border-left:solid 1px #aaaaaa;
	border-right:solid 1px #aaaaaa;
	border-bottom:solid 1px #aaaaaa;
	padding:3x;
}


text:
module.exports = function(){
  var express = require('express');
  var app = express();
  var mongoskin = require('mongoskin');

  var db = mongoskin.db('mongodb://@localhost:27017/techdb', {safe:true})

app.get('/api/customers/:sort_by/:order/:from?/:to?', function(req, res, next) {

  // check if logged in
  var token = req.headers['x-token'];
  var tokens = db.collection('tokens');

  tokens.findOne({"token":token}, function(err, result) {
    if (err) throw err;
    console.log(result['token']);

    if (token==result['token']){
      // Authenticated
      function showCustomers(err, result) {
        if (err) throw err;
        for (i = 0; i < result.length; i++) {
          delete result[i]["_id"];
        }
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify(result));
      }
      var order_d = {'A':1, 'D':-1};
      var customers = db.collection('customers');
      var sortBy = req.params.sort_by;
      var order = order_d[req.params.order];
      if (req.params.from && req.params.to) {
        var firstValue = parseInt(req.params.from);
        var lim = parseInt(req.params.to) - firstValue + 1;
        customers.find({},{sort:[[sortBy, order]]}).limit(lim).skip(firstValue).toArray(showCustomers);
      }
      else{
        customers.find({},{sort:[[sortBy, order]]}).toArray(showCustomers);
      }

    }
    else{
      res.statusCode = 403;
      res.send('403 error');
    }

  });

})

  return app;
}();


text:
from WeatherServer import db

class Province(db.Document):

    location_id = db.StringField(verbose_name='location_id',
                                 max_length=20,
                                 required=True,
                                 primary_key=True,
                                 unique=True)

    name = db.StringField(verbose_name='省份',
                          max_length=30,
                          required=True)

    cities = db.ListField(db.ReferenceField('City'))

    def __unicode__(self):
        return '<省份:%s (%s)>' % (self.name, self.location_id)

class City(db.Document):

    location_id = db.StringField(verbose_name='location_id',
                                 max_length=20,
                                 required=True,
                                 primary_key=True,
                                 unique=True)

    name = db.StringField(verbose_name='省份',
                          max_length=30,
                          required=True)

    countries = db.ListField(db.ReferenceField('Country'))

    def __unicode__(self):
        return '<城市:%s (%s)>' % (self.name, self.location_id)

class Country(db.Document):

    location_id = db.StringField(verbose_name='location_id',
                                 max_length=20,
                                 required=True,
                                 primary_key=True,
                                 unique=True)

    weather_id = db.StringField(verbose_name='weather_id',
                                max_length=80,
                                required=True,
                                unique=True)

    name = db.StringField(verbose_name='中文名',
                          max_length=30,
                          required=True)

    weather_infos = db.EmbeddedDocumentListField('WeatherInfo')

    def __unicode__(self):
        return '<名称:%s id-%s weather-id-%s>' % \
            (self.name, self.location_id, self.weather_id)

class RealTimeInfo(db.EmbeddedDocument):

    humidity = db.StringField(verbose_name='湿度',
                              max_length=10)

    wind_direction = db.StringField(verbose_name='风向',
                                    max_length=10)

    wind_speed = db.StringField(verbose_name='风力',
                                max_length=10)

    temp = db.StringField(verbose_name='温度',
                          max_length=10)

    time = db.DateTimeField(verbose_name='当前时间')

    weather = db.StringField(verbose_name='天气')

    def __unicode__(self):
        return '%s:%s' % (self.time.hour, self.time.minute)

class TodayInfo(db.EmbeddedDocument):

    humidity_max = db.IntField(verbose_name='最高湿度')
    humidity_min = db.IntField(verbose_name='最低湿度')

    temp_max = db.IntField(verbose_name='最高温度')
    temp_min = db.IntField(verbose_name='最低温度')

    weather_start = db.StringField(verbose_name='开始天气',
                                   max_length=30)
    weather_end = db.StringField(verbose_name='结束天气',
                                 max_length=30)

    wind_direction_start = db.StringField(verbose_name='开始风向',
                                          max_length=30)
    wind_direction_end = db.StringField(verbose_name='结束风向',
                                        max_length=30)

    wind_max = db.IntField(verbose_name='最大风力')
    wind_min = db.IntField(verbose_name='最小风力')

class AqiInfo(db.EmbeddedDocument):

    pub_date = db.DateTimeField(verbose_name='更新日期')

    aqi = db.StringField(verbose_name='空气质量',
                         max_length=20)

    pm25 = db.StringField(verbose_name='pm2.5',
                          max_length=20)

    pm10 = db.StringField(verbose_name='pm10',
                          max_length=20)

    so2 = db.StringField(verbose_name='so2',
                         max_length=20)

    no2 = db.StringField(verbose_name='no2',
                         max_length=20)

    source = db.StringField(verbose_name='来源',
                            max_length=50)

    spot = db.StringField(verbose_name='地点',
                          max_length=50)

    def __unicode__(self):
        return '更新时间: %s:%s 空气质量: %s' % \
            (self.pub_date.hour, self.pub_date.minute, self.aqi)

class IndexInfo(db.EmbeddedDocument):

    code = db.StringField(verbose_name='code',
                          max_length=10)

    details = db.StringField(verbose_name='细节',
                             max_length=300)

    index = db.StringField(verbose_name='指数',
                           max_length=20)

    name = db.StringField(verbose_name='name',
                          max_length=20)

    def __unicode__(self):
        return '%s: %s' % (self.name, self.index)

class Forecast(db.EmbeddedDocument):

    wind = db.StringField(verbose_name='风力',
                          max_length=10)

    wind_detail = db.StringField(verbose_name='风力细节',
                                 max_length=20)

    temp = db.StringField(verbose_name='温度',
                          max_length=20)

    weather = db.StringField(verbose_name='天气描述',
                             max_length=20)

    week = db.StringField(verbose_name='星期几')

    def __unicode__(self):
        return '%s %s' % (self.week, self.weather)

class WeatherInfo(db.EmbeddedDocument):

    datetime = db.DateTimeField(verbose_name='datetime',
                                required=True,
                                unique=True)

    week = db.StringField(verbose_name='星期几')

    today = db.EmbeddedDocumentField('TodayInfo',
                                     verbose_name='今天天气')

    realtime = db.EmbeddedDocumentField('RealTimeInfo',
                                        verbose_name='实时天气')

    aqi = db.EmbeddedDocumentField('AqiInfo',
                                   verbose_name='空气指数')

    index = db.EmbeddedDocumentListField('IndexInfo',
                                         verbose_name='指数信息')

    forecast = db.EmbeddedDocumentListField('Forecast',
                                            verbose_name='预报信息')

    def __unicode__(self):
        date = self.datetime
        return '%s-%s-%s' % (date.year, date.month,
                             date.day)

class WeatherHistoryInfo(db.EmbeddedDocument):

    date = db.StringField(required=True,
                          unique=True,
                          max_length=30,
                          verbose_name='日期')

    datetime = db.DateTimeField(required=True)

    temp_min = db.StringField(verbose_name='最低气温',
                              max_length=30)

    temp_max = db.StringField(verbose_name='最高气温',
                              max_length=30)

    weather = db.StringField(verbose_name='天气描述',
                             max_length=50)

    wind_direction = db.StringField(verbose_name='风向',
                                    max_length=30)

    wind_speed = db.StringField(verbose_name='风力',
                                max_length=30)

    def __unicode__(self):
        return '<%s>' % self.date

class WeatherHistory(db.Document):

    country = db.StringField(required=True,
                             unique=True,
                             max_length=20)

    history_infos = db.EmbeddedDocumentListField('WeatherHistoryInfo',
                                                 verbose_name='历史天气')

    def __unicode__(self):
        return '<%s>' % self.country


text:
env | grep npm | sort | egrep 'dependency|bundle'
echo NODE_PATH=$NODE_PATH


text:
module.exports = function (name, prefix) {
    return [
        `src/components/${prefix || ''}${name}/${name}-component-controller.js`,
        `src/components/${prefix || ''}${name}/${name}-component.js`,
        `src/components/${prefix || ''}${name}/${name}-component.scss`,
        `src/components/${prefix || ''}${name}/${name}-component.html`,
        `src/components/${prefix || ''}${name}/${name}-component-spec.js`,
        `src/components/${prefix || ''}${name}/${name}-component-test.js`,
        `src/components/${prefix || ''}${name}/index.js`
    ];
};


text:
package de.bht.mmi.iot.service;

import de.bht.mmi.iot.exception.EntityNotFoundException;
import de.bht.mmi.iot.exception.NotAuthorizedException;
import de.bht.mmi.iot.model.Gateway;
import de.bht.mmi.iot.model.Sensor;
import de.bht.mmi.iot.model.User;
import de.bht.mmi.iot.repository.GatewayRepository;
import de.bht.mmi.iot.repository.SensorRepository;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import static de.bht.mmi.iot.constants.RoleConstants.*;

@Service
public class GatewayServiceImpl implements GatewayService {

    @Autowired
    private GatewayRepository gatewayRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private SensorService sensorService;

    @Autowired
    private SensorRepository sensorRepository;

    @Override
    public Iterable<Gateway> getAll() {
        return gatewayRepository.findAll();
    }

    @Override
    public Iterable<Gateway> getAll(UserDetails authenticatedUser) throws EntityNotFoundException {
        final String username = authenticatedUser.getUsername();
        if (userService.isAnyRolePresent(authenticatedUser, ROLE_ADMIN, ROLE_GET_ALL_GATEWAY)) {
            return getAll();
        } else {
            final Set<Gateway> result = new HashSet<>();
            CollectionUtils.addAll(result, getAllByOwner(username));
            CollectionUtils.addAll(result, getAllReleasedForUser(username));
            return result;
        }
    }

    @Override
    public Iterable<Gateway> getAllReleasedForUser(String username) throws EntityNotFoundException {
        final User user = userService.loadUserByUsername(username);
        final Iterable<Gateway> userGateways = gatewayRepository.findAll(user.getReleasedForGateways());
        return userGateways != null ? userGateways : Collections.emptyList();
    }

    @Override
    public Iterable<Gateway> getAllForIds(String... gatewayId) {
        return gatewayRepository.findAll(Arrays.asList(gatewayId));
    }

    @Override
    public Iterable<Gateway> getAllByOwner(String username) throws EntityNotFoundException {
        userService.loadUserByUsername(username);
        return gatewayRepository.findAllByOwner(username);
    }

    @Override
    public Iterable<Gateway> getAllByOwner(String username, UserDetails authenticatedUser) throws EntityNotFoundException, NotAuthorizedException {
        userService.loadUserByUsername(username);
        if (userService.isAnyRolePresent(authenticatedUser, ROLE_ADMIN, ROLE_GET_ALL_GATEWAY)
                || username.equals(authenticatedUser.getUsername())) {
            return getAllByOwner(username);
        }
        throw new NotAuthorizedException(
                String.format("You are not authorized to get all gateways for owner '%s'", username));
    }

    @Override
    public Gateway getOne(String gatewayId) throws EntityNotFoundException {
        Gateway gateway = gatewayRepository.findOne(gatewayId);
        if (gateway != null) {
            return gateway;
        } else {
            throw new EntityNotFoundException(String.format("Gateway with id '%s' not found", gatewayId));
        }
    }

    @Override
    public Gateway save(Gateway gateway) throws EntityNotFoundException {
        userService.loadUserByUsername(gateway.getOwner());
        return gatewayRepository.save(gateway);
    }

    @Override
    public Gateway save(Gateway gateway, UserDetails authenticatedUser)
            throws EntityNotFoundException, NotAuthorizedException {

        Gateway oldGateway = null;
        if (gateway.getId() != null) {
            oldGateway = gatewayRepository.findOne(gateway.getId());
        }

        if (oldGateway == null) {
            if (userService.isAnyRolePresent(authenticatedUser, ROLE_ADMIN, ROLE_CREATE_GATEWAY)) {
                return save(gateway);
            }
        } else {
            if (userService.isAnyRolePresent(authenticatedUser, ROLE_ADMIN, ROLE_UPDATE_GATEWAY)
                    || oldGateway.getOwner().equals(authenticatedUser.getUsername())) {
                return save(gateway);
            }
        }
        throw new NotAuthorizedException("You are not authorized to save/update gateways");
    }

    @Override
    public void delete(String gatewayId) throws EntityNotFoundException {
        getOne(gatewayId);
        final Iterable<Sensor> sensorsAttachedToGateway = sensorService.getAllByGatewayId(gatewayId);
        for (Sensor sensor : sensorsAttachedToGateway) {
            sensor.setAttachedGateway(null);
            sensorService.save(sensor);
        }
        sensorRepository.save(sensorsAttachedToGateway);
        gatewayRepository.delete(gatewayId);
    }

    @Override
    public void delete(String gatewayId, UserDetails authenticatedUser) throws EntityNotFoundException,
            NotAuthorizedException {
        final Gateway gateway = getOne(gatewayId);
        if (userService.isAnyRolePresent(authenticatedUser, ROLE_ADMIN, ROLE_DELETE_GATEWAY)
                || gateway.getOwner().equals(authenticatedUser.getUsername())) {
            delete(gatewayId);
            return;
        }
        throw new NotAuthorizedException(
                String.format("You are not authorized to delete gateway with id '%s'", gatewayId));
    }

}


text:
package com.intellij.xml.arrangement;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Eugene.Kudelevsky
 */
public class XmlArrangementParseInfo {

  private final List<XmlElementArrangementEntry> myEntries = new ArrayList<>();

  @NotNull
  public List<XmlElementArrangementEntry> getEntries() {
    return myEntries;
  }

  public void addEntry(@NotNull XmlElementArrangementEntry entry) {
    myEntries.add(entry);
  }
}


text:
#include "e_ofono_private.h"

/**
 * Get property "Mode" value.
 *
 * If this property isn't found then 0 is returned.
 * If zero is returned, then this call failed and parameter-returned
 * values shall be considered invalid.
 *
 * @param mode where to store the property value, must be a pointer
 *        to string (const char **), it will not be allocated or
 *        copied and references will be valid until element changes,
 *        so copy it if you want to use it later.
 *
 * @return @c EINA_TRUE on success, @c EINA_FALSE otherwise.
 */
Eina_Bool
e_ofono_netreg_mode_get(const E_Ofono_Element *element, const char **mode)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(element, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(mode, EINA_FALSE);

   return e_ofono_element_property_get_stringshared
             (element, e_ofono_prop_mode, NULL, mode);
}

/**
 * Get property "Status" value.
 *
 * If this property isn't found then 0 is returned.
 * If zero is returned, then this call failed and parameter-returned
 * values shall be considered invalid.
 *
 * @param status where to store the property value, must be a pointer
 *        to string (const char **), it will not be allocated or
 *        copied and references will be valid until element changes,
 *        so copy it if you want to use it later.
 *
 * @return @c EINA_TRUE on success, @c EINA_FALSE otherwise.
 */
Eina_Bool
e_ofono_netreg_status_get(const E_Ofono_Element *element, const char **status)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(element, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(status, EINA_FALSE);

   return e_ofono_element_property_get_stringshared
             (element, e_ofono_prop_status, NULL, status);
}

/**
 * Get property "Operator" value.
 *
 * If this property isn't found then 0 is returned.
 * If zero is returned, then this call failed and parameter-returned
 * values shall be considered invalid.
 *
 * @param operator where to store the property value, must be a pointer
 *        to string (const char **), it will not be allocated or
 *        copied and references will be valid until element changes,
 *        so copy it if you want to use it later.
 *
 * @return @c EINA_TRUE on success, @c EINA_FALSE otherwise.
 */
Eina_Bool
e_ofono_netreg_operator_get(const E_Ofono_Element *element, const char **op)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(element, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(op, EINA_FALSE);

   return e_ofono_element_property_get_stringshared
             (element, e_ofono_prop_operator, NULL, op);
}

/**
 * Get property "Strength" value.
 *
 * @param strength where to store the property value, must be a pointer
 *        to char (char *), it will not be allocated or
 *        copied and references will be valid until element changes,
 *        so copy it if you want to use it later.
 *
 * @return @c EINA_TRUE on success, @c EINA_FALSE otherwise.
 */
Eina_Bool
e_ofono_netreg_strength_get(const E_Ofono_Element *element, uint8_t *strength)
{
   EINA_SAFETY_ON_NULL_RETURN_VAL(element, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(strength, EINA_FALSE);

   return e_ofono_element_property_get_stringshared
             (element, e_ofono_prop_strength, NULL, strength);
}


text:
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef __itkVTKImageIO_h
#define __itkVTKImageIO_h
#include "ITKIOVTKExport.h"

#include <fstream>
#include "itkStreamingImageIOBase.h"

namespace itk
{
/** \class VTKImageIO
 *
 *  \brief ImageIO class for reading VTK images
 *
 * This implementation was taken fron the Insight Joural:
 * http://hdl.handle.net/10380/3171
 *
 * \ingroup IOFilters
 *
 * \ingroup ITKIOVTK
 */
class ITKIOVTK_EXPORT VTKImageIO:
  public StreamingImageIOBase
{
public:
  /** Standard class typedefs. */
  typedef VTKImageIO                 Self;
  typedef StreamingImageIOBase       Superclass;
  typedef SmartPointer< Self >       Pointer;
  typedef SmartPointer< const Self > ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(VTKImageIO, StreamingImageIOBase);

// see super class for documentation
  //
  // overidden to return true only when supported
  virtual bool CanStreamWrite(void);

  // see super class for documentation
  //
  // overidden to return true only when supported
  virtual bool CanStreamRead(void);

  /*-------- This part of the interface deals with reading data. ------ */

  /** Determine the file type. Returns true if this ImageIO can read the
   * file specified. */
  virtual bool CanReadFile(const char *);

  /** Set the spacing and dimesion information for the current filename. */
  virtual void ReadImageInformation();

  /** Reads the data from disk into the memory buffer provided. */
  virtual void Read(void *buffer);

  /*-------- This part of the interfaces deals with writing data. ----- */

  /** Determine the file type. Returns true if this ImageIO can read the
   * file specified. */
  virtual bool CanWriteFile(const char *);

  /** Writes the spacing and dimensions of the image.
   * Assumes SetFileName has been called with a valid file name. */
  virtual void WriteImageInformation() {}

  /** Writes the data to disk from the memory buffer provided. Make sure
   * that the IORegion has been set properly. */
  virtual void Write(const void *buffer);

  /** returns the header size, if it is unknown it will return 0 */
  virtual SizeType GetHeaderSize() const { return this->m_HeaderSize; }

protected:
  VTKImageIO();
  ~VTKImageIO();

  void PrintSelf(std::ostream & os, Indent indent) const;

  void InternalReadImageInformation(std::ifstream & file);

  void WriteImageInformation(const void *buffer);

  void ReadHeaderSize(std::ifstream & file);

  /** Convenient method to read a buffer as ASCII text. */
  virtual void ReadBufferAsASCII(std::istream & os, void *buffer,
                         IOComponentType ctype,
                         SizeType numberOfBytesToBeRead);

  /** Convenient method to write a buffer as ASCII text. */
  virtual void WriteBufferAsASCII(std::ostream & os, const void *buffer,
                          IOComponentType ctype,
                          SizeType numberOfBytesToWrite);

  /** We have a special method to read symmetric second rank tensors because
   * the VTK file format expands the symmetry and only supports 3D tensors. */
  virtual void ReadSymmetricTensorBufferAsBinary(std::istream& os,
    void *buffer,
    StreamingImageIOBase::SizeType num);

  /** We have a special method to write symmetric second rank tensors because
   * the VTK file format expands the symmetry and only supports 3D tensors. */
  virtual void WriteSymmetricTensorBufferAsBinary(std::ostream& os,
    const void *buffer,
    StreamingImageIOBase::SizeType num);

private:
  VTKImageIO(const Self &);    //purposely not implemented
  void operator=(const Self &); //purposely not implemented
  void SetPixelTypeFromString(const std::string & pixelType);

  SizeType m_HeaderSize;
};
} // end namespace itk

#endif // __itkVTKImageIO_h


text:
package com.example.android.foldinglayout;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Shader.TileMode;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * The folding layout where the number of folds, the anchor point and the
 * orientation of the fold can be specified. Each of these parameters can
 * be modified individually and updates and resets the fold to a default
 * (unfolded) state. The fold factor varies between 0 (completely unfolded
 * flat image) to 1.0 (completely folded, non-visible image).
 *
 * This layout throws an exception if there is more than one child added to the view.
 * For more complicated view hierarchy's inside the folding layout, the views should all
 * be nested inside 1 parent layout.
 *
 * This layout folds the contents of its child in real time. By applying matrix
 * transformations when drawing to canvas, the contents of the child may change as
 * the fold takes place. It is important to note that there are jagged edges about
 * the perimeter of the layout as a result of applying transformations to a rectangle.
 * This can be avoided by having the child of this layout wrap its content inside a
 * 1 pixel transparent border. This will cause an anti-aliasing like effect and smoothen
 * out the edges.
 *
 */
public class FoldingLayout extends ViewGroup {

    public static enum Orientation {
        VERTICAL,
        HORIZONTAL
    }

    private final String FOLDING_VIEW_EXCEPTION_MESSAGE = "Folding Layout can only 1 child at " +
            "most";

    private final float SHADING_ALPHA = 0.8f;
    private final float SHADING_FACTOR = 0.5f;
    private final int DEPTH_CONSTANT = 1500;
    private final int NUM_OF_POLY_POINTS = 8;

    private Rect[] mFoldRectArray;

    private Matrix[] mMatrix;

    private Orientation mOrientation = Orientation.HORIZONTAL;

    private float mAnchorFactor = 0;
    private float mFoldFactor = 0;

    private int mNumberOfFolds = 2;

    private boolean mIsHorizontal = true;

    private int mOriginalWidth = 0;
    private int mOriginalHeight = 0;

    private float mFoldMaxWidth = 0;
    private float mFoldMaxHeight = 0;
    private float mFoldDrawWidth = 0;
    private float mFoldDrawHeight = 0;

    private boolean mIsFoldPrepared = false;
    private boolean mShouldDraw = true;

    private Paint mSolidShadow;
    private Paint mGradientShadow;
    private LinearGradient mShadowLinearGradient;
    private Matrix mShadowGradientMatrix;

    private float[] mSrc;
    private float[] mDst;

    private OnFoldListener mFoldListener;

    private float mPreviousFoldFactor = 0;

    private Bitmap mFullBitmap;
    private Rect mDstRect;

    public FoldingLayout(Context context) {
        super(context);
    }

    public FoldingLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FoldingLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected boolean addViewInLayout(View child, int index, LayoutParams params,
                                      boolean preventRequestLayout) {
        throwCustomException(getChildCount());
        boolean returnValue = super.addViewInLayout(child, index, params, preventRequestLayout);
        return returnValue;
    }

    @Override
    public void addView(View child, int index, LayoutParams params) {
        throwCustomException(getChildCount());
        super.addView(child, index, params);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        View child = getChildAt(0);
        measureChild(child,widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        View child = getChildAt(0);
        child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
        updateFold();
    }

    /**
     * The custom exception to be thrown so as to limit the number of views in this
     * layout to at most one.
     */
    private class NumberOfFoldingLayoutChildrenException extends RuntimeException {
        public NumberOfFoldingLayoutChildrenException(String message) {
            super(message);
        }
    }

    /** Throws an exception if the number of views added to this layout exceeds one.*/
    private void throwCustomException (int numOfChildViews) {
        if (numOfChildViews == 1) {
            throw new NumberOfFoldingLayoutChildrenException(FOLDING_VIEW_EXCEPTION_MESSAGE);
        }
    }

    public void setFoldListener(OnFoldListener foldListener) {
        mFoldListener = foldListener;
    }

    /**
     * Sets the fold factor of the folding view and updates all the corresponding
     * matrices and values to account for the new fold factor. Once that is complete,
     * it redraws itself with the new fold. */
    public void setFoldFactor(float foldFactor) {
        if (foldFactor != mFoldFactor) {
            mFoldFactor = foldFactor;
            calculateMatrices();
            invalidate();
        }
    }

    public void setOrientation(Orientation orientation) {
        if (orientation != mOrientation) {
            mOrientation = orientation;
            updateFold();
        }
    }

    public void setAnchorFactor(float anchorFactor) {
        if (anchorFactor != mAnchorFactor) {
            mAnchorFactor = anchorFactor;
            updateFold();
        }
    }

    public void setNumberOfFolds(int numberOfFolds) {
        if (numberOfFolds != mNumberOfFolds) {
            mNumberOfFolds = numberOfFolds;
            updateFold();
        }
    }

    public float getAnchorFactor() {
        return mAnchorFactor;
    }

    public Orientation getOrientation() {
        return mOrientation;
    }

    public float getFoldFactor() {
        return mFoldFactor;
    }

    public int getNumberOfFolds() {
        return mNumberOfFolds;
    }

    private void updateFold() {
        prepareFold(mOrientation, mAnchorFactor, mNumberOfFolds);
        calculateMatrices();
        invalidate();
    }

    /**
     * This method is called in order to update the fold's orientation, anchor
     * point and number of folds. This creates the necessary setup in order to
     * prepare the layout for a fold with the specified parameters. Some of the
     * dimensions required for the folding transformation are also acquired here.
     *
     * After this method is called, it will be in a completely unfolded state by default.
     */
    private void prepareFold(Orientation orientation, float anchorFactor, int numberOfFolds) {

        mSrc = new float[NUM_OF_POLY_POINTS];
        mDst = new float[NUM_OF_POLY_POINTS];

        mDstRect = new Rect();

        mFoldFactor = 0;
        mPreviousFoldFactor = 0;

        mIsFoldPrepared = false;

        mSolidShadow = new Paint();
        mGradientShadow = new Paint();

        mOrientation = orientation;
        mIsHorizontal = (orientation == Orientation.HORIZONTAL);

        if (mIsHorizontal) {
            mShadowLinearGradient = new LinearGradient(0, 0, SHADING_FACTOR, 0, Color.BLACK,
                    Color.TRANSPARENT, TileMode.CLAMP);
        } else {
            mShadowLinearGradient = new LinearGradient(0, 0, 0, SHADING_FACTOR, Color.BLACK,
                    Color.TRANSPARENT, TileMode.CLAMP);
        }

        mGradientShadow.setStyle(Style.FILL);
        mGradientShadow.setShader(mShadowLinearGradient);
        mShadowGradientMatrix = new Matrix();

        mAnchorFactor = anchorFactor;
        mNumberOfFolds = numberOfFolds;

        mOriginalWidth = getMeasuredWidth();
        mOriginalHeight = getMeasuredHeight();

        mFoldRectArray = new Rect[mNumberOfFolds];
        mMatrix = new Matrix [mNumberOfFolds];

        for (int x = 0; x < mNumberOfFolds; x++) {
            mMatrix[x] = new Matrix();
        }

        int h = mOriginalHeight;
        int w = mOriginalWidth;

        if (FoldingLayoutActivity.IS_JBMR2) {
            mFullBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(mFullBitmap);
            getChildAt(0).draw(canvas);
        }

        int delta = Math.round(mIsHorizontal ? ((float) w) / ((float) mNumberOfFolds) :
                ((float) h) /((float) mNumberOfFolds));

        /* Loops through the number of folds and segments the full layout into a number
         * of smaller equal components. If the number of folds is odd, then one of the
         * components will be smaller than all the rest. Note that deltap below handles
         * the calculation for an odd number of folds.*/
        for (int x = 0; x < mNumberOfFolds; x++) {
            if (mIsHorizontal) {
                int deltap = (x + 1) * delta > w ? w - x * delta : delta;
                mFoldRectArray[x] = new Rect(x * delta, 0, x * delta + deltap, h);
            } else {
                int deltap = (x + 1) * delta > h ? h - x * delta : delta;
                mFoldRectArray[x] = new Rect(0, x * delta, w, x * delta + deltap);
            }
        }

        if (mIsHorizontal) {
            mFoldMaxHeight = h;
            mFoldMaxWidth = delta;
        } else {
            mFoldMaxHeight = delta;
            mFoldMaxWidth = w;
        }

        mIsFoldPrepared = true;
    }

    /*
    * Calculates the transformation matrices used to draw each of the separate folding
    * segments from this view.
    */
    private void calculateMatrices() {

        mShouldDraw = true;

        if (!mIsFoldPrepared) {
            return;
        }

        /** If the fold factor is 1 than the folding view should not be seen
         * and the canvas can be left completely empty. */
        if (mFoldFactor == 1) {
            mShouldDraw = false;
            return;
        }

        if (mFoldFactor == 0 &&  mPreviousFoldFactor > 0) {
            mFoldListener.onEndFold();
        }

        if (mPreviousFoldFactor == 0 && mFoldFactor > 0) {
            mFoldListener.onStartFold();
        }

        mPreviousFoldFactor = mFoldFactor;

        /* Reset all the transformation matrices back to identity before computing
         * the new transformation */
        for (int x = 0; x < mNumberOfFolds; x++) {
            mMatrix[x].reset();
        }

        float cTranslationFactor = 1 - mFoldFactor;

        float translatedDistance = mIsHorizontal ? mOriginalWidth * cTranslationFactor :
                mOriginalHeight * cTranslationFactor;

        float translatedDistancePerFold = Math.round(translatedDistance / mNumberOfFolds);

        /* For an odd number of folds, the rounding error may cause the
         * translatedDistancePerFold to be grater than the max fold width or height. */
        mFoldDrawWidth = mFoldMaxWidth < translatedDistancePerFold ?
                translatedDistancePerFold : mFoldMaxWidth;
        mFoldDrawHeight = mFoldMaxHeight < translatedDistancePerFold ?
                translatedDistancePerFold : mFoldMaxHeight;

        float translatedDistanceFoldSquared = translatedDistancePerFold * translatedDistancePerFold;

        /* Calculate the depth of the fold into the screen using pythagorean theorem. */
        float depth = mIsHorizontal ?
                (float)Math.sqrt((double)(mFoldDrawWidth * mFoldDrawWidth -
                        translatedDistanceFoldSquared)) :
                (float)Math.sqrt((double)(mFoldDrawHeight * mFoldDrawHeight -
                        translatedDistanceFoldSquared));

        /* The size of some object is always inversely proportional to the distance
        *  it is away from the viewpoint. The constant can be varied to to affect the
        *  amount of perspective. */
        float scaleFactor = DEPTH_CONSTANT / (DEPTH_CONSTANT + depth);

        float scaledWidth, scaledHeight, bottomScaledPoint, topScaledPoint, rightScaledPoint,
                leftScaledPoint;

        if (mIsHorizontal) {
            scaledWidth = mFoldDrawWidth * cTranslationFactor;
            scaledHeight = mFoldDrawHeight * scaleFactor;
        } else {
            scaledWidth = mFoldDrawWidth * scaleFactor;
            scaledHeight = mFoldDrawHeight * cTranslationFactor;
        }

        topScaledPoint = (mFoldDrawHeight - scaledHeight) / 2.0f;
        bottomScaledPoint = topScaledPoint + scaledHeight;

        leftScaledPoint = (mFoldDrawWidth - scaledWidth) / 2.0f;
        rightScaledPoint = leftScaledPoint + scaledWidth;

        float anchorPoint = mIsHorizontal ? mAnchorFactor * mOriginalWidth :
                mAnchorFactor * mOriginalHeight;

        /* The fold along which the anchor point is located. */
        float midFold = mIsHorizontal ? (anchorPoint / mFoldDrawWidth) : anchorPoint /
                mFoldDrawHeight;

        mSrc[0] = 0;
        mSrc[1] = 0;
        mSrc[2] = 0;
        mSrc[3] = mFoldDrawHeight;
        mSrc[4] = mFoldDrawWidth;
        mSrc[5] = 0;
        mSrc[6] = mFoldDrawWidth;
        mSrc[7] = mFoldDrawHeight;

        /* Computes the transformation matrix for each fold using the values calculated above. */
        for (int x = 0; x < mNumberOfFolds; x++) {

            boolean isEven = (x % 2 == 0);

            if (mIsHorizontal) {
                mDst[0] = (anchorPoint > x * mFoldDrawWidth) ? anchorPoint + (x - midFold) *
                        scaledWidth : anchorPoint - (midFold - x) * scaledWidth;
                mDst[1] = isEven ? 0 : topScaledPoint;
                mDst[2] = mDst[0];
                mDst[3] = isEven ? mFoldDrawHeight: bottomScaledPoint;
                mDst[4] = (anchorPoint > (x + 1) * mFoldDrawWidth) ? anchorPoint + (x + 1 - midFold)
                        * scaledWidth : anchorPoint - (midFold - x - 1) * scaledWidth;
                mDst[5] = isEven ? topScaledPoint : 0;
                mDst[6] = mDst[4];
                mDst[7] = isEven ? bottomScaledPoint : mFoldDrawHeight;

            } else {
                mDst[0] = isEven ? 0 : leftScaledPoint;
                mDst[1] = (anchorPoint > x * mFoldDrawHeight) ? anchorPoint + (x - midFold) *
                        scaledHeight : anchorPoint - (midFold - x) * scaledHeight;
                mDst[2] = isEven ? leftScaledPoint: 0;
                mDst[3] = (anchorPoint > (x + 1) * mFoldDrawHeight) ? anchorPoint + (x + 1 -
                        midFold) * scaledHeight : anchorPoint - (midFold - x - 1) * scaledHeight;
                mDst[4] = isEven ? mFoldDrawWidth : rightScaledPoint;
                mDst[5] = mDst[1];
                mDst[6] = isEven ? rightScaledPoint : mFoldDrawWidth;
                mDst[7] = mDst[3];
            }

            /* Pixel fractions are present for odd number of folds which need to be
             * rounded off here.*/
            for (int y = 0; y < 8; y ++) {
                mDst[y] = Math.round(mDst[y]);
            }

            /* If it so happens that any of the folds have reached a point where
            *  the width or height of that fold is 0, then nothing needs to be
            *  drawn onto the canvas because the view is essentially completely
            *  folded.*/
            if (mIsHorizontal) {
                if (mDst[4] <= mDst[0] || mDst[6] <= mDst[2]) {
                    mShouldDraw = false;
                    return;
                }
            } else {
                if (mDst[3] <= mDst[1] || mDst[7] <= mDst[5]) {
                    mShouldDraw = false;
                    return;
                }
            }

            /* Sets the shadow and bitmap transformation matrices.*/
            mMatrix[x].setPolyToPoly(mSrc, 0, mDst, 0, NUM_OF_POLY_POINTS / 2);
        }
        /* The shadows on the folds are split into two parts: Solid shadows and gradients.
         * Every other fold has a solid shadow which overlays the whole fold. Similarly,
         * the folds in between these alternating folds also have an overlaying shadow.
         * However, it is a gradient that takes up part of the fold as opposed to a solid
         * shadow overlaying the whole fold.*/

        /* Solid shadow paint object. */
        int alpha = (int) (mFoldFactor * 255 * SHADING_ALPHA);

        mSolidShadow.setColor(Color.argb(alpha, 0, 0, 0));

        if (mIsHorizontal) {
            mShadowGradientMatrix.setScale(mFoldDrawWidth, 1);
            mShadowLinearGradient.setLocalMatrix(mShadowGradientMatrix);
        } else {
            mShadowGradientMatrix.setScale(1, mFoldDrawHeight);
            mShadowLinearGradient.setLocalMatrix(mShadowGradientMatrix);
        }

        mGradientShadow.setAlpha(alpha);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        /** If prepareFold has not been called or if preparation has not completed yet,
         * then no custom drawing will take place so only need to invoke super's
         * onDraw and return. */
        if (!mIsFoldPrepared || mFoldFactor == 0) {
            super.dispatchDraw(canvas);
            return;
        }

        if (!mShouldDraw) {
            return;
        }

        Rect src;
         /* Draws the bitmaps and shadows on the canvas with the appropriate transformations. */
        for (int x = 0; x < mNumberOfFolds; x++) {

            src = mFoldRectArray[x];
            /* The canvas is saved and restored for every individual fold*/
            canvas.save();

            /* Concatenates the canvas with the transformation matrix for the
             *  the segment of the view corresponding to the actual image being
             *  displayed. */
            canvas.concat(mMatrix[x]);
            if (FoldingLayoutActivity.IS_JBMR2) {
                mDstRect.set(0, 0, src.width(), src.height());
                canvas.drawBitmap(mFullBitmap, src, mDstRect, null);
            } else {
                /* The same transformation matrix is used for both the shadow and the image
                 * segment. The canvas is clipped to account for the size of each fold and
                 * is translated so they are drawn in the right place. The shadow is then drawn on
                 * top of the different folds using the sametransformation matrix.*/
                canvas.clipRect(0, 0, src.right - src.left, src.bottom - src.top);

                if (mIsHorizontal) {
                    canvas.translate(-src.left, 0);
                } else {
                    canvas.translate(0, -src.top);
                }

                super.dispatchDraw(canvas);

                if (mIsHorizontal) {
                    canvas.translate(src.left, 0);
                } else {
                    canvas.translate(0, src.top);
                }
            }
            /* Draws the shadows corresponding to this specific fold. */
            if (x % 2 == 0) {
                canvas.drawRect(0, 0, mFoldDrawWidth, mFoldDrawHeight, mSolidShadow);
            } else {
                canvas.drawRect(0, 0, mFoldDrawWidth, mFoldDrawHeight, mGradientShadow);
            }

            canvas.restore();
        }
    }

}