text:
/**
 * Interfaces for consuming state and returning results.
 */
package io.dazraf.vertx.function;


text:
extern "Java"
{
  namespace gnu
  {
    namespace java
    {
      namespace nio
      {
        namespace charset
        {
            class EncodingHelper;
        }
      }
    }
  }
  namespace java
  {
    namespace nio
    {
      namespace charset
      {
          class Charset;
      }
    }
  }
}

class gnu::java::nio::charset::EncodingHelper : public ::java::lang::Object
{

public:
  EncodingHelper();
  static ::java::lang::String * getDefaultEncoding();
  static ::java::lang::String * getOldCanonical(::java::lang::String *);
  static jboolean isISOLatin1(::java::lang::String *);
  static ::java::nio::charset::Charset * getCharset(::java::lang::String *);
  static ::java::nio::charset::Charset * getDefaultCharset();
private:
  static ::java::util::HashMap * canonicalNames;
public:
  static ::java::lang::Class class$;
};

#endif // __gnu_java_nio_charset_EncodingHelper__

redpajama_set_name: RedPajamaGithub


text: Pensionfund::Application.config.session_store :cookie_store, key: '_pensionfund_session'


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.ensignprojects.dockeradmin;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import nl.ensignprojects.dockeradmin.container.ContainerFX;
import javafx.fxml.FXML;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import nl.ensignprojects.dockeradmin.container.Container;
import nl.ensignprojects.dockeradmin.rest.DockerEndpointQuery;

/**
 * Controller - Glue between businessrules and the view
 * @author jurrian
 */
public class FXMLContainerController {
    @FXML
    private TableView<ContainerFX> tableContainers;

    @FXML
    private TableColumn<ContainerFX, Boolean> check;

    @FXML
    private TableColumn<ContainerFX, String> name;

    @FXML
    private TableColumn<ContainerFX, String> nameImage;

    @FXML
    private TableColumn<ContainerFX, String> state;

    @FXML
    private void startContainerAction() {
        this.containerAction(c -> DockerEndpointQuery.startContainer(c.getContainer()));
    }

    @FXML
    private void stopContainerAction() {
        this.containerAction(c -> DockerEndpointQuery.stopContainer(c.getContainer()));
    }

    @FXML
    private void removeContainerAction() {
        this.containerAction(c -> DockerEndpointQuery.removeContainer(c.getContainer()));
    }

    private void containerAction(Consumer<ContainerFX> action) {
        tableContainers.getItems()
                .filtered(c -> c.getCheck())
                .forEach(action);
        this.deSelectAllAction();
        tableContainers.setItems(parseInitContainers());
    }

    @FXML
    private void selectAllAction() {
        tableContainers.getItems().forEach(c -> c.setCheck(Boolean.TRUE));
    }

    @FXML
    private void deSelectAllAction() {
        tableContainers.getItems().forEach(c -> c.setCheck(Boolean.FALSE));
    }

    @FXML
    private void invertSelection() {
        tableContainers.getItems().forEach(c -> c.setCheck(!c.getCheck()));
    }

    @FXML
    private void initialize() {
        check.setCellFactory(CheckBoxTableCell.forTableColumn(check));
        check.setCellValueFactory(c -> c.getValue().checkProperty());

        name.setCellValueFactory(new PropertyValueFactory<ContainerFX, String>("name"));
        nameImage.setCellValueFactory(new PropertyValueFactory<ContainerFX, String>("nameImage"));
        state.setCellValueFactory(new PropertyValueFactory<ContainerFX, String>("state"));

        tableContainers.setItems(parseInitContainers());

    }

    private ObservableList<ContainerFX> parseInitContainers(){
        // parse and construct User datamodel list by looping your ResultSet rs
        // and return the list
        List<Container> containerList = DockerEndpointQuery.getAllContainers();
        List<ContainerFX> containerFXList = new ArrayList<>();

        containerList.stream().forEach(c ->
            containerFXList.add(new ContainerFX(c))
        );

        return FXCollections.observableArrayList(containerFXList);
    }

}


text:
import dateLocale from 'date-fns/locale/es';
const resources = {
  AdvancedInputControls: {
    'Clear Field': 'Borrar campo'
  },
  AvatarButton: {
    'Profile Picture': 'Imagen de perfil'
  },
  AvatarUser: {
    Avatar: 'Avatar'
  },
  BulkActions: {
    AllPageCountDisplayedSelected: 'Se seleccionaron los {{pageCount}} elementos que se muestran',
    AllTotalCountSelected: 'Se seleccionaron los {{totalCount}} elementos',
    'Bulk Actions': 'Acciones masivas',
    'Clear Selection': 'Borrar selección',
    SelectAllCountResults: 'Seleccionar los {{totalCount}} resultados',
    SelectedCountOfTotalDisplayed: 'Se seleccionaron {{selectedItemCount}} de los {{pageCount}} elementos que se muestran'
  },
  CalendarNav: {
    'next month': 'mes siguiente',
    'previous month': 'mes anterior'
  },
  CheckMarkMixed: {
    'Check Mark Mixed': 'Marca de verificación combinada'
  },
  Chip: {
    Delete: 'Eliminar'
  },
  ColumnSelector: {
    Apply: 'Aplicar',
    Cancel: 'Cancelar',
    'Select All': 'Seleccionar todo',
    'Select None': 'No seleccionar nada',
    'Select columns to display': 'Seleccionar columnas para mostrar'
  },
  ConfirmationDialog: {
    Cancel: 'Cancelar',
    Confirm: 'Confirmar'
  },
  CopyToClipboard: {
    Copied: 'Copiado',
    'Copy to Clipboard': 'Copiar en el portapapeles'
  },
  DataTable: {
    'No Results': 'No hay resultados'
  },
  DataTableItem: {
    Options: 'Opciones'
  },
  FieldTimeSelect: {
    'Please enter a valid time': 'Escriba una hora válida.'
  },
  GetIntentLabel: {
    Error: 'Error',
    Inform: 'Informe',
    Success: 'Correcto',
    Warning: 'Advertencia'
  },
  InputDate: {
    'Open calendar': 'Abrir calendario'
  },
  InputDateRange: {
    'End date': 'Fecha final',
    'Start date': 'Fecha inicial'
  },
  InputFilters: {
    'Clear Filters': 'Borrar filtros',
    'Filter List': 'Lista de filtros',
    'bottom-start': 'abajo-inicio'
  },
  InputTimeSelect: {
    'Select time': 'Seleccionar hora'
  },
  MessageBar: {
    DismissIntent: 'Descartar {{intent}}'
  },
  ModalHeaderCloseButton: {
    Close: 'Cerrar'
  },
  MonthPickerNav: {
    close: 'cerrar',
    'next year': 'año siguiente',
    'previous year': 'año anterior'
  },
  PageSize: {
    Display: 'Mostrar',
    of: 'de'
  },
  Pagination: {
    'First page of results': 'Primera página de resultados',
    'Last page of results': 'Última página de resultados',
    'Next page of results': 'Página siguiente de resultados',
    'Previous page of results': 'Página anterior de resultados',
    of: 'de'
  },
  PanelHeader: {
    CloseTitle: 'Cerrar {{title}}'
  },
  PopoverFooter: {
    Done: 'Listo'
  },
  PromptDialog: {
    Cancel: 'Cancelar',
    Save: 'Guardar'
  },
  RangeSlider: {
    'Maximum Value': 'Valor máximo',
    'Minimum Value': 'Valor mínimo'
  },
  RequiredStar: {
    required: 'obligatorio'
  },
  SelectOptions: {
    Loading: 'Cargando',
    'No options': 'Sin opciones'
  },
  TabList: {
    Tabs: 'Pestañas'
  }
};
export const esES = {
  dateLocale,
  locale: 'es-ES',
  resources: {
    'es-ES': resources
  }
};
//# sourceMappingURL=es-ES.js.map


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>zebra.layout.Layout</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

Zebra API Doc

APIs

Classes

Packages

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

zebra.data.Item

zebra.data.ListModel

zebra.data.Matrix

zebra.data.SingleLineTxt

zebra.data.Text

zebra.data.TextModel

zebra.data.TreeModel

zebra.Dummy

zebra.io.HTTP

zebra.io.JRPC

zebra.io.QS

zebra.io.Service

zebra.io.XRPC

zebra.layout.BorderLayout

zebra.layout.Constraints

zebra.layout.FlowLayout

zebra.layout.GridLayout

zebra.layout.Layout

zebra.layout.Layoutable

zebra.layout.ListLayout

zebra.layout.PercentLayout

zebra.layout.RasterLayout

zebra.layout.StackLayout

zebra.ui.BaseLayer

zebra.ui.BaseList

zebra.ui.BoldLabel

zebra.ui.Border

zebra.ui.BorderPan

zebra.ui.Button

zebra.ui.Checkbox

zebra.ui.Checkbox.Box

zebra.ui.Combo

zebra.ui.Combo.ComboPadPan

zebra.ui.Combo.ContentPan

zebra.ui.Combo.EditableContentPan

zebra.ui.Combo.ReadonlyContentPan

zebra.ui.ComboArrowView

zebra.ui.CommandManager

zebra.ui.CompList

zebra.ui.CompositeEvStatePan

zebra.ui.CompositeView

zebra.ui.CompRender

zebra.ui.CursorManager

zebra.ui.designer.ShaperPan

zebra.ui.Dotted

zebra.ui.Etched

zebra.ui.EventManager

zebra.ui.EvStatePan

zebra.ui.ExtendablePan

zebra.ui.FocusManager

zebra.ui.Font

zebra.ui.Gradient

zebra.ui.grid.BaseCaption

zebra.ui.grid.CompGridCaption

zebra.ui.grid.CompGridCaption.TitlePan

zebra.ui.grid.DefEditors

zebra.ui.grid.DefViews

zebra.ui.grid.Grid

zebra.ui.grid.GridCaption

zebra.ui.grid.GridStretchPan

zebra.ui.grid.Metrics

zebra.ui.Group

zebra.ui.HtmlElement

zebra.ui.HtmlTextArea

zebra.ui.HtmlTextField

zebra.ui.HtmlTextInput

zebra.ui.ImageLabel

zebra.ui.ImagePan

zebra.ui.InputEvent

zebra.ui.KeyEvent

zebra.ui.Label

zebra.ui.Line

zebra.ui.Link

zebra.ui.List

zebra.ui.List.ViewProvider

zebra.ui.Manager

zebra.ui.Menu

zebra.ui.Menubar

zebra.ui.MenuItem

zebra.ui.MLabel

zebra.ui.MobileScrollMan

zebra.ui.MouseEvent

zebra.ui.MouseWheelSupport

zebra.ui.PaintManager

zebra.ui.PaintManImpl

zebra.ui.Panel

zebra.ui.PassTextField

zebra.ui.PasswordText

zebra.ui.Pattern

zebra.ui.Picture

zebra.ui.PopupLayer

zebra.ui.PopupManager

zebra.ui.Progress

zebra.ui.Radial

zebra.ui.Radiobox

zebra.ui.RadioView

zebra.ui.Raised

zebra.ui.Render

zebra.ui.RootLayer

zebra.ui.RoundBorder

zebra.ui.Scroll

zebra.ui.ScrollManager

zebra.ui.ScrollPan

zebra.ui.Slider

zebra.ui.SplitPan

zebra.ui.StatePan

zebra.ui.StatusBar

zebra.ui.StringRender

zebra.ui.Sunken

zebra.ui.SwitchManager

zebra.ui.Tabs

zebra.ui.Tabs.TabView

zebra.ui.TextArea

zebra.ui.TextField

zebra.ui.TextRender

zebra.ui.TitledBorder

zebra.ui.Toolbar

zebra.ui.Tooltip

zebra.ui.tree.$IM

zebra.ui.tree.BaseTree

zebra.ui.tree.CompTree

zebra.ui.tree.DefEditors

zebra.ui.tree.DefViews

zebra.ui.tree.Tree

zebra.ui.tree.TreeSignView

zebra.ui.VideoPan

zebra.ui.View

zebra.ui.ViewPan

zebra.ui.ViewSet

zebra.ui.Window

zebra.ui.WinLayer

zebra.ui.zCanvas

zebra.URL

zebra.util.Bag

zebra.util.Listeners

zebra.util.Position

zebra.util.Position.Metric

zebra.util.rgb

zebra.util.TaskCotext

data

io

layout

ui

ui.designer

ui.grid

ui.tree

util

zebra

zebra.layout.Layout Class

Layout manager interface

            Index

Methods

Item Index

Methods

                                calcPreferredSize

                                doLayout

                                getDirectAt

                                getDirectChild

                                getMaxPreferredSize

                                getTopParent

                                toChildOrigin

                                toParentOrigin

Methods

calcPreferredSize

            (

                        t

)

Calculate preferred size of the given component

Parameters:

                        t
                        zebra.layout.Layoutable

a target layoutable component

doLayout

            (

                        t

)

Layout children components of the specified layoutable target component

Parameters:

                        t
                        zebra.layout.Layoutable

a target layoutable component

getDirectAt

            (

                        x

                        y

                        parent

)

            zebra.layout.Layoutable

Find a direct component located at the given location of the specified
parent component and the specified parent component

Parameters:

                        x
                        Integer

a x coordinate relatively to the parent component

                        y
                        Integer

a y coordinate relatively to the parent component

                        parent
                        zebra.layout.Layoutable

a parent component

                        Return: zebra.layout.Layoutable

an index of direct children component
or -1 if no a children component can be found

getDirectChild

            (

                        parent

                        child

)

            zebra.layout.Layoutable

Find a direct children element for the given children component
and the specified parent component

Parameters:

                        parent
                        zebra.layout.Layoutable

a parent component

                        child
                        zebra.layout.Layoutable

a children component

                        Return: zebra.layout.Layoutable

a direct children component

getMaxPreferredSize

            (

                        target

)

            Object

Calculate maximal preferred width and height of
children component of the given target component.

Parameters:

                        target
                        zebra.layout.Layoutable

a target component

                        Return: Object

a maximal preferred width and height

   { width:{Integer}, height:{Integer} }

getTopParent

            (

                        c

)

            zebra.layout.Layoutable

Get a top (the highest in component hierarchy) parent component
of the given component

Parameters:

                        c
                        zebra.layout.Layoutable

a component

                        Return: zebra.layout.Layoutable

a top parent component

toChildOrigin

            (

                        x

                        y

                        p

                        c

)

            Object

Convert the given component location into relative
location of the specified children component successor.

Parameters:

                        x
                        Integer

a x coordinate relatively to the given
component

                        y
                        Integer

a y coordinate relatively to the given
component

                        p
                        zebra.layout.Layoutable

a component

                        c
                        zebra.layout.Layoutable

a children successor component

                        Return: Object

a relative location

 { x:{Integer}, y:{Integer} }

toParentOrigin

            (

                        [x]

                        [y]

                        c

                        [p]

)

            Object

Translate the given relative location into the parent relative location.

Parameters:

                        [x]
                        Integer
                        optional

a x coordinate relatively  to the given component

                        [y]
                        Integer
                        optional

a y coordinate relatively  to the given component

                        c
                        zebra.layout.Layoutable

a component

                        [p]
                        zebra.layout.Layoutable
                        optional

a parent component

                        Return: Object

a relative to the given parent UI component location:

   { x:{Integer}, y:{Integer} }


text:
package org.apache.flex.forks.batik.bridge;

/**
 * Defines a viewport for a <tt>UserAgent</tt>.
 *
 * @author Thierry Kormann
 * @version $Id: UserAgentViewport.java 475477 2006-11-15 22:44:28Z cam $
 */
public class UserAgentViewport implements Viewport {

    private UserAgent userAgent;

    /**
     * Constructs a new viewport for the specified user agent.
     * @param userAgent the user agent that defines the viewport
     */
    public UserAgentViewport(UserAgent userAgent) {
        this.userAgent = userAgent;
    }

    /**
     * Returns the width of this viewport.
     */
    public float getWidth() {
        return (float) userAgent.getViewportSize().getWidth();
    }

    /**
     * Returns the height of this viewport.
     */
    public float getHeight() {
        return (float) userAgent.getViewportSize().getHeight();
    }
}


text:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace MLocati.ServicesControl
{
    public partial class frmProgramOutputViewer : Form
    {
        private readonly ProgramOutput Output;

        public frmProgramOutputViewer(ProgramOutput output)
        {
            InitializeComponent();
            this.Icon = Program.Icon;
            this.Output = output;
            this.rtbOutput.SuspendLayout();
            foreach (var chunk in this.Output.Chunks)
            {
                this.ViewChunk(chunk, false);
            }
            this.rtbOutput.ResumeLayout();
            this.Output.Cleared += this.Output_Cleared;
            this.Output.ChunkAdded += Output_ChunkAdded;
        }

        private void Output_ChunkAdded(object sender, ProgramOutput.ChunkAddedEventArgs e)
        {
            if (this.rtbOutput.InvokeRequired)
            {
                this.rtbOutput.Invoke((MethodInvoker)delegate
                {
                    this.ViewChunk(e.Chunk, true);
                });
            }
            else
            {
                this.ViewChunk(e.Chunk, true);
            }
        }

        private void Output_Cleared(object sender, EventArgs e)
        {
            if (this.rtbOutput.InvokeRequired)
            {
                this.rtbOutput.Invoke((MethodInvoker)delegate
               {
                   this.rtbOutput.Clear();
               });
            }
            else
            {
                this.rtbOutput.Clear();
            }
        }

        private void ViewChunk(ProgramOutput.Chunk chunk, bool suspendLayout)
        {
            if (suspendLayout)
            {
                this.rtbOutput.SuspendLayout();
            }
            var oldStart = this.rtbOutput.SelectionStart;
            var oldLength = this.rtbOutput.SelectionLength;
            this.rtbOutput.SelectionStart = this.rtbOutput.TextLength;
            this.rtbOutput.SelectionLength = 0;
            this.rtbOutput.SelectionColor = chunk.Type == ProgramOutput.Type.StdErr ? Color.Red : this.rtbOutput.ForeColor;
            this.rtbOutput.AppendText(chunk.Text);
            this.rtbOutput.SelectionColor = this.rtbOutput.ForeColor;
            this.rtbOutput.AppendText(Environment.NewLine);
            this.rtbOutput.SelectionStart = oldStart;
            this.rtbOutput.SelectionLength = oldLength;
            if (suspendLayout)
            {
                this.rtbOutput.ResumeLayout();
            }
        }

        private void frmProgramOutputViewer_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Output.Cleared -= this.Output_Cleared;
            this.Output.ChunkAdded -= this.Output_ChunkAdded;
        }
    }
}


text:
apps.ngdemos.start.controller(
	'SimpleController2',
	['$scope',function ($scope) {

		$scope.customers = [
			{ name: 'Dave Jones',	city: 'Phoenix' },
			{ name: 'Jamie Riley',	city: 'Atlanta' },
			{ name: 'Heedy Wahlin',	city: 'Chandler' },
			{ name: 'Thomas Winter',	city: 'Seattle' }
		];

		$scope.addCustomer = function () {
			$scope.customers.push(
				{ name: $scope.inputData.name, city: $scope.inputData.city }
			);
		}
	}]
);


text:
codeId: code-checkout-subscription
---
```c#
using Paymentwall;

Paymentwall_Base.setApiType(Paymentwall_Base.API_GOODS);
Paymentwall_Base.setAppKey("YOUR_PROJECT_KEY");
Paymentwall_Base.setSecretKey("YOUR_SECRET_KEY");

List<Paymentwall_Product> productList = new List<Paymentwall_Product>();
Paymentwall_Product product = new Paymentwall_Product(
    "product301", // ag_external_id
    9.99, // amount
    "USD", // currencyCode
    "Gold Membership", // ag_name
    Paymentwall_Product.TYPE_SUBSCRIPTION, // ag_type
    1, // ag_period_length
    Paymentwall_Product.PERIOD_TYPE_YEAR, // ag_period_type
    true // ag_recurring
);
productList.Add(product);
Paymentwall_Widget widget = new Paymentwall_Widget(
    "user40012",
    "pw_1",
    productList,
    new Dictionary<string, string>() {
        {
            'email' => 'user@hostname.com',
            'timestamp' => 'transaction_current_timestamp',
            'ps' => 'all', // Replace it with specific payment system short code for single payment methods
            'additional_param_name' => 'additional_param_value'
        }
    }
);
Response.Write(widget.getUrl());
```


text:
#import "AutoScalingExecutePolicyRequestMarshaller.h"

@implementation AutoScalingExecutePolicyRequestMarshaller

+(AmazonServiceRequest *)createRequest:(AutoScalingExecutePolicyRequest *)executePolicyRequest
{
    AmazonServiceRequest *request = [[AutoScalingRequest alloc] init];

    [request setParameterValue:@"ExecutePolicy"           forKey:@"Action"];
    [request setParameterValue:@"2011-01-01"   forKey:@"Version"];

    [request setDelegate:[executePolicyRequest delegate]];
    [request setCredentials:[executePolicyRequest credentials]];
    [request setEndpoint:[executePolicyRequest requestEndpoint]];
    [request setRequestTag:[executePolicyRequest requestTag]];

    if (executePolicyRequest != nil) {
        if (executePolicyRequest.autoScalingGroupName != nil) {
            [request setParameterValue:[NSString stringWithFormat:@"%@", executePolicyRequest.autoScalingGroupName] forKey:[NSString stringWithFormat:@"%@", @"AutoScalingGroupName"]];
        }
    }
    if (executePolicyRequest != nil) {
        if (executePolicyRequest.policyName != nil) {
            [request setParameterValue:[NSString stringWithFormat:@"%@", executePolicyRequest.policyName] forKey:[NSString stringWithFormat:@"%@", @"PolicyName"]];
        }
    }
    if (executePolicyRequest != nil) {
        if (executePolicyRequest.honorCooldownIsSet) {
            [request setParameterValue:(executePolicyRequest.honorCooldown ? @"true":@"false") forKey:[NSString stringWithFormat:@"%@", @"HonorCooldown"]];
        }
    }

    return [request autorelease];
}

@end


text:
/**
 * Created by Andrew Rapo on 12/27/15.
 */
"use strict";

class MimState {
    constructor() {
        this.tries = 0;
        this.noInputCount = 0;
        this.noMatchCount = 0;
        this.lastResultState = '';
        this.success = false;
        this.failure = false;
        this.promptText = '';

    }

    get done() {
        return (this.success || this.failure);
    }

    incrementTries() {
        this.tries++;
    }

    incrementNoInputCount() {
        this.noInputCount++
    }

    incrementNoMatchCount() {
        this.noMatchCount++
    }

    toHtml() {
        let html = '
MimState:
';

        html += `promptText: <strong>${this.promptText}</strong></br>`;
        html += `try (#): ${this.tries}</br>`;
        html += `noInputCount: ${this.noInputCount}</br>`;
        html += `noMatchCount: ${this.noMatchCount}</br>`;
        html += `lastResultState: ${this.lastResultState}</br>`;
        html += `success: ${this.success}</br>`;
        html += `failure: ${this.failure}</br>`;
        html += `done: ${this.done}</br>`;

        html += '
';

        return html;
    }
}

module.exports = MimState;


text:
<?php
/**
 * Prevent the file accessed directly
 */
if ( ! defined( 'ABSPATH' ) ) die( 'Cheating, uh?' );

class VcsExtension_Widget extends WP_Widget {
	/**
	 * Register widget
	 */
	public function __construct() {
		parent::__construct(
	 		VCSEXTENSION_PLUGIN_SLUG . '_widget',
			'Sebar',
			array( 'description' => __( 'Display awesome related contents.', VCSEXTENSION_PLUGIN_SLUG ), )
		);
	}

	/**
	 * Front-end display of widget.
	 *
	 * @see WP_Widget::widget()
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {
		extract( $args );
		$id = (int)$instance['viral'];
		if ( !empty( $id ) ) {
			global $wpdb;
			$tableViral = $wpdb->prefix . 'viralcs_virals';

			$viral = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $tableViral WHERE id = %d", $id ) );
			if ( !empty( $viral ) ) {
				if ( !class_exists( 'VcsShortcode' ) ) {
					include_once( VIRALCONTENTSLIDER_PLUGIN_DIR . 'codes/shortcodes/shortcode.php' );
				}
				$shortcode = new VcsShortcode( $viral, 'wdg' );
				echo $shortcode->generate();
			}
		}
	}

	/**
	 * Back-end widget form.
	 *
	 * @see WP_Widget::form()
	 *
	 * @param array $instance Previously saved values from database.
	 */
	public function form( $instance ) {
		$wViral = '';
		if ( isset( $instance['viral'] ) ) {
			$wViral = (int)$instance['viral'];
		}
		?>
		<p>
			<select id="<?php echo $this->get_field_id( 'viral' ); ?>" name="<?php echo $this->get_field_name( 'viral' ); ?>" class="widefat">
				<?php
					$virals = $this->virals();
					if ( !empty( $virals ) ) {
						foreach ( $virals as $viral ) {
							$selected = '';
							if ( $viral->id == $wViral ) {
								$selected = 'selected="selected"';
							}
							echo '<option value="' . $viral->id . '" ' . $selected . '>' . $viral->name . '</option>';
						}
					}
				?>
			</select>
		</p>
		<?php
	}

	/**
	 * Sanitize widget form values as they are saved.
	 *
	 * @see WP_Widget::update()
	 *
	 * @param array $new_instance Values just sent to be saved.
	 * @param array $old_instance Previously saved values from database.
	 *
	 * @return array Updated safe values to be saved.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['viral'] = ( !empty( $new_instance['viral'] ) ) ? strip_tags( $new_instance['viral'] ) : '';
		return $instance;
	}

	/**
	 * Get virals
	 */
	private function virals() {
		global $wpdb;
		$tableVirals = $wpdb->prefix . 'viralcs_virals';
		$virals = $wpdb->get_results( "SELECT * FROM $tableVirals WHERE deleted_at IS NULL ORDER BY name ASC" );
		return $virals;
	}
}


text:
package org.pma.nutrifami.lib;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;

import org.pma.nutrifami.R;

import java.util.Objects;

/**
 * Created by Peter Juras on 06.06.16.
 */

public class UnitExplanationManager {
    private static UnitExplanationManager mInstance;

    public static UnitExplanationManager getInstance() {
        if (mInstance == null) {
            mInstance = new UnitExplanationManager();
        }
        return mInstance;
    }

    public void showExplanation(Context context, String title, String content, DialogInterface.OnDismissListener callback) {
        final MaterialDialog.Builder builder = new MaterialDialog.Builder(context)
                .title(title)
                .content(content)
                .dismissListener(callback)
                .positiveText(R.string.explanation_positive_text);
        if (title.equals(context.getString(R.string.explanation_correct))) {
            builder.titleColorRes(R.color.colorAccent);
        } else {
            builder.titleColorRes(R.color.colorRedSwipe);
        }
        builder.show();
    }
}


text:
package metrics

import (
	"time"

	"k8s.io/component-base/metrics"
	"k8s.io/component-base/metrics/legacyregistry"
	"k8s.io/utils/clock"
)

const (
	namespace = "apiserver"
	subsystem = "egress_dialer"

	// ProtocolHTTPConnect means that the proxy protocol is http-connect.
	ProtocolHTTPConnect = "http_connect"
	// ProtocolGRPC means that the proxy protocol is the GRPC protocol.
	ProtocolGRPC = "grpc"
	// TransportTCP means that the transport is TCP.
	TransportTCP = "tcp"
	// TransportUDS means that the transport is UDS.
	TransportUDS = "uds"
	// StageConnect indicates that the dial failed at establishing connection to the proxy server.
	StageConnect = "connect"
	// StageProxy indicates that the dial failed at requesting the proxy server to proxy.
	StageProxy = "proxy"
)

var (
	// Use buckets ranging from 5 ms to 12.5 seconds.
	latencyBuckets = []float64{0.005, 0.025, 0.1, 0.5, 2.5, 12.5}

	// Metrics provides access to all dial metrics.
	Metrics = newDialMetrics()
)

// DialMetrics instruments dials to proxy server with prometheus metrics.
type DialMetrics struct {
	clock     clock.Clock
	starts    *metrics.CounterVec
	latencies *metrics.HistogramVec
	failures  *metrics.CounterVec
}

// newDialMetrics create a new DialMetrics, configured with default metric names.
func newDialMetrics() *DialMetrics {
	starts := metrics.NewCounterVec(
		&metrics.CounterOpts{
			Namespace:      namespace,
			Subsystem:      subsystem,
			Name:           "dial_start_total",
			Help:           "Dial starts, labeled by the protocol (http-connect or grpc) and transport (tcp or uds).",
			StabilityLevel: metrics.ALPHA,
		},
		[]string{"protocol", "transport"},
	)

	latencies := metrics.NewHistogramVec(
		&metrics.HistogramOpts{
			Namespace:      namespace,
			Subsystem:      subsystem,
			Name:           "dial_duration_seconds",
			Help:           "Dial latency histogram in seconds, labeled by the protocol (http-connect or grpc), transport (tcp or uds)",
			Buckets:        latencyBuckets,
			StabilityLevel: metrics.ALPHA,
		},
		[]string{"protocol", "transport"},
	)

	failures := metrics.NewCounterVec(
		&metrics.CounterOpts{
			Namespace:      namespace,
			Subsystem:      subsystem,
			Name:           "dial_failure_count",
			Help:           "Dial failure count, labeled by the protocol (http-connect or grpc), transport (tcp or uds), and stage (connect or proxy). The stage indicates at which stage the dial failed",
			StabilityLevel: metrics.ALPHA,
		},
		[]string{"protocol", "transport", "stage"},
	)

	legacyregistry.MustRegister(starts)
	legacyregistry.MustRegister(latencies)
	legacyregistry.MustRegister(failures)
	return &DialMetrics{starts: starts, latencies: latencies, failures: failures, clock: clock.RealClock{}}
}

// Clock returns the clock.
func (m *DialMetrics) Clock() clock.Clock {
	return m.clock
}

// SetClock sets the clock.
func (m *DialMetrics) SetClock(c clock.Clock) {
	m.clock = c
}

// Reset resets the metrics.
func (m *DialMetrics) Reset() {
	m.starts.Reset()
	m.latencies.Reset()
	m.failures.Reset()
}

// ObserveDialStart records the start of a dial attempt, labeled by protocol, transport.
func (m *DialMetrics) ObserveDialStart(protocol, transport string) {
	m.starts.WithLabelValues(protocol, transport).Inc()
}

// ObserveDialLatency records the latency of a dial, labeled by protocol, transport.
func (m *DialMetrics) ObserveDialLatency(elapsed time.Duration, protocol, transport string) {
	m.latencies.WithLabelValues(protocol, transport).Observe(elapsed.Seconds())
}

// ObserveDialFailure records a failed dial, labeled by protocol, transport, and the stage the dial failed at.
func (m *DialMetrics) ObserveDialFailure(protocol, transport, stage string) {
	m.failures.WithLabelValues(protocol, transport, stage).Inc()
}


text:
//
//  UIView+Init.h
//  Zaker-C
//
//  Created by GuangliChan on 16/2/29.
//  Copyright © 2016年 GLChen. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIView (Init)
+ (instancetype)cgl_viewFromXib;
/** 获取view 的view控制器 */
- (UINavigationController *)viewController;
/** 获取view 的nav控制器 */
- (UINavigationController *)navController;
@end


text:
test:
	find test -name test\*.rb | xargs -L 1 ruby

test_archive:
	ruby test/test-archive.rb

.PHONY: test test_archive


text:
package org.apache.camel.component.file.remote;

import java.io.File;

import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Producer;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.converter.IOConverter;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit test to verify that using option setNames and having multi remote directories the files
 * are stored locally in the same directory layout.
 */
public class FromFtpSetNamesWithMultiDirectoriesTest extends FtpServerTestSupport {

    private String getFtpUrl() {
        return "ftp://admin@localhost:" + getPort() + "/incoming?password=admin&binary=true&recursive=true&initialDelay=0&delay=100";
    }

    @Override
    @Before
    public void setUp() throws Exception {
        deleteDirectory("target/ftpsetnamestest");
        super.setUp();
    }

    @Test
    public void testFtpRoute() throws Exception {
        NotifyBuilder notify = new NotifyBuilder(context).whenDone(2).create();
        MockEndpoint resultEndpoint = getMockEndpoint("mock:result");
        resultEndpoint.expectedMessageCount(2);

        prepareFtpServer();

        context.getRouteController().startRoute("foo");

        assertMockEndpointsSatisfied();
        assertTrue(notify.matchesMockWaitTime());

        Exchange ex = resultEndpoint.getExchanges().get(0);
        byte[] bytes = ex.getIn().getBody(byte[].class);
        assertTrue("Logo size wrong", bytes.length > 10000);

        // assert the file
        File file = new File("target/ftpsetnamestest/data1/logo1.jpeg");
        assertTrue("The binary file should exists", file.exists());
        assertTrue("Logo size wrong", file.length() > 10000);

        // assert the file
        file = new File("target/ftpsetnamestest/data2/logo2.png");
        assertTrue(" The binary file should exists", file.exists());
        assertTrue("Logo size wrong", file.length() > 50000);
    }

    private void prepareFtpServer() throws Exception {
        // prepares the FTP Server by creating a file on the server that we want to unit
        // test that we can pool and store as a local file
        String ftpUrl = "ftp://admin@localhost:" + getPort() + "/incoming/data1/?password=admin&binary=true";
        Endpoint endpoint = context.getEndpoint(ftpUrl);
        Exchange exchange = endpoint.createExchange();
        exchange.getIn().setBody(IOConverter.toFile("src/test/data/ftpbinarytest/logo1.jpeg"));
        exchange.getIn().setHeader(Exchange.FILE_NAME, "logo1.jpeg");
        Producer producer = endpoint.createProducer();
        producer.start();
        producer.process(exchange);
        producer.stop();

        ftpUrl = "ftp://admin@localhost:" + getPort() + "/incoming/data2/?password=admin&binary=true";
        endpoint = context.getEndpoint(ftpUrl);
        exchange = endpoint.createExchange();
        exchange.getIn().setBody(IOConverter.toFile("src/test/data/ftpbinarytest/logo2.png"));
        exchange.getIn().setHeader(Exchange.FILE_NAME, "logo2.png");
        producer = endpoint.createProducer();
        producer.start();
        producer.process(exchange);
        producer.stop();
    }

    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from(getFtpUrl())
                    .routeId("foo").noAutoStartup()
                    .to("file:target/ftpsetnamestest", "mock:result");
            }
        };
    }
}


text:
<!DOCTYPE html>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

/**
 * @class DaliRenderer
 * Layer between DreemGL and Dali. Although Dali has a complete api, this
 * class is used to encapsulate the api to simplify how it is embedded into
 * the dreemgl dali platform.
 *
 * Each instance of DaliRenderer contains a dali.Renderer object, which
 * combines a DaliGeometry object and a DaliMaterial object
 */

/**
 * @property dalirenderer
 * dali.Renderer object
 */

define.class(function(require, exports){
        // internal, DaliApi is a static object to access the dali api
        DaliApi = require('./dali_api')

        // Assign a unique id to each dalirenderer object
        var DaliRenderer = exports
        DaliRenderer.GlobalId = 0

        // The depth index does not auto-increment. Child layers should have a
        // larger value than parent so child actors are rendered after parent.
        // An alternate solution suggested by Nick, is to add an actor as a child
        // to another actor (no depthindex changes are needed).
        DaliRenderer.DepthIndex = 5

        /**
         * @method constructor
         * Create a dali.Renderer object by specifying a geometry and material
         * @param {object} geometry DaliShader object
         * @param {object} material DaliMaterial object
         * You can access the dali.Renderer object as this.dalirenderer
         */
        this.atConstructor = function(geometry, material) {
                this.object_type = 'DaliRenderer'

                var dali = DaliApi.dali;

                // Cache the property values (blend-related)
                this.property_cache = {};

                this.id = ++DaliRenderer.GlobalId;
                this.daligeometry = geometry;
                this.dalimaterial = material;
                this.dalirenderer = new dali.Renderer(this.daligeometry.daligeometry, this.dalimaterial.dalimaterial);

                DaliRenderer.DepthIndex += 5;
                this.dalirenderer.depthIndex = DaliRenderer.DepthIndex;

                if (DaliApi.emitcode) {
                        console.log('DALICODE: ' + this.name() + ' = new dali.Renderer(' + this.daligeometry.name() + ', ' + this.dalimaterial.name() + ');');
                        console.log('DALICODE: ' + this.name() + '.depthIndex = ' + DaliRenderer.DepthIndex + ';');
                }

        }

        // Blend Modes moved from material to renderer in some versions of dali

        /**
         * @method hasBlender
         * Return true if the material has blending api
         */
        this.hasBlender = function(mode) {
                return (typeof this.dalirenderer.setBlendEquation === 'function');
        }

        /**
         * @method setBlendMode
         * Forward request to dali.Material object. dali enumerations match webgl.
         * @param {number} mode Set the blending mode
         */
        this.setBlendMode = function(mode) {
                var val = this.property_cache['blendmode'];
                if (val && val == mode)
                        return;

                this.dalirenderer.blendingMode = mode;
                this.property_cache['blendmode'] = mode;

                if (DaliApi.emitcode) {
                        console.log('DALICODE: ' + this.name() + '.blendingMode = ' + mode + ';');
                }
        }

        /**
         * @method setBlendEquation
         * Forward request to dali.Material object
         * @param {number} equationRgb Equation for combining rgb components
         * @param {number} equationAlpha Equation for combining alpha component
         */
        this.setBlendEquation = function(equationRgb, equationAlpha) {
                var hash = DaliApi.getHash([equationRgb, equationAlpha]);

                var val = this.property_cache['blendequation'];
                if (val && val == hash)
                        return;

                this.dalirenderer.setBlendEquation(equationRgb, equationAlpha);
                this.property_cache['blendequation'] = hash;

                if (DaliApi.emitcode) {
                        console.log('DALICODE: ' + this.name() + '.setBlendEquation(' + equationRgb + ', ' + equationAlpha + ');');
                }
        }

        /**
         * @method setBlendFunc
         * Forward request to dali.Material object
         * @param {number} srcFactorRgb Source blending rgb
         * @param {number} dstFactorRgb Destination blending rgb
         * @param {number} srcFactorAlpha Source blending alpha
         * @param {number} dstFactorAlpha Destination blending alpha
         */
        this.setBlendFunc = function(srcFactorRgb, dstFactorRgb, srcFactorAlpha, dstFactorAlpha) {
                var hash = DaliApi.getHash([srcFactorRgb, dstFactorRgb, srcFactorAlpha, dstFactorAlpha]);

                var val = this.property_cache['blendfunc'];
                if (val && val == hash)
                        return;

                this.dalirenderer.setBlendFunc(srcFactorRgb, dstFactorRgb, srcFactorAlpha, dstFactorAlpha);
                this.property_cache['blendfunc'] = hash;

                if (DaliApi.emitcode) {
                        console.log('DALICODE: ' + this.name() + '.setBlendFunc(' + srcFactorRgb + ', ' + dstFactorRgb + ', ' + srcFactorAlpha + ', ' + dstFactorAlpha + ');');
                }
        }

        this.name = function() {
                return 'dalirenderer' + this.id;
        }

        this.inspect = function(depth) {
                var obj = {daliRenderer:this.id, obj:[this.daligeometry.inspect(depth), this.dalimaterial.inspect(depth)]};
                var util = require('util')
                return util.inspect(obj, {depth: null});
        }

});


text:
require File.expand_path("../../../base", __FILE__)

require "vagrant/util/scoped_hash_override"

describe Vagrant::Util::ScopedHashOverride do
  let(:klass) do
    Class.new do
      extend Vagrant::Util::ScopedHashOverride
    end
  end

  it "should not mess with non-overrides" do
    original = {
      key: "value",
      another_value: "foo"
    }

    expect(klass.scoped_hash_override(original, "foo")).to eq(original)
  end

  it "should override if the scope matches" do
    original = {
      key: "value",
      scope__key: "replaced"
    }

    expected = {
      key: "replaced",
      scope__key: "replaced"
    }

    expect(klass.scoped_hash_override(original, "scope")).to eq(expected)
  end

  it "should ignore non-matching scopes" do
    original = {
      key: "value",
      scope__key: "replaced",
      another__key: "value"
    }

    expected = {
      key: "replaced",
      scope__key: "replaced",
      another__key: "value"
    }

    expect(klass.scoped_hash_override(original, "scope")).to eq(expected)
  end
end


text:
//
// Copyright 2014-2020 Paytronix Systems, Inc.
//
// 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.
//

package com.paytronix.utils.interchange.base.derive

import scala.language.higherKinds
import scala.reflect.macros.Universe
import scala.reflect.macros.whitebox.Context
import scalaz.NonEmptyList

import com.paytronix.utils.interchange.base

/**
 * Trait which implements a family of macros used to generate various coders for some format.
 *
 * Each format implements an object extending this trait and so gets appropriate macros at a lower
 * implementation cost.
 */
trait DeriveCoderMacros extends DeriveUtils {
    val c: Context

    import c.universe.{Annotation, DefDef, DefDefTag, Ident, Quasiquote, TermName, Tree, Type, ValDef, ValDefTag, typeOf, weakTypeTag}

    /** Type of coders for the given type */
    type Coder[A]

    /**
     * The name to use when attaching implicitly derived coders to companion objects, e.g. `avroCoder` or `jacksonCoder`.
     * To avoid confusion and madness this should always return some constant name, but has to be a function because macros.
     */
    //def implicitCoderName: c.universe.TermName

    /** Type tree of coder pairs of the given type name */
    def coderType(tpe: Tree): Tree

    /** Materializer for coder pairs of the given type */
    def materializeCoder(tpe: Type, annotations: List[Annotation]): Tree

    /** Type of encoders of the given type */
    type Encoder[A]

    /** Type tree of encoders of the given type name */
    def encoderType(tpe: Tree): Tree

    /** Materializer for encoders of the given type */
    def materializeEncoder(tpe: Type, annotations: List[Annotation]): Tree

    /** Type of decoders of the given type */
    type Decoder[A]

    /** Type tree of decoders of the given type name */
    def decoderType(tpe: Tree): Tree

    /** Materializer of decoders of the given type */
    def materializeDecoder(tpe: Type, annotations: List[Annotation]): Tree

    /** Tree which evaluates to the front end of the macro package, for implicit structure coder pair implementation */
    def makeStructureCoder(target: Tree): Tree

    /** Generate methods for implementing the encoder type of a structure, giving the model and references to the subsidiary encoders to use */
    def structureEncoderMethods(tpe: Type, encoderFor: Property => Tree, model: Structure): List[Tree]

    /** Generate methods for implementing the decoder type of a structure, giving the model and references to the subsidiary decoders to use */
    def structureDecoderMethods(tpe: Type, decoderFor: Property => Tree, model: Structure): List[Tree]

    /** Tree which evaluates to the front end of the macro package, for implicit wrapper coder pair implementation */
    def makeWrapperCoder(target: Tree): Tree

    /** Generate methods for implementing the decoder type of a wrapper, given an unwrapping function and the single property of the wrapper */
    def wrapperEncoderMethods(targetType: Type, property: Property, unwrap: Tree => Tree): List[Tree]

    /** Generate methods for implementing the decoder type of a wrapper, given a wrapping function and the single property of the wrapper */
    def wrapperDecoderMethods(targetType: Type, property: Property, wrap: Tree => Tree): List[Tree]

    /** Wrap a core expression which materializes or constructs a coder with additional wrapping based on annotations, used for implementing materialize* */
    def wrapCoderForAnnotations (
        coder: Tree,
        annotations: List[Annotation],
        nullable: Tree => Tree,
        default: Tree => Tree => Tree
    ): Tree = {
        val nullableTpe = typeOf[base.nullable]
        val defaultTpe = typeOf[base.default]
        List (
            annotations.collectFirst { case annot if annot.tree.tpe =:= nullableTpe => annot }.map { _ => nullable },
            annotations.collectFirst { case annot if annot.tree.tpe =:= defaultTpe && annot.tree.children.size > 1 =>
                annot.tree.children.tail.head
            }.map { valueTree => default(valueTree) }
        ).foldLeft(coder) { (inside, wrapper) =>
            wrapper match {
                case Some(f) => f(inside)
                case None    =>   inside
            }
        }
    }

    /**
     * Implement the deriveCoder annotation for structures, attaching an automatically derived structure
     * coder pair to the companion of the annotated class
     */
    /* 2014-08-27 RMM: having multiple annotation macros which addToCompanion causes the compiler to not emit the object class (Blah$) even though
                       it doesn't error at runtime.
    def deriveImplicitStructureCoderAnnotation(annottees: c.Expr[Any]*): c.Expr[Any] =
        addToCompanion(annottees) { (targetName, _) =>
            List(q"implicit val ${implicitCoderName}: ${coderType(Ident(targetName))} = ${makeStructureCoder(Ident(targetName))}")
        }
    */

    /** Def macro implementation which derives a coder pair for a structure */
    def structureCoderDefImpl[A: c.WeakTypeTag]: c.Expr[Coder[A]] = try {
        val tpe = weakTypeTag[A].tpe
        val name = TermName(tpe.typeSymbol.name.decodedName.toString + "Coder")
        val model = structureOf(tpe)

        //System.out.println("structureCoderDefImpl tpe: " + tpe)
        //System.out.println("structureCoderDefImpl name: " + name)
        //System.out.println("structureCoderDefImpl model: " + model)

        val declareCoders = model.properties.flatMap { prop =>
            List (
                q"lazy val ${prop.decoderName} = ${materializeDecoder(prop.tpe, prop.annotations)}",
                q"lazy val ${prop.encoderName} = ${materializeEncoder(prop.tpe, prop.annotations)}"
            )
        }

        c.Expr[Coder[A]](q"""
            {
                object $name extends ${coderType(tq"$tpe")} {
                    ..$declareCoders
                    object decode extends ${decoderType(tq"$tpe")} {
                        ..${structureDecoderMethods(tpe, p => Ident(p.decoderName), model)}
                    }
                    object encode extends ${encoderType(tq"$tpe")} {
                        ..${structureEncoderMethods(tpe, p => Ident(p.encoderName), model)}
                    }
                }
                $name: ${coderType(tq"$tpe")}
            }
        """)
    } catch { case e: Exception =>
        System.err.println("uhoh, macro explosion!")
        e.printStackTrace(System.err)
        null
    }

    /** Def macro implementation which derives a decoder for a structure */
    def structureDecoderDefImpl[A: c.WeakTypeTag]: c.Expr[Decoder[A]] = try {
        val tpe = weakTypeTag[A].tpe
        val name = TermName(tpe.typeSymbol.name.decodedName.toString + "Decoder")
        val model = structureOf(tpe)

        val declareDecoders = model.properties.map { prop =>
            q"lazy val ${prop.decoderName} = ${materializeDecoder(prop.tpe, prop.annotations)}"
        }

        c.Expr[Decoder[A]](q"""
            {
                object $name extends ${decoderType(tq"$tpe")} {
                    ..$declareDecoders
                    ..${structureDecoderMethods(tpe, p => Ident(p.decoderName), model)}
                }
                $name: ${decoderType(tq"$tpe")}
            }
        """)
    } catch { case e: Exception =>
        System.err.println("uhoh, macro explosion!")
        e.printStackTrace(System.err)
        null
    }

    /** Def macro implementation which derives a encoder for a structure */
    def structureEncoderDefImpl[A: c.WeakTypeTag]: c.Expr[Encoder[A]] = try {
        val tpe = weakTypeTag[A].tpe
        val name = TermName(tpe.typeSymbol.name.decodedName.toString + "Encoder")
        val model = structureOf(tpe)

        val declareEncoders = model.properties.map { prop =>
            q"lazy val ${prop.encoderName} = ${materializeEncoder(prop.tpe, prop.annotations)}"
        }

        c.Expr[Encoder[A]](q"""
            {
                object $name extends ${encoderType(tq"$tpe")} {
                    ..$declareEncoders
                    ..${structureEncoderMethods(tpe, p => Ident(p.encoderName), model)}
                }
                $name: ${encoderType(tq"$tpe")}
            }
        """)
    } catch { case e: Exception =>
        System.err.println("uhoh, macro explosion!")
        e.printStackTrace(System.err)
        null
    }

    /**
     * Annotation macro implementation which implements a coder pair for a structure where some fields can
     * use an explicit coder pair rather than one from implicit scope
     */
    def structureCoderAnnotation(annottees: c.Expr[Any]*): c.Expr[Any] = try {
        val SimplifiedDeriveAnnotation(targetType, _, _, implDef) = simplifyDeriveAnnotation(annottees: _*)
        val model = structureOf(targetType)

        val overridden = implDef.impl.body.collect {
            case ValDef(_, n, _, _)       if n.decodedName.toString.endsWith("Coder") => n.decodedName.toString.stripSuffix("Coder")
            case DefDef(_, n, _, _, _, _) if n.decodedName.toString.endsWith("Coder") => n.decodedName.toString.stripSuffix("Coder")
        }

        val declareDefaultCoders = model.properties.filterNot(overridden contains _.internalName).map { prop =>
            q"""
                lazy val ${prop.coderName} = ${materializeCoder(prop.tpe, prop.annotations)}
            """
        }

        val newStats = declareDefaultCoders ++ List (
            q"""
                object encode extends ${encoderType(tq"$targetType")} {
                    ..${structureEncoderMethods(targetType, p => q"${p.coderName}.encode", model)}
                }
            """,
            q"""
                object decode extends ${decoderType(tq"$targetType")} {
                    ..${structureDecoderMethods(targetType, p => q"${p.coderName}.decode", model)}
                }
            """
        )

        c.Expr[Any](augmentImpl(implDef, List(coderType(tq"$targetType")), newStats))
    } catch { case e: Exception =>
        System.err.println("uhoh, macro explosion!")
        e.printStackTrace(System.err)
        null
    }

    /**
     * Annotation macro implementation which implements an encoder for a structure where some fields can
     * use an explicit encoder rather than one from implicit scope
     */
    def structureEncoderAnnotation(annottees: c.Expr[Any]*): c.Expr[Any] = try {
        val SimplifiedDeriveAnnotation(targetType, _, _, implDef) = simplifyDeriveAnnotation(annottees: _*)
        val model = structureOf(targetType)

        val overridden = implDef.impl.body.collect {
            case ValDef(_, n, _, _)       if n.decodedName.toString.endsWith("Encoder") => n.decodedName.toString.stripSuffix("Encoder")
            case DefDef(_, n, _, _, _, _) if n.decodedName.toString.endsWith("Encoder") => n.decodedName.toString.stripSuffix("Encoder")
        }

        val declareDefaultEncoders = model.properties.filterNot(overridden contains _.internalName).map { prop =>
            q"""
                lazy val ${prop.encoderName} = ${materializeEncoder(prop.tpe, prop.annotations)}
            """
        }

        val newStats = declareDefaultEncoders ++ structureEncoderMethods(targetType, p => Ident(p.encoderName), model)

        c.Expr[Any](augmentImpl(implDef, List(encoderType(tq"$targetType")), newStats))
    } catch { case e: Exception =>
        System.err.println("uhoh, macro explosion!")
        e.printStackTrace(System.err)
        null
    }

    /**
     * Annotation macro implementation which implements a decoder for a structure where some fields can
     * use an explicit decoder rather than one from implicit scope
     */
    def structureDecoderAnnotation(annottees: c.Expr[Any]*): c.Expr[Any] = try {
        val SimplifiedDeriveAnnotation(targetType, _, _, implDef) = simplifyDeriveAnnotation(annottees: _*)
        val model = structureOf(targetType)

        val overridden = implDef.impl.body.collect {
            case ValDef(_, n, _, _)       if n.decodedName.toString.endsWith("Decoder") => n.decodedName.toString.stripSuffix("Decoder")
            case DefDef(_, n, _, _, _, _) if n.decodedName.toString.endsWith("Decoder") => n.decodedName.toString.stripSuffix("Decoder")
        }

        val declareDefaultDecoders = model.properties.filterNot(overridden contains _.internalName).map { prop =>
            q"""
                lazy val ${prop.decoderName} = ${materializeDecoder(prop.tpe, prop.annotations)}
            """
        }

        val newStats = declareDefaultDecoders ++ structureDecoderMethods(targetType, p => Ident(p.decoderName), model)

        c.Expr[Any](augmentImpl(implDef, List(decoderType(tq"$targetType")), newStats))
    } catch { case e: Exception =>
        System.err.println("uhoh, macro explosion!")
        e.printStackTrace(System.err)
        null
    }

    /**
     * Implement the deriveCoder annotation for wrappers, attaching an automatically derived wrapper
     * coder pair to the companion of the annotated class
     */
    /* 2014-08-27 RMM: having multiple annotation macros which addToCompanion causes the compiler to not emit the object class (Blah$) even though
                       it doesn't error at runtime.
    def deriveImplicitWrapperCoderAnnotation(annottees: c.Expr[Any]*): c.Expr[Any] =
        addToCompanion(annottees) { (targetName, _) =>
            List(q"implicit val ${implicitCoderName}: ${coderType(Ident(targetName))} = ${makeWrapperCoder(Ident(targetName))}")
        }
    */

    /** Def macro implementation which derives a coder pair for a wrapper */
    def wrapperCoderDefImpl[A: c.WeakTypeTag]: c.Expr[Coder[A]] = try {
        val targetType = c.universe.weakTypeTag[A].tpe
        val model = structureOf(targetType)

        model.constructorProperties match {
            case prop :: Nil =>
                val name = TermName(targetType.typeSymbol.name.decodedName.toString + "Coder")
                val declareCoder =
                    List (
                        q"lazy val ${prop.decoderName} = ${materializeDecoder(prop.tpe, prop.annotations)}",
                        q"lazy val ${prop.encoderName} = ${materializeEncoder(prop.tpe, prop.annotations)}"
                    )

                c.Expr[Coder[A]](q"""
                    {
                        object $name extends ${coderType(tq"$targetType")} {
                            ..$declareCoder
                            object decode extends ${decoderType(tq"$targetType")} {
                                ..${wrapperDecoderMethods(targetType, prop, a => model.constructAndAssign(_ => a))}
                            }
                            object encode extends ${encoderType(tq"$targetType")} {
                                ..${wrapperEncoderMethods(targetType, prop, prop.read)}
                            }
                        }
                        $name: ${coderType(tq"$targetType")}
                    }
                """)

            case other =>
                sys.error("expected a class with a constructor taking only one explicit argument (the value being wrapped) not " +
                          other.mkString("[", ", ", "]"))
        }
    } catch { case e: Exception =>
        System.err.println("uhoh, macro explosion!")
        e.printStackTrace(System.err)
        null
    }

    /** Def macro implementation which derives a encoder for a wrapper */
    def wrapperEncoderDefImpl[A: c.WeakTypeTag]: c.Expr[Encoder[A]] = try {
        val targetType = c.universe.weakTypeTag[A].tpe
        val model = structureOf(targetType)

        model.constructorProperties match {
            case prop :: Nil =>
                val name = TermName(targetType.typeSymbol.name.decodedName.toString + "Encoder")
                val declareEncoder = q"lazy val ${prop.encoderName} = ${materializeEncoder(prop.tpe, prop.annotations)}"

                c.Expr[Encoder[A]](q"""
                    {
                        object $name extends ${encoderType(tq"$targetType")} {
                            $declareEncoder
                            ..${wrapperEncoderMethods(targetType, prop, prop.read)}
                        }
                        $name: ${encoderType(tq"$targetType")}
                    }
                """)

            case other =>
                sys.error("expected a class with a constructor taking only one explicit argument (the value being wrapped) not " +
                          other.mkString("[", ", ", "]"))
        }
    } catch { case e: Exception =>
        System.err.println("uhoh, macro explosion!")
        e.printStackTrace(System.err)
        null
    }

    /** Def macro implementation which derives a decoder for a wrapper */
    def wrapperDecoderDefImpl[A: c.WeakTypeTag]: c.Expr[Decoder[A]] = try {
        val targetType = c.universe.weakTypeTag[A].tpe
        val model = structureOf(targetType)

        model.constructorProperties match {
            case prop :: Nil =>
                val name = TermName(targetType.typeSymbol.name.decodedName.toString + "Decoder")
                val declareDecoder = q"lazy val ${prop.decoderName} = ${materializeDecoder(prop.tpe, prop.annotations)}"

                c.Expr[Decoder[A]](q"""
                    {
                        object $name extends ${decoderType(tq"$targetType")} {
                            $declareDecoder
                            ..${wrapperDecoderMethods(targetType, prop, a => model.constructAndAssign(_ => a))}
                        }
                        $name: ${decoderType(tq"$targetType")}
                    }
                """)

            case other =>
                sys.error("expected a class with a constructor taking only one explicit argument (the value being wrapped) not " +
                          other.mkString("[", ", ", "]"))
        }
    } catch { case e: Exception =>
        System.err.println("uhoh, macro explosion!")
        e.printStackTrace(System.err)
        null
    }
}


text:
package se.mulander.cosmos.common.database.testobjects;

import se.mulander.cosmos.common.database.MaxLength;
import se.mulander.cosmos.common.database.TableName;

/**
 * Created by marcu on 2017-03-15.
 */
@TableName(name = "testobject")
public class MissingID
{
	public int intVal;
	public boolean boolValue;
	@MaxLength(length = 20)
	public String stringValue;

	public MissingID(int intValue, boolean boolValue, String stringValue)
	{
		this.intVal = intValue;
		this.boolValue = boolValue;
		this.stringValue = stringValue;
	}

	public MissingID()
	{

	}
}


text:
package org.wso2.developerstudio.eclipse.gmf.esb.internal.persistence;

import org.apache.synapse.mediators.base.SequenceMediator;
import org.eclipse.core.runtime.Assert;
import org.wso2.developerstudio.eclipse.gmf.esb.DBLookupMediator;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbNode;
import org.wso2.developerstudio.eclipse.gmf.esb.persistence.TransformationInfo;

/**
 * DBLookup mediator transformer
 *
 */
public class DBLookupMediatorTransformer extends AbstractDBMediatorTransformer {

	public void transform(TransformationInfo information, EsbNode subject) throws Exception {

		information.getParentSequence().addChild(createDBLookupMediator(information, subject));
		// Transform the property mediator output data flow path.
		doTransform(information, ((DBLookupMediator) subject).getOutputConnector());
	}

	public void transformWithinSequence(TransformationInfo information, EsbNode subject,
			SequenceMediator sequence) throws Exception {
		sequence.addChild(createDBLookupMediator(information, subject));
		doTransformWithinSequence(information, ((DBLookupMediator) subject).getOutputConnector()
				.getOutgoingLink(), sequence);

	}

	private org.apache.synapse.mediators.db.DBLookupMediator createDBLookupMediator(
			TransformationInfo information, EsbNode subject) throws Exception {
		Assert.isTrue(subject instanceof DBLookupMediator,
				"Unsupported mediator passed in for serialization.");
		DBLookupMediator visualDBLookup = (DBLookupMediator) subject;

		org.apache.synapse.mediators.db.DBLookupMediator dbLookupMediator = new org.apache.synapse.mediators.db.DBLookupMediator();
		transformDBMediator(dbLookupMediator, visualDBLookup);
		return dbLookupMediator;
	}

}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Naming controller for directory tree.
 * @param {!DirectoryModel} directoryModel
 * @param {!DirectoryTree} directoryTree
 * @param {!cr.ui.dialogs.AlertDialog} alertDialog
 * @constructor
 * @struct
 */
function DirectoryTreeNamingController(
    directoryModel, directoryTree, alertDialog) {
  /**
   * @private {!DirectoryModel}
   * @const
   */
  this.directoryModel_ = directoryModel;

  /**
   * @private {!DirectoryTree}
   * @const
   */
  this.directoryTree_ = directoryTree;

  /**
   * @private {!cr.ui.dialogs.AlertDialog}
   * @const
   */
  this.alertDialog_ = alertDialog;

  /**
   * @private {DirectoryItem}
   */
  this.currentDirectoryItem_ = null;

  /**
   * @private {boolean}
   */
  this.editting_ = false;

  /**
   * @private {!HTMLInputElement}
   * @const
   */
  this.inputElement_ = /** @type {!HTMLInputElement} */
      (document.createElement('input'));
  this.inputElement_.type = 'text';
  this.inputElement_.spellcheck = false;
  this.inputElement_.addEventListener('keydown', this.onKeyDown_.bind(this));
  this.inputElement_.addEventListener('blur', this.commitRename_.bind(this));
  this.inputElement_.addEventListener('click', function(event) {
    // Stop propagation of click event to prevent it being captured by directory
    // item and current directory is changed to editing item.
    event.stopPropagation();
  });
}

/**
 * Returns input element.
 * @return {!HTMLInputElement}
 */
DirectoryTreeNamingController.prototype.getInputElement = function() {
  return this.inputElement_;
};

/**
 * Attaches naming controller to specified directory item and start rename.
 * @param {!DirectoryItem} directoryItem
 */
DirectoryTreeNamingController.prototype.attachAndStart = function(
    directoryItem) {
  if (!!this.currentDirectoryItem_)
    return;

  this.currentDirectoryItem_ = directoryItem;
  this.currentDirectoryItem_.setAttribute('renaming', true);
  this.currentDirectoryItem_.firstElementChild.appendChild(this.inputElement_);

  this.inputElement_.value = this.currentDirectoryItem_.label;
  this.inputElement_.select();
  this.inputElement_.focus();

  this.editting_ = true;
};

/**
 * Commits rename.
 * @private
 */
DirectoryTreeNamingController.prototype.commitRename_ = function() {
  if (!this.editting_)
    return;
  this.editting_ = false;

  var entry = this.currentDirectoryItem_.entry;
  var newName = this.inputElement_.value;

  // If new name is same with current name, do nothing.
  if (newName === this.currentDirectoryItem_.label) {
    this.detach_();
    return;
  }

  // Validate new name.
  new Promise(entry.getParent.bind(entry)).then(function(parentEntry) {
    return util.validateFileName(parentEntry, newName,
        this.directoryModel_.getFileFilter().isFilterHiddenOn());
  }.bind(this)).then(
  this.performRename_.bind(this, entry, newName),
  function(errorMessage) {
    this.alertDialog_.show(errorMessage, this.detach_.bind(this));
  }.bind(this));
};

/**
 * Performs rename operation.
 * @param {!DirectoryEntry} entry
 * @param {string} newName Validated name.
 * @private
 */
DirectoryTreeNamingController.prototype.performRename_ = function(
    entry, newName) {
  var renamingCurrentDirectory = util.isSameEntry(entry,
      this.directoryModel_.getCurrentDirEntry());
  if (renamingCurrentDirectory)
    this.directoryModel_.setIgnoringCurrentDirectoryDeletion(true /* ignore */);

  // TODO(yawano): Rename might take time on some volumes. Optimiscally show new
  //     name in the UI before actual rename is completed.
  new Promise(util.rename.bind(null, entry, newName)).then(function(newEntry) {
    // Show new name before detacching input element to prevent showing old
    // name.
    var label =
        this.currentDirectoryItem_.firstElementChild.querySelector('.label');
    label.textContent = newName;

    this.currentDirectoryItem_.entry = newEntry;

    this.detach_();

    // If renamed directory was current directory, change it to new one.
    if (renamingCurrentDirectory) {
      this.directoryModel_.changeDirectoryEntry(newEntry,
          this.directoryModel_.setIgnoringCurrentDirectoryDeletion.bind(
              this.directoryModel_, false /* not ignore */));
    }
  }.bind(this), function(error) {
    this.directoryModel_.setIgnoringCurrentDirectoryDeletion(
        false /* not ignore*/);
    this.detach_();

    this.alertDialog_.show(util.getRenameErrorMessage(error, entry, newName));
  }.bind(this));
};

/**
 * Cancels rename.
 * @private
 */
DirectoryTreeNamingController.prototype.cancelRename_ = function() {
  if (!this.editting_)
    return;
  this.editting_ = false;

  this.detach_();
};

/**
 * Detaches controller from current directory item.
 * @private
 */
DirectoryTreeNamingController.prototype.detach_ = function() {
  assert(!!this.currentDirectoryItem_);

  this.currentDirectoryItem_.firstElementChild.removeChild(this.inputElement_);
  this.currentDirectoryItem_.removeAttribute('renaming');
  this.currentDirectoryItem_ = null;

  // Restore focus to directory tree.
  this.directoryTree_.focus();
};

/**
 * Handles keydown event.
 * @param {!Event} event
 * @private
 */
DirectoryTreeNamingController.prototype.onKeyDown_ = function(event) {
  event.stopPropagation();

  switch (util.getKeyModifiers(event) + event.key) {
    case 'Escape':
      this.cancelRename_();
      event.preventDefault();
      break;

    case 'Enter':
      this.commitRename_();
      event.preventDefault();
      break;
  }
};


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ("chroma_core", "0022_fs_name_uniqueness"),
    ]

    operations = [
        migrations.RemoveField(
            model_name="sendstratagemresultstoclientjob",
            name="filesystem",
        ),
        migrations.RemoveField(
            model_name="sendstratagemresultstoclientjob",
            name="job_ptr",
        ),
        migrations.DeleteModel(
            name="SendStratagemResultsToClientJob",
        ),
    ]


text:
package v1alpha1

import (
	"context"
	"testing"

	"github.com/google/go-cmp/cmp"
)

func TestCouchDbDefaults(t *testing.T) {
	testCases := map[string]struct {
		initial  CouchDbSource
		expected CouchDbSource
	}{
		"nil spec": {
			initial: CouchDbSource{},
			expected: CouchDbSource{
				Spec: CouchDbSourceSpec{
					Feed: FeedContinuous,
				},
			},
		},
		"feed not set": {
			initial: CouchDbSource{
				Spec: CouchDbSourceSpec{},
			},
			expected: CouchDbSource{
				Spec: CouchDbSourceSpec{

					Feed: FeedContinuous,
				},
			},
		},
	}
	for n, tc := range testCases {
		t.Run(n, func(t *testing.T) {
			tc.initial.SetDefaults(context.TODO())
			if diff := cmp.Diff(tc.expected, tc.initial); diff != "" {
				t.Fatalf("Unexpected defaults (-want, +got): %s", diff)
			}
		})
	}
}


text:
package jpower.core.utils;

import jpower.core.reflect.MethodInvoker;

public class ThreadUtils {
   /**
    * Sleeps without Exceptions
    *
    * @param time time to sleep in milliseconds
    */
   public static void sleep(long time) {
      try {
         Thread.sleep(time);
      } catch (InterruptedException ignored) {
         // Do Nothing
      }
   }

   public static Thread start(Runnable action) {
      Thread thread = new Thread(action);
      thread.start();
      return thread;
   }

   public static Thread startDaemon(Runnable action) {
      Thread thread = new Thread(action);
      thread.setDaemon(true);
      thread.start();
      return thread;
   }

   public static Thread[] getAllThreads() {
      return (Thread[]) MethodInvoker.invokeSafe(Thread.class, "getThreads");
   }
}


text:
<?php

namespace MusicBrainz\Relation\Type\Url\Work\OtherDatabases;

use MusicBrainz\Relation\Type\Url\Work\OtherDatabases;
use MusicBrainz\Value\Name;

/**
 * This links a soundtrack work to the IMDb page for the movie, show or game of which it is a soundtrack.
 *
 * @see  http://www.imdb.com/
 * @link https://musicbrainz.org/relationship/e5c75559-4dda-452e-a900-ae375935164c
 */
class Imdb extends OtherDatabases
{
    /**
     * Returns the name of the relation.
     *
     * @return Name
     */
    public static function getRelationName(): Name
    {
        return new Name('IMDb');
    }
}


text:
<?php

namespace frontend\models\query;

/**
 * This is the ActiveQuery class for [[\frontend\models\Category]].
 *
 * @see \frontend\models\Category
 */
class CategoryQuery extends \yii\db\ActiveQuery
{
    /*public function active()
    {
        $this->andWhere('[[status]]=1');
        return $this;
    }*/

    /**
     * @inheritdoc
     * @return \frontend\models\Category[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return \frontend\models\Category|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }
}


text:
package com.planet_ink.coffee_mud.Abilities.Songs;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Song_Detection extends Song
{
	public String ID() { return "Song_Detection"; }
	public String name(){ return "Awareness";}
	public int abstractQuality(){ return Ability.QUALITY_OK_OTHERS;}
    protected boolean HAS_QUANTITATIVE_ASPECT(){return false;}

	public void affectEnvStats(Environmental affected, EnvStats affectableStats)
	{
		super.affectEnvStats(affected,affectableStats);
		if(invoker==null) return;
		affectableStats.setSensesMask(affectableStats.sensesMask()|EnvStats.CAN_SEE_BONUS);
	}
}


text:
layout: page
title: Lozano Purple Chemical Dinner
date: 2016-05-24
author: Helen Hines
tags: weekly links, java
status: published
summary: Nunc nec lacus id tellus hendrerit pulvinar et.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 01/14/2016
  endDate: 01/18/2016
  ctyhocn: SLCRRHX
  groupCode: LPCD
published: true
---
Vestibulum sodales justo lectus, vel pretium sapien tempus a. Integer semper vehicula erat sit amet rutrum. In posuere ultricies mauris et sollicitudin. Nulla consequat sem augue, id tincidunt elit elementum non. Nullam ipsum velit, convallis sed lorem in, cursus accumsan nisl. Curabitur eu quam in mi porta ultrices. Suspendisse potenti. Etiam eu justo justo. Sed ullamcorper felis vel ultricies egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur neque purus, laoreet et maximus vitae, tincidunt eget leo. Curabitur ultricies justo at consectetur eleifend. Maecenas commodo dapibus quam, at maximus risus condimentum eget. Sed justo purus, tincidunt id ultrices ut, gravida laoreet ipsum.

* Vestibulum ac eros commodo, porta enim eu, iaculis nunc
* Cras id velit nec lorem interdum congue
* Donec imperdiet libero rhoncus, porta arcu ac, pulvinar purus.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec commodo, eros ut rhoncus mattis, augue sapien porttitor ipsum, a facilisis augue leo nec leo. Aenean venenatis diam ac ante bibendum, sed consectetur turpis tempor. Morbi ullamcorper lobortis metus. Proin mauris elit, commodo sit amet diam id, dignissim gravida dui. Suspendisse sollicitudin porttitor dui in rutrum. Vivamus quis dignissim dui. Ut eleifend ultrices mi, at pharetra mi porttitor eu. Mauris facilisis metus a ligula condimentum scelerisque. Integer blandit lacus non nunc venenatis lobortis. Vivamus faucibus gravida odio consequat viverra. Mauris lobortis eu libero vitae blandit.
Nullam tempus scelerisque urna quis dignissim. In suscipit purus ac sodales finibus. Nunc sed vulputate mi. Aliquam eu congue orci. Aliquam eget laoreet nibh. Nullam sed tristique nulla, dictum tempus sem. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam non augue nec nibh convallis pulvinar in quis lorem. Fusce sagittis auctor est in rhoncus.


text:
package org.rioproject.test;

import java.lang.annotation.*;

/**
 * <p>
 * Defines the method to invoke to get additional JVM system properties to pass to
 * created JVMs
 * </p>
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={ElementType.METHOD, ElementType.FIELD})
@Inherited
public @interface AddSystemProperties {
}


text:
"""`care(A, B, Q, R)`

Compute 'X', the solution to the continuous-time algebraic Riccati equation,
defined as A'X + XA - (XB)R^-1(B'X) + Q = 0, where R is non-singular.

Algorithm taken from:
Laub, "A Schur Method for Solving Algebraic Riccati Equations."
http://dspace.mit.edu/bitstream/handle/1721.1/1301/R-0859-05666488.pdf
"""
function care(A, B, Q, R)
    G = try
        B*inv(R)*B'
    catch y
        if y isa SingularException
            error("R must be non-singular in care.")
        else
            throw(y)
        end
    end

    Z = [A  -G;
        -Q  -A']

    S = schur(Z)
    S = ordschur(S, real(S.values).<0)
    U = S.Z

    (m, n) = size(U)
    U11 = U[1:div(m, 2), 1:div(n,2)]
    U21 = U[div(m,2)+1:m, 1:div(n,2)]
    return U21/U11
end

"""`dare(A, B, Q, R)`

Compute `X`, the solution to the discrete-time algebraic Riccati equation,
defined as A'XA - X - (A'XB)(B'XB + R)^-1(B'XA) + Q = 0, where Q>=0 and R>0

Algorithm taken from:
Laub, "A Schur Method for Solving Algebraic Riccati Equations."
http://dspace.mit.edu/bitstream/handle/1721.1/1301/R-0859-05666488.pdf
"""
function dare(A, B, Q, R)
    if !issemiposdef(Q)
        error("Q must be positive-semidefinite.");
    end
    if (!isposdef(R))
        error("R must be positive definite.");
    end

    n = size(A, 1);

    E = [
        Matrix{Float64}(I, n, n) B*(R\B');
        zeros(size(A)) A'
    ];
    F = [
        A zeros(size(A));
        -Q Matrix{Float64}(I, n, n)
    ];

    QZ = schur(F, E);
    QZ = ordschur(QZ, abs.(QZ.alpha./QZ.beta) .< 1);

    return QZ.Z[(n+1):end, 1:n]/QZ.Z[1:n, 1:n];
end

"""`dlyap(A, Q)`

Compute the solution `X` to the discrete Lyapunov equation
`AXA' - X + Q = 0`.
"""
function dlyap(A::AbstractMatrix, Q)
    lhs = kron(A, conj(A))
    lhs = I - lhs
    x = lhs\reshape(Q, prod(size(Q)), 1)
    return reshape(x, size(Q))
end

"""`gram(sys, opt)`

Compute the grammian of system `sys`. If `opt` is `:c`, computes the
controllability grammian. If `opt` is `:o`, computes the observability
grammian."""
function gram(sys::AbstractStateSpace, opt::Symbol)
    if !isstable(sys)
        error("gram only valid for stable A")
    end
    func = iscontinuous(sys) ? lyap : dlyap
    if opt === :c
        # TODO probably remove type check in julia 0.7.0
        return func(sys.A, sys.B*sys.B')#::Array{numeric_type(sys),2} # lyap is type-unstable
    elseif opt === :o
        return func(Matrix(sys.A'), sys.C'*sys.C)#::Array{numeric_type(sys),2} # lyap is type-unstable
    else
        error("opt must be either :c for controllability grammian, or :o for
                observability grammian")
    end
end

"""`obsv(A, C)` or `obsv(sys)`

Compute the observability matrix for the system described by `(A, C)` or `sys`.

Note that checking for observability by computing the rank from `obsv` is
not the most numerically accurate way, a better method is checking if
`gram(sys, :o)` is positive definite."""
function obsv(A::AbstractMatrix, C::AbstractMatrix)
    T = promote_type(eltype(A), eltype(C))
    n = size(A, 1)
    ny = size(C, 1)
    if n != size(C, 2)
        throw(ArgumentError("C must have the same number of columns as A"))
    end
    res = fill(zero(T), n*ny, n)
    res[1:ny, :] = C
    for i=1:n-1
        res[(1 + i*ny):(1 + i)*ny, :] = res[((i - 1)*ny + 1):i*ny, :] * A
    end
    return res
end
obsv(sys::StateSpace) = obsv(sys.A, sys.C)

"""`ctrb(A, B)` or `ctrb(sys)`

Compute the controllability matrix for the system described by `(A, B)` or
`sys`.

Note that checking for controllability by computing the rank from
`ctrb` is not the most numerically accurate way, a better method is
checking if `gram(sys, :c)` is positive definite."""
function ctrb(A::AbstractMatrix, B::AbstractMatrix)
    T = promote_type(eltype(A), eltype(B))
    n = size(A, 1)
    nu = size(B, 2)
    if n != size(B, 1)
        throw(ArgumentError("B must have the same number of rows as A"))
    end
    res = fill(zero(T), n, n*nu)
    res[:, 1:nu] = B
    for i=1:n-1
        res[:, (1 + i*nu):(1 + i)*nu] = A * res[:, ((i - 1)*nu + 1):i*nu]
    end
    return res
end
ctrb(sys::StateSpace) = ctrb(sys.A, sys.B)

"""`P = covar(sys, W)`

Calculate the stationary covariance `P = E[y(t)y(t)']` of the output `y` of a
`StateSpace` model `sys` driven by white Gaussian noise `w` with covariance
`E[w(t)w(τ)]=W*δ(t-τ)` (δ is the Dirac delta).

Remark: If `sys` is unstable then the resulting covariance is a matrix of `Inf`s.
Entries corresponding to direct feedthrough (D*W*D' .!= 0) will equal `Inf`
for continuous-time systems."""
function covar(sys::AbstractStateSpace, W)
    (A, B, C, D) = ssdata(sys)
    if !isa(W, UniformScaling) && (size(B,2) != size(W, 1) || size(W, 1) != size(W, 2))
        error("W must be a square matrix the same size as `sys.B` columns")
    end
    if !isstable(sys)
        return fill(Inf,(size(C,1),size(C,1)))
    end
    func = iscontinuous(sys) ? lyap : dlyap
    Q = try
        func(A, B*W*B')
    catch
        error("No solution to the Lyapunov equation was found in covar")
    end
    P = C*Q*C'
    if !isdiscrete(sys)
        #Variance and covariance infinite for direct terms
        direct_noise = D*W*D'
        for i in 1:size(C,1)
            if direct_noise[i,i] != 0
                P[i,:] .= Inf
                P[:,i] .= Inf
            end
        end
    else
        P += D*W*D'
    end
    return P
end

covar(sys::TransferFunction, W) = covar(ss(sys), W)

# Note: the H∞ norm computation is probably not as accurate as with SLICOT,
# but this seems to be still reasonably ok as a first step
"""
`..  norm(sys, p=2; tol=1e-6)`

`norm(sys)` or `norm(sys,2)` computes the H2 norm of the LTI system `sys`.

`norm(sys, Inf)` computes the H∞ norm of the LTI system `sys`.
The H∞ norm is the same as the H∞ for stable systems, and Inf for unstable systems.
If the peak gain frequency is required as well, use the function `hinfnorm` instead.
See [`hinfnorm`](@ref) for further documentation.

`tol` is an optional keyword argument, used only for the computation of L∞ norms.
It represents the desired relative accuracy for the computed L∞ norm
(this is not an absolute certificate however).

`sys` is first converted to a `StateSpace` model if needed.
"""
function LinearAlgebra.norm(sys::AbstractStateSpace, p::Real=2; tol=1e-6)
    if p == 2
        return sqrt(tr(covar(sys, I)))
    elseif p == Inf
        return hinfnorm(sys; tol=tol)[1]
    else
        error("`p` must be either `2` or `Inf`")
    end
end
LinearAlgebra.norm(sys::TransferFunction, p::Real=2; tol=1e-6) = norm(ss(sys), p, tol=tol)

"""
`   (Ninf, ω_peak) = hinfnorm(sys; tol=1e-6)`

Compute the H∞ norm `Ninf` of the LTI system `sys`, together with a frequency
`ω_peak` at which the gain Ninf is achieved.

`Ninf := sup_ω σ_max[sys(iω)]`  if `G` is stable (σ_max = largest singular value)
      :=        `Inf'           if `G` is unstable

`tol` is an optional keyword argument for the desired relative accuracy for
the computed H∞ norm (not an absolute certificate).

`sys` is first converted to a state space model if needed.

The continuous-time L∞ norm computation implements the 'two-step algorithm' in:\\
**N.A. Bruinsma and M. Steinbuch**, 'A fast algorithm to compute the H∞-norm of
a transfer function matrix', Systems and Control Letters (1990), pp. 287-293.

For the discrete-time version, see:\\
**P. Bongers, O. Bosgra, M. Steinbuch**, 'L∞-norm calculation for generalized
state space systems in continuous and discrete time', American Control Conference, 1991.

See also [`linfnorm`](@ref).
"""
hinfnorm(sys::AbstractStateSpace{<:Continuous}; tol=1e-6) = _infnorm_two_steps_ct(sys, :hinf, tol)
hinfnorm(sys::AbstractStateSpace{<:Discrete}; tol=1e-6) = _infnorm_two_steps_dt(sys, :hinf, tol)
hinfnorm(sys::TransferFunction; tol=1e-6) = hinfnorm(ss(sys); tol=tol)

"""
`   (Ninf, ω_peak) = linfnorm(sys; tol=1e-6)`

Compute the L∞ norm `Ninf` of the LTI system `sys`, together with a frequency
`ω_peak` at which the gain `Ninf` is achieved.

`Ninf := sup_ω σ_max[sys(iω)]` (σ_max denotes the largest singular value)

`tol` is an optional keyword argument representing the desired relative accuracy for
the computed L∞ norm (this is not an absolute certificate however).

`sys` is first converted to a state space model if needed.

The continuous-time L∞ norm computation implements the 'two-step algorithm' in:\\
**N.A. Bruinsma and M. Steinbuch**, 'A fast algorithm to compute the H∞-norm of
a transfer function matrix', Systems and Control Letters (1990), pp. 287-293.

For the discrete-time version, see:\\
**P. Bongers, O. Bosgra, M. Steinbuch**, 'L∞-norm calculation for generalized
state space systems in continuous and discrete time', American Control Conference, 1991.

See also [`hinfnorm`](@ref).
"""
function linfnorm(sys::AbstractStateSpace; tol=1e-6)
    if iscontinuous(sys)
        return _infnorm_two_steps_ct(sys, :linf, tol)
    else
        return _infnorm_two_steps_dt(sys, :linf, tol)
    end
end
linfnorm(sys::TransferFunction; tol=1e-6) = linfnorm(ss(sys); tol=tol)

function _infnorm_two_steps_ct(sys::AbstractStateSpace, normtype::Symbol, tol=1e-6, maxIters=250, approximag=1e-10)
    # norm type :hinf or :linf the reason that to not use `hinfnorm(sys) = isstable(sys) : linfnorm ? (Inf, Nan)`
    # is to avoid re computing the poles and return the peak frequencies for, e.g., 1/(s^2 + 1)
    # `maxIters`: the maximum  number of iterations allowed in the algorithm (default 1000)
    # approximag is a tuning parameter: what does it mean for a number to be on the imaginary axis
    # Because of this tuning for example, the relative precision that we provide on the norm computation
    # is not a true guarantee, more an order of magnitude
    # outputs: An approximatation of the L∞ norm and the frequency ω_peak at which it is achieved
    # QUESTION: The tolerance for determining if there are poles on the imaginary axis
    # would not be very appropriate for systems with slow dynamics?
    T = promote_type(real(numeric_type(sys)), Float64)
    on_imag_axis = z -> abs(real(z)) < approximag # Helper fcn for readability

    if sys.nx == 0  # static gain
        return (T(opnorm(sys.D)), T(0))
    end

    pole_vec = pole(sys)

    # Check if there is a pole on the imaginary axis
    pidx = findfirst(on_imag_axis, pole_vec)
    if !(pidx isa Nothing)
        return (T(Inf), T(imag(pole_vec[pidx])))
        # note: in case of cancellation, for s/s for example, we return Inf, whereas Matlab returns 1
    end

    if normtype === :hinf && any(z -> real(z) > 0, pole_vec)
        return T(Inf), T(NaN) # The system is unstable
    end

    # Initialization: computation of a lower bound from 3 terms
    if isreal(pole_vec)  # only real poles
        ω_p = minimum(abs.(pole_vec))
    else  # at least one pair of complex poles
        maxidx = argmax([abs(imag(p)/real(p))/abs(p) for p in pole_vec])
        ω_p = abs(pole_vec[maxidx])
    end

    m_vec_init = [0, ω_p, Inf]

    (lb, idx) = findmax([opnorm(evalfr(sys, im*m_vec_init[1]));
                         opnorm(evalfr(sys, im*m_vec_init[2]));
                         opnorm(sys.D)])
    ω_peak = m_vec_init[idx]

    # Iterations
    for iter=1:maxIters
        gamma = (1+2*T(tol))*lb
        R = sys.D'*sys.D - gamma^2*I
        S = sys.D*sys.D' - gamma^2*I
        M = sys.A-sys.B*(R\sys.D')*sys.C
        H = [         M              -gamma*sys.B*(R\sys.B') ;
               gamma*sys.C'*(S\sys.C)            -M'            ]

        Λ = complex(eigvals(H)) # To make type stable

        if numeric_type(sys) <: Real
            # Only need to consider one eigenvalue in each complex-conjugate pairs
            filter!(z -> imag(z) >= 0, Λ)
        end

        # Find eigenvalues on the imaginary axis
        Λ_on_imag_axis = filter(on_imag_axis, Λ)

        ω_vec = imag.(Λ_on_imag_axis)

        sort!(ω_vec)

        if isempty(ω_vec)
            return T((1+tol)*lb), T(ω_peak)
        end

        # Improve the lower bound
        # if not empty, ω_vec contains at least two values
        for k=1:length(ω_vec)-1
            mk = (ω_vec[k] + ω_vec[k+1])/2
            sigmamax_mk = opnorm(evalfr(sys,mk*1im))
            if sigmamax_mk > lb
                lb = sigmamax_mk
                ω_peak = mk
            end
        end
    end
    error("In _infnorm_two_steps_dt: The computation of the H∞/L∞ norm did not converge in $maxIters iterations")
end

function _infnorm_two_steps_dt(sys::AbstractStateSpace, normtype::Symbol, tol=1e-6, maxIters=250, approxcirc=1e-8)
    # Discrete-time version of linfnorm_two_steps_ct above
    # Compuations are done in normalized frequency θ

    on_unit_circle = z -> abs(abs(z) - 1) < approxcirc # Helper fcn for readability

    T = promote_type(real(numeric_type(sys)), Float64, typeof(true/sys.Ts))
    Tw = typeof(one(T)/sys.Ts)

    if sys.nx == 0  # static gain
        return (T(opnorm(sys.D)), Tw(0))
    end

    pole_vec = pole(sys)

    # Check if there is a pole on the unit circle
    pidx = findfirst(on_unit_circle, pole_vec)
    if !(pidx isa Nothing)
        return T(Inf), Tw(angle(pole_vec[pidx])/sys.Ts)
    end

    if normtype == :hinf && any(z -> abs(z) > 1, pole_vec)
        return T(Inf), Tw(NaN) # The system is unstable
    end

    # Initialization: computation of a lower bound from 3 terms

    if isreal(pole_vec)  # not just real poles
        # find frequency of pôle closest to unit circle
        θ_p = angle(pole_vec[argmin(abs.(abs.(pole_vec).-1))])
    else
        θ_p = T(pi)/2
    end

    if isreal(pole_vec)  # only real poles
        ω_p = minimum(abs.(pole_vec))
    else  # at least one pair of complex poles
        maxidx = argmax([abs(imag(p)/real(p))/abs(p) for p in pole_vec])
        ω_p = abs(pole_vec[maxidx])
    end

    m_vec_init = [0, θ_p, pi]

    (lb, idx) = findmax([opnorm(evalfr(sys, exp(im*m))) for m in m_vec_init])
    θ_peak = m_vec_init[idx]

    # Iterations
    for iter=1:maxIters
        gamma = (1+2*T(tol))*lb
        R = gamma^2*I - sys.D'*sys.D
        RinvDt = R\sys.D'
        L = [ sys.A+sys.B*RinvDt*sys.C  sys.B*(R\sys.B');
              zeros(T, sys.nx,sys.nx)      I]
        M = [ I                                 zeros(T, sys.nx,sys.nx);
              sys.C'*(I+sys.D*RinvDt)*sys.C     L[1:sys.nx,1:sys.nx]']

        Λ = complex(eigvals(L,M)) # complex is to ensure type stability

        if numeric_type(sys) <: Real
            # Only need to consider one eigenvalue in each complex-conjugate pairs
            filter!(z -> imag(z) >= 0, Λ)
        end

        # Find eigenvalues on the unit circle
        Λ_on_unit_cirlce = filter(on_unit_circle, Λ)

        θ_vec = angle.(Λ_on_unit_cirlce)

        sort!(θ_vec)

        if isempty(θ_vec)
            return T((1+tol)*lb), Tw(θ_peak/sys.Ts)
        end

        # Improve the lower bound
        # if not empty, θ_vec contains at least two values
        for k=1:length(θ_vec)-1
            mk = (θ_vec[k] + θ_vec[k+1])/2
            sigmamax_mk = opnorm(evalfr(sys,exp(mk*1im)))
            if sigmamax_mk > lb
                lb = sigmamax_mk
                θ_peak = mk
            end
        end
    end
    error("In _infnorm_two_steps_dt: The computation of the L∞ norm did not converge in $maxIters iterations")
end

"""
    S, P, B = balance(A[, perm=true])

Compute a similarity transform `T = S*P` resulting in `B = T\\A*T` such that the row
and column norms of `B` are approximately equivalent. If `perm=false`, the
transformation will only scale `A` using diagonal `S`, and not permute `A` (i.e., set `P=I`).
"""
function balance(A, perm::Bool=true)
    n = LinearAlgebra.checksquare(A)
    B = copy(A)
    job = perm ? 'B' : 'S'
    ilo, ihi, scaling = LAPACK.gebal!(job, B)

    S = diagm(0 => scaling)
    for j = 1:(ilo-1)   S[j,j] = 1 end
    for j = (ihi+1):n   S[j,j] = 1 end

    P = Matrix{Int}(I,n,n)
    if perm
        if ilo > 1
            for j = (ilo-1):-1:1 cswap!(j, round(Int, scaling[j]), P) end
        end
        if ihi < n
            for j = (ihi+1):n    cswap!(j, round(Int, scaling[j]), P) end
        end
    end
    return S, P, B
end

function cswap!(i::Integer, j::Integer, X::StridedMatrix)
    for k = 1:size(X,1)
        X[i, k], X[j, k] = X[j, k], X[i, k]
    end
end

"""
`sysr, G = balreal(sys::StateSpace)`

Calculates a balanced realization of the system sys, such that the observability and reachability gramians of the balanced system are equal and diagonal `G`

See also `gram`, `baltrunc`

Glad, Ljung, Reglerteori: Flervariabla och Olinjära metoder
"""
function balreal(sys::ST) where ST <: AbstractStateSpace
    P = gram(sys, :c)
    Q = gram(sys, :o)

    Q1 = try
        cholesky(Hermitian(Q)).U
    catch
        throw(ArgumentError("Balanced realization failed: Observability grammian not positive definite, system needs to be observable"))
    end
    U,Σ,V = svd(Q1*P*Q1')
    Σ .= sqrt.(Σ)
    Σ1 = diagm(0 => sqrt.(Σ))
    T = Σ1\(U'Q1)

    Pz = T*P*T'
    Qz = inv(T')*Q*inv(T)
    if norm(Pz-Qz) > sqrt(eps())
        @warn("balreal: Result may be inaccurate")
        println("Controllability gramian before transform")
        display(P)
        println("Controllability gramian after transform")
        display(Pz)
        println("Observability gramian before transform")
        display(Q)
        println("Observability gramian after transform")
        display(Qz)
        println("Singular values of PQ")
        display(Σ)
    end

    sysr = ST(T*sys.A/T, T*sys.B, sys.C/T, sys.D, sys.timeevol), diagm(0 => Σ)
end

"""
    sysr, G = baltrunc(sys::StateSpace; atol = √ϵ, rtol=1e-3, unitgain=true, n = nothing)

Reduces the state dimension by calculating a balanced realization of the system sys, such that the observability and reachability gramians of the balanced system are equal and diagonal `G`, and truncating it to order `n`. If `n` is not provided, it's chosen such that all states corresponding to singular values less than `atol` and less that `rtol σmax` are removed.

If `unitgain=true`, the matrix `D` is chosen such that unit static gain is achieved.

See also `gram`, `balreal`

Glad, Ljung, Reglerteori: Flervariabla och Olinjära metoder
"""
function baltrunc(sys::ST; atol = sqrt(eps()), rtol = 1e-3, unitgain = true, n = nothing) where ST <: AbstractStateSpace
    sysbal, S = balreal(sys)
    S = diag(S)
    if n === nothing
        S = S[S .>= atol]
        S = S[S .>= S[1]*rtol]
        n = length(S)
    else
        S = S[1:n]
    end
    A = sysbal.A[1:n,1:n]
    B = sysbal.B[1:n,:]
    C = sysbal.C[:,1:n]
    D = sysbal.D
    if unitgain
        D = D/(C*inv(-A)*B)
    end

    return ST(A,B,C,D,sys.timeevol), diagm(0 => S)
end

"""
    syst = similarity_transform(sys, T)
Perform a similarity transform `T : Tx̃ = x` on `sys` such that
```
à = T⁻¹AT
B̃ = T⁻¹ B
C̃ = CT
D̃ = D
```
"""
function similarity_transform(sys::ST, T) where ST <: AbstractStateSpace
    Tf = factorize(T)
    A = Tf\sys.A*T
    B = Tf\sys.B
    C = sys.C*T
    D = sys.D
    ST(A,B,C,D,sys.timeevol)
end

"""
sysi = innovation_form(sys, R1, R2)
sysi = innovation_form(sys; sysw=I, syse=I, R1=I, R2=I)

Takes a system
```
x' = Ax + Bu + w ~ R1
y  = Cx + e ~ R2
```
and returns the system
```
x' = Ax + Kv
y  = Cx + v
```
where `v` is the innovation sequence.

If `sysw` (`syse`) is given, the covariance resulting in filtering noise with `R1` (`R2`) through `sysw` (`syse`) is used as covariance.

See Stochastic Control, Chapter 4, Åström
"""
function innovation_form(sys::ST, R1, R2) where ST <: AbstractStateSpace
    K = kalman(sys, R1, R2)
    ST(sys.A, K, sys.C, Matrix{eltype(sys.A)}(I, sys.ny, sys.ny), sys.timeevol)
end
# Set D = I to get transfer function H = I + C(sI-A)\ K
function innovation_form(sys::ST; sysw=I, syse=I, R1=I, R2=I) where ST <: AbstractStateSpace
	K = kalman(sys, covar(sysw,R1), covar(syse, R2))
	ST(sys.A, K, sys.C, Matrix{eltype(sys.A)}(I, sys.ny, sys.ny), sys.timeevol)
end


text:
from py2neo import neo4j, Graph, Node, Relationship, rel

graph = Graph('http://localhost:7474/db/data')
cypher = graph.cypher
cypher.execute("MATCH (t:Topics)-[:Contains]->(:Experiments)-[:`In Category`]->(c:Categories) CREATE UNIQUE (t)-[r:`Correlates With`]->(c)")