text:
/*
 * IoT - Industrial Internet Framework
 * Apache License Version 2.0, January 2004
 * Released as a part of Helsinki University
 * Software Engineering Lab in summer 2015
 */
package fi.iot.iiframework.restapi;

import fi.iot.iiframework.domain.Validatable;
import fi.iot.iiframework.errors.ErrorLogger;
import fi.iot.iiframework.errors.ErrorSeverity;
import fi.iot.iiframework.errors.ErrorType;
import fi.iot.iiframework.errors.SysError;
import fi.iot.iiframework.restapi.exceptions.InvalidObjectException;
import fi.iot.iiframework.restapi.exceptions.InvalidParametersException;
import fi.iot.iiframework.restapi.exceptions.ResourceNotFoundException;
import fi.iot.iiframework.restapi.exceptions.ShouldBeBooleanException;
import org.springframework.stereotype.Component;

@Component
public class RestAPIHelper {

    private boolean errorLogging;
    private long maxObjectsRetrieved;

    public RestAPIHelper() {
        this.errorLogging = true;
        maxObjectsRetrieved = 10000;
    }

    public RestAPIHelper(boolean errorLogging) {
        this.errorLogging = errorLogging;
    }

    public RestAPIHelper(boolean errorLogging, long maxObjectsRetrieved) {
        this.errorLogging = errorLogging;
        this.maxObjectsRetrieved = maxObjectsRetrieved;
    }

    /**
     * Returns true if the errors are saved to the database, false if not.
     *
     * @return boolean
     */
    public boolean isErrorLogging() {
        return errorLogging;
    }

    /**
     * Set new status for error logging, it true the errors are saved to the
     * database and if false errors will not be saved.
     *
     * @param errorLogging new status to be set
     */
    public void setErrorLogging(boolean errorLogging) {
        this.errorLogging = errorLogging;
    }

    /**
     * Returns maximum amount of objects retrieved.
     *
     * @return maximum amount of objects retrieved
     *
     * @see RestAPIHelper#exceptionIfWrongLimits()
     */
    public long getMaxObjectsRetrieved() {
        return maxObjectsRetrieved;
    }

    /**
     * Set maximum amount of objects retrieved.
     *
     * @param maxObjectsRetrieved maximum amount of objects retrieved to be set
     */
    public void setMaxObjectsRetrieved(long maxObjectsRetrieved) {
        this.maxObjectsRetrieved = maxObjectsRetrieved;
    }

    /**
     * Throws exception if the given limits are incorret based on the following
     * criteria: {from} cannot be negative, {to} cannot be negative, {to} cannot
     * be equal to {from}, {to} cannot be smaller than {from}, {from} minus {to}
     * cannot be bigger than default max objects retrieved.
     *
     * @param from lower limit
     * @param to   higher limit
     *
     * @throws InvalidParametersException thrown if the criteria are not met
     */
    public void exceptionIfWrongLimits(int from, int to) throws InvalidParametersException {
        if(from<0||to<=0||to==from||from>to
                ||(to-from)>maxObjectsRetrieved) {
            logErrorIfAllowed(new SysError(ErrorType.BAD_REQUEST, ErrorSeverity.LOW, "Invalid parameters given for limits ("+from+", "+to+") in RestAPI."));
            throw new InvalidParametersException();
        }
    }

    /**
     * Returns the object it was given, if the object is null
     * ResourceNotFoundException will be thrown.
     *
     * @param object Object to check for null
     *
     * @return Object it was given
     *
     * @throws ResourceNotFoundException if the object is null
     */
    public Object returnOrException(Object object) throws ResourceNotFoundException {
        if(object==null) {
            logErrorIfAllowed(new SysError(ErrorType.NOT_FOUND, ErrorSeverity.LOW, "Resource request could not be found in RestAPI."));
            throw new ResourceNotFoundException();
        }

        return object;
    }

    /**
     * Checks if Validatable object is valid and throws exception if not.
     *
     * @param validatable Validatable object
     *
     * @throws InvalidObjectException if not valid
     */
    public void checkIfObjectIsValid(Validatable validatable) throws InvalidObjectException {
        if(!validatable.isValid()) {
            logErrorIfAllowed(new SysError(ErrorType.IO_ERROR, ErrorSeverity.LOW, "Object recieved was invalid or wrong type in RestAPI."));
            throw new InvalidObjectException();
        }
    }

    /**
     * Checks if given string resembles a boolean or not and throws exception if
     * not.
     *
     * @param str String to compare
     *
     * @return boolean representation of the String
     *
     * @throws ShouldBeBooleanException if String doesn't resemble a boolean
     */
    public boolean checkIfStringIsBoolean(String str) throws ShouldBeBooleanException {
        if(str.equals("true")) {
            return true;
        }
        if(str.equals("false")) {
            return false;
        }

        throw new ShouldBeBooleanException();
    }

    /*
     * Only log to database if errorLogging is set to true.
     */
    private void logErrorIfAllowed(SysError error) {
        if(errorLogging) {
            ErrorLogger.log(error);
        }
    }
}


text:
package de.learnlib.filter.statistic.sul;

import de.learnlib.api.ObservableSUL;
import de.learnlib.filter.statistic.Counter;

public class ResetCounterObservableSUL<S, I, O> extends ResetCounterSUL<I, O> implements ObservableSUL<S, I, O> {

    private final ObservableSUL<S, I, O> sul;

    public ResetCounterObservableSUL(String name, ObservableSUL<S, I, O> sul) {
        super(name, sul);
        this.sul = sul;
    }

    private ResetCounterObservableSUL(Counter counter, ObservableSUL<S, I, O> sul) {
        super(counter, sul);
        this.sul = sul;
    }

    @Override
    public ObservableSUL<S, I, O> fork() {
        return new ResetCounterObservableSUL<>(getStatisticalData(), sul.fork());
    }

    @Override
    public S getState() {
        return sul.getState();
    }

    @Override
    public boolean deepCopies() {
        return sul.deepCopies();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import unittest
import numpy as np
import flavio
import math

s = 1.519267515435317e+24
ps = 1e-12*s

class TestIntegrate(unittest.TestCase):
    def test_nintegrate(self):
        # integrate sin(x) from 0 to 2
        xmin = 0
        xmax = 2
        val = 2*math.sin(1)**2
        self.assertAlmostEqual(flavio.math.integrate.nintegrate(math.sin, xmin, xmax), val, delta=0.01*val)
        self.assertAlmostEqual(flavio.math.integrate.nintegrate_fast(math.sin, xmin, xmax), val, delta=0.01*val)


text:
ig.module
(
    'game.building-base'
)
.requires
(
	'impact.entity',
    'game.entities.buildings-dirt'
)
.defines(function ()
{
    BuildingBase = ig.Entity.extend(
    {
        collides: ig.Entity.COLLIDES.NEVER,
        type: ig.Entity.TYPE.B,
        checkAgainst: ig.Entity.TYPE.A,
        maxVel: { x: 0, y: 0 },
        health: 1,

        is_built: false,
        is_placed: false,
        building_status: 0,

        building_speed: 1,

        dirt_obj: 0,

        res_type: 0,

        wood_costs: 0,
        stone_costs: 0,
        water_costs: 0,

        sound_building: new ig.Sound('media/sounds/building.*'),
        music_building: new ig.Music(),

        init: function (x, y, settings)
        {
            this.parent(x, y, settings);

            this.music_building.add(this.sound_building);
            this.music_building.loop = true;

            this.reset(x, y, settings);
        },

        reset: function(x, y, settings)
        {
            this.parent(x, y, settings);
            this.music_building.stop();
        },

        update: function ()
        {
            this.parent();

            this.music_building.pause();

            if (!this.is_built && this.is_placed)
            {
                if (this.building_status >= 100)
                {
                    this.building_finished();
                }
            }
        },

        draw: function()
        {
            if (this.is_built || !this.is_placed)
                this.parent();
        },

        check: function (other)
        {
            if (!this.is_built && this.is_placed && other instanceof EntityUnitsWorker)
            {
                this.building_status += this.building_speed;
                this.dirt_obj.working();
                this.music_building.play();
                other.is_building();
            }
        },

        receiveDamage: function(amount, from)
        {
        },

        kill: function()
        {
            this.parent();
        },

        building_placed: function()
        {
            this.dirt_obj = ig.game.spawnEntity(EntityBuildingsDirt, this.pos.x + this.size.x * 0.5 - 8, this.pos.y + this.size.y * 0.5 - 8);
            this.is_placed = true;
        },

        building_finished: function()
        {
            this.music_building.stop();
            ig.game.removeEntity(this.dirt_obj);
            ig.game.add_building(this.res_type);
            this.is_built = true;
        }
    });
});


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Publication_types on Aziz Khan</title>
    <link>https://asntech.github.io/publication_types/</link>
    <description>Recent content in Publication_types on Aziz Khan</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>&copy; 2020 Aziz Khan</copyright>
    <lastBuildDate>Thu, 15 Apr 2021 00:00:00 +0000</lastBuildDate>
    <atom:link href="/publication_types/" rel="self" type="application/rss+xml" />

    <item>
      <title>1</title>
      <link>https://asntech.github.io/publication_types/1/</link>
      <pubDate>Thu, 15 Apr 2021 00:00:00 +0000</pubDate>

      <guid>https://asntech.github.io/publication_types/1/</guid>
      <description></description>
    </item>

    <item>
      <title>2</title>
      <link>https://asntech.github.io/publication_types/2/</link>
      <pubDate>Tue, 17 Nov 2020 00:00:00 +0000</pubDate>

      <guid>https://asntech.github.io/publication_types/2/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
class AssayOrganism < ActiveRecord::Base
  belongs_to :assay
  belongs_to :organism
  belongs_to :culture_growth_type
  belongs_to :strain

  validates_presence_of :assay
  validates_presence_of :organism

  include Seek::Rdf::ReactToAssociatedChange
  update_rdf_on_change :assay

  scope :matches_for, ->(strain,organism,assay,culture_growth_type) do
     strain_clause = strain.nil? ? "strain_id IS NULL" : "strain_id = #{strain.id}"
     cg_clause = culture_growth_type.nil? ? "culture_growth_type_id IS NULL" : "culture_growth_type_id = #{culture_growth_type.id}"
     where("#{strain_clause} AND assay_id = ? AND organism_id = ? AND #{cg_clause}",assay.id,organism.id)
  end

  def self.exists_for? strain,organism,assay,culture_growth_type
    !AssayOrganism.matches_for(strain,organism,assay,culture_growth_type).empty?
  end

end


text:
- rex
    + tokens to consider (clang -cc1 -dump-tokens temp.cpp)
        * https://msdn.microsoft.com/en-us/library/3bstk3k5.aspx
        * comma
        * built-in types (deduced?)
        * name for each operator (star, equal, )
        * brace, bracket, angle bracket, etc.
        * literals (string, numeric, etc.)
        * c++ seems to have a token for every keyword (and IDs, etc.)
        * keywords, identifiers, literals (integer, float, boolean, char, string[char*], pointer), operators, punctuators
        * https://msdn.microsoft.com/en-us/library/126fe14k.aspx (operators)
    + ... range or ..
    + **Operators** are used in expressions to describe operations involving one or more operands. For example, the expression a + b uses the + operator to add the two operands a and b.
    + **Punctuators** are for grouping and separating.
    + Operator or punctuator
        * Alternative representation
        * &&  and
        * |   bitor
        * ||  or
        * ^   xor
        * ~   compl
        * &   bitand
        * &=  and_eq
        * |=  or_eq
        * ^=  xor_eq
        * !   not
        * !=  not_eq


text:
import * as React from "react";

interface ButtonProperties {
  toggle ?: boolean;
  onClick ?: (button : ButtonComponent) => void;
  width ?: string;
  height ?: string;
  href ?: string;
  target ?: string;
  icon ?: JSX.Element;
  title : string;
}

interface ButtonState {
  toggleValue ?: boolean;
}

export class ButtonComponent extends React.Component<ButtonProperties, ButtonState> {
  constructor(props : any) {
    super(props);
    if(this.props.toggle) {
      this.state = {
        toggleValue: false
      };
    }
  }
  onClick() {
    if(this.props.toggle) {
      let toggleValue : boolean = !this.state.toggleValue;
      this.setState({
        toggleValue: toggleValue
      });
    }

    if(this.props.onClick) {
      this.props.onClick(this);
    }
  }
  createStyle() {
    return {
      display: this.props.width ? undefined : "inline-block",
      width: this.props.width,
      height: this.props.height
    };
  }
  iconContent() {
    return this.props.icon ?
{this.props.icon}
 : undefined;
  }

  className() { return "btn"; }
  classNameActive() { return "btn--active"; }

  render() {
    let className = (this.props.toggle && this.state.toggleValue) ? `${this.className()} ${this.classNameActive()}` : this.className();

    if(this.props.href) {
      return (

          {this.iconContent()}

{this.props.title}

      );
    }
    else {
      return (

        {this.iconContent()}

{this.props.title}

);
    }
  }
}

export class GhostButton extends ButtonComponent {
  className() { return "btn-ghost"; }
  classNameActive() { return "btn-ghost--active"; }
}

export class TextButton extends ButtonComponent {
  className() { return "btn-text"; }
  classNameActive() { return "btn-text--active"; }
}


text:
package com.deeplink;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Keep
public class CommonRouteHandler implements RouteHandler {
    private static final String ENCODING_UTF_8 = "utf-8";
    private String regex;
    private Class<?> clazz;
    private HashMap<String, String> customParam = new HashMap<>();

    public CommonRouteHandler(String regex, Class<?> clazz) {
        this.regex = regex;
        this.clazz = clazz;
    }

    @Override
    public Intent handle(Uri uri, Context context) {
        HashMap<String, UrlParam> params = new HashMap<>();
        String path = uri.getPath();
        // We will use name expression to extract the parameter in path, but it won't work in following case:
        // url : /r/ddd/31303/?p=1
        // regex : \/r\/.+\/(?<pid>\d+)$
        // So remove the last char '/' in path to make it works
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        // When there's no path segments, redirect user to home page.
        if (path.equals("") && regex.equals("")) {
            params.putAll(convert(customParam));
            Intent intent = new Intent(context, clazz);
            intent.putExtra(DeepLink.FROM_DEEP_LINK, true);
            intent.putExtra(DeepLink.DEEP_LINK_PARAM, params);
            return intent;
        }
        //
        if (isMatch(uri, regex)) {
            // get parameter in path segments
            params.putAll(findParameterInPath(uri, regex));
            // get parameter in query
            Set<String> queryParameterNames = uri.getQueryParameterNames();
            for (String name : queryParameterNames) {
                List<String> list = uri.getQueryParameters(name);
                UrlParam urlParam;
                if (list.size() > 1) {
                    urlParam = UrlParam.from(list);
                } else {
                    urlParam = UrlParam.from(list.get(0));
                }
                params.put(name, urlParam);
            }
            // put all custom parameter into final parameter map
            params.putAll(convert(customParam));
            // build intent to pass whole params
            Intent intent = new Intent(context, clazz);
            intent.putExtra(DeepLink.FROM_DEEP_LINK, true);
            intent.putExtra(DeepLink.DEEP_LINK_PARAM, params);
            return intent;
        } else {
            return null;
        }
    }

    private Map<String, UrlParam> findParameterInPath(Uri uri, String regex) {
        Map<String, UrlParam> urlParamMap = new HashMap<>();
        List<String> uriPathSegments = uri.getPathSegments();
        List<String> regexSegments =  new ArrayList<>(Arrays.asList(regex.split("/")));
        regexSegments.remove(0);
        for (int i = 0; i < uriPathSegments.size(); i++) {
            String actual = uriPathSegments.get(i);
            String expect = regexSegments.get(i);
            if (isParameter(expect)) {
                int length = expect.length();
                String key = expect.substring(1, length - 1);
                UrlParam urlParam = urlParamMap.get(key);
                if (urlParam == null) {
                    urlParam = UrlParam.from(actual);
                    urlParamMap.put(key, urlParam);
                } else {
                    urlParam.list.add(actual);
                }
            }
        }
        return urlParamMap;
    }

    private boolean isMatch(Uri uri, String regex) {
        List<String> uriPathSegments = uri.getPathSegments();
        List<String> regexSegments = new ArrayList<>(Arrays.asList(regex.split("/")));
        regexSegments.remove(0);
        if (uriPathSegments.size() != regexSegments.size()) {
            return false;
        }

        for (int i = 0; i < uriPathSegments.size(); i++) {
            String actual = uriPathSegments.get(i);
            String expect = regexSegments.get(i);
            if (!isParameter(expect)) {
                if (!actual.equals(expect)) {
                    return false;
                }
            }
        }
        return true;
    }

    private boolean isParameter(String expect) {
        return expect.startsWith("{") && expect.endsWith("}");
    }

    private Map<String, UrlParam> convert(@NonNull Map<String, String> strMap) {
        HashMap<String, UrlParam> map = new HashMap<>(strMap.size());
        for (Map.Entry<String, String> entry : strMap.entrySet()) {
            map.put(entry.getKey(), UrlParam.from(entry.getValue()));
        }
        return map;
    }

    public CommonRouteHandler addCustomParam(String key, String value) {
        customParam.put(key, value);
        return this;
    }

    @NonNull
    public static Map<String, String> getQueryStringMap(String urlString) {
        Map<String, String> queryPairs = new HashMap<>();
        if (!TextUtils.isEmpty(urlString)) {
            Uri uri = Uri.parse(urlString);
            if (uri != null) {
                for (String pair : uri.getQueryParameterNames()) {
                    try {
                        queryPairs.put(
                                URLDecoder.decode(pair, ENCODING_UTF_8),
                                URLDecoder.decode(uri.getQueryParameter(pair), ENCODING_UTF_8));
                    } catch (UnsupportedEncodingException ex) {
                        Log.e(CommonRouteHandler.class.getSimpleName(), ex.getMessage());
                    }
                }
            }
        }
        return queryPairs;
    }
}


text:
namespace AjourBT.Domain.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class holiday : DbMigration
    {
        public override void Up()
        {
        }

        public override void Down()
        {
        }
    }
}


text:
layout: post
comments: true
title:  "Controllability"
excerpt: "Derivation of controllability conditions for a linear system dynamics."
date:   2016-09-19 11:00:00
mathjax: true
---

#### Vivek Yadav

Before getting into design control laws, it is crucial to first determine if the system is controllable or not? Further, as control laws are based on state estimates obtained from the available sensor measurements, it is important to know if the state estimates required for control are observable. These two specific questions are addressed by the concepts fo controllability and observability.

#### Controllability:

We say a system is controllable if given any initial state vector and a final state vector, we can find at least one control law that ensures that the final state vector can be achieved.

##### Controllability of a continuous linear system
Say the continuous dynamic system is given by

$$ \frac{d x(t) }{dt} = A x(t) + B u(t) .$$

$$ x(t) = e^{At} x_0 +  \int_{0}^{t} e^{A(t- \lambda) } B u(\lambda) d\lambda .  $$

Therefore, given a final state \\(x_f \\), for some time \\(t_f\\), we have

$$ x_f = e^{At} x_0 +  \int_{0}^{t_f} e^{A(t_f- \lambda) } B u(\lambda) d\lambda .  $$

Using Cayley-Hamilton theorm we can express \\( e^{A(t_f- \lambda)}  \\),

$$ e^{A(t_f- \lambda)} = \sum_{i=0}^{n-1} a_i(t_f,\lambda) A^{i}$$

Recall, the solution of this equation is

$$ x_f = e^{At_f}c(t_f)  = e^{At_f} x_0 +  \int_{0}^{t_f} e^{A(t_f- \lambda) } B u(\lambda) d\lambda .  $$

Substituting \\( e^{A(t- \lambda)} \\) gives

$$ x_f = e^{At_f} x_0 +  \int_{0}^{t_f}  \sum_{i=0}^{n-1} a_i(t_f,\lambda) A^{i} B u(\lambda) d\lambda .  $$

As \\( A \\) and \\( B\\) are constant, we can rearrange the solution equation as

$$ x_f - e^{At_f} x_0 =   \underbrace{\left[ \begin{array}{ccccc} B & AB & A^2B & \dots & A^{n-1}B \end{array}  \right]}_{controllability~matrix}  \left[ \begin{array}{c} \int_{0}^{t} a_0(t_f,\lambda) d\lambda  \\ \int_{0}^{t} a_1(t_f,\lambda) d\lambda  \\ \int_{0}^{t} a_2(t_f,\lambda) d\lambda  \\ \vdots \\ \int_{0}^{t} a_{i-1}(t_f,\lambda) d\lambda  \end{array}  \right] .  $$

The equation above has solution for any value of \\(x_f\\) and \\(x_0\\) if and only if \\( \left[ \begin{array}{ccccc} B & AB & A^2B & \dots & A^{n-1}B \end{array}  \right]  \\) has rank \\( n \\). The \\( \left[ \begin{array}{ccccc} B & AB & A^2B & \dots & A^{n-1}B \end{array}  \right]  \\) matrix is also refered as the controllability matrix. ** Controllability matrix can be computed in MATLAB using 'ctrb' command.  **

##### Controllability of a discrete linear system

Controllability of a discrete system is also defined in a similar manner. Lets consider a discrete system given by

$$ x[k+1] = A x[k] + Bu[k] . $$

The system above is controllable if for any given values of initial and final states, there exists a sequence of control inputs that when applied to the system above, take the system from the initial state to the final state. The solution for the system above, given the initial state \\( x_0 \\), given \\( n \\) steps between them is,

$$ x[n] = x_f = A^{n} x[0] + \sum_{i=0}^{n-1}A^{n-i-1} B u[i] $$

$$ x_f = A^{n} x[0] + A^{n-1} B u[0]+A^{n-2} B u[1]+\dots+ B u[n-1]$$

$$ x_f - A^{n} x[0] =   \underbrace{\left[ \begin{array}{ccccc} B & AB & A^2B & \dots & A^{n-1}B \end{array}  \right]}_{controllability~matrix}  \left[ \begin{array}{c} u[n-1]  \\ u[n-2]  \\ u[n-3]  \\ \vdots \\  u[0]  \end{array}  \right] .  $$

The equation above has solution for any value of \\(x_f\\) and \\(x_0\\) if and only if \\( \left[ \begin{array}{ccccc} B & AB & A^2B & \dots & A^{n-1}B \end{array}  \right]  \\) has rank \\( n \\). The \\( \left[ \begin{array}{ccccc} B & AB & A^2B & \dots & A^{n-1}B \end{array}  \right]  \\) matrix is also refered as the controllability matrix.

Controllability is also expressed via a Grammian matrix P,

$$ P(T) =  \int_{0}^{T} e^{ A \lambda } BB^T  e^{A^T \lambda }    d\lambda .  $$

If \\( P(T) \\) is non-singular for all \\( T\\) then the underlying dynamic system is controllable.

##### Similarity transforms

Two square-matrices  \\( A \\)  and  \\( C \\)  are called similar if there exists an invertible square matrix  \\( P \\)  such that, \\( C= P^{-1}AP \\). The transformation  \\(P^{-1}AP \\) is also called similarity. Similarity transforms allow us to express system dynamics in special forms that allow us to draw inferences about the system dynamics easily and design of control easier. Before getting into useful similarity transforms, lets first look into some properties of similarity transforms,

1. Matrices \\( A \\) and \\( C \\) have the same eigen values. Say some \\( \lambda \\) satisfies, \\( det( A - \lambda I ) = 0  \\), then,

    $$ det( C - \lambda I ) = det( P^{-1} A P - \lambda P^{-1} P) = det( P^{-1}( A - \lambda I  ) P )    $$

    The experession above is 0 when \\( ( A - \lambda I  )  \\) loses rank, i.e. for eigen values of \\( A \\). Therefore, \\( A \\) and \\( C \\) have the same eigen values, and if we applied similairty tranform to the system dynamics matrix \\( A \\), the corresponding stability properties will not change.
2. Consider the system \\( \dot{x} = Ax + Bu \\), with the transformation of variables \\( \hat{x} = P x \\). The system dynamics equation modifies as,

    $$ \dot{ \hat{x}} = P^{-1} A P  + P^{-1}  B. $$
3. By choosing the values of \\( P \\) appropriately, the system dynamics equations can be modified into special forms that are easier for control design and analysis. A few examples of such transforms are,
    - Jordan tranform
    - Diagonal transform (From HW 1)
    - Canonical transform (From HW 2)
4. Applying similarity transforms does not change the controllability of the system.

##### Output controllability

In many control applications, we do not have direct measure of the states of the system. The system is monitored using mesurements from the system. For such systems, output controllability is defined with reference to the ability to control the output. A system is said to be output controllable such that for any starting and final output of the system, one or many sequence of control inputs exist that when applied to the system take its output from the initial to final values. A system

$$ \frac{d x(t) }{dt} = A x(t) + B u(t) .$$

with measurements

$$ y = C x + D u $$

is said to be output controllable if the matrix \\( \left[ \begin{array}{cccccc} CB & CAB & CA^2B & \dots & CA^{n-1}B & D \end{array}  \right]  \\) has rank \\( n \\).

##### When do systems become uncontrollable?

There are several factors that can give rise to an uncontrolable system. The list below is just enumeration of a few of them.

1. When some states are repeated. If the states are chosen poorely, it may happen that one or more states are completely defined by the other states. In such cases, it is not possible to control all the states independently.
2. Any external contraints on the system that are not accounted for by the dynamic model. For example, the same set of equations of motion describe movements of a 2-link robotic manipulator that is free to move anywhere and one that is constrained to move along a line.
3. Controller with smaller bandwidth. Recall, bandwidth is the frequency at which the power of the frequency response drops to -3dB and phase shifts by 180. A larger bandwidth implies the controller is very responsive and can apply the commanded control value.
4. Systems may also become uncontrollable if two or more control variables influence the system in the same way.
5. Zero-dynamics are defined as the 'residual dynamics' of the system when the output of the system is zero. By definition, the states involved in zero-dynamics cannot always be controlled. We will discuss this concept in more detail later in the course.

$$ \dot{x_1} = A_1 x_1 + B_1u $$

$$ \dot{x_2} = A_{12} x_1 + A_{22} x_2 + B_2 u $$

with measurement \\(y = x_1\\). Say we apply control such that \\( y = 0\\) this gives \\( x_1 = 0 \\), and the system above reduces to

$$ \dot{x_1} = 0 $$

$$ \dot{x_2} = A_{22} x_2$$

Depending on the value of $ A_{22} $, this system may be controllable or not controllable. If $ A_{22} $ is negative, then the \\( x_2 \\) goes to 0, else it blows up.

#### Stabalizability
In addition to controllability, a concept of stabalizability is also defined. A system is stabalizable if for any given initial conditions, there exists atleast one series of control inputs that drive the system states to 0 either in finite time or asymptotically. All controlable states are stabalizable.


text:
<?php

declare(strict_types=1);

namespace Railt\Http\Tests\Request;

use PHPUnit\Framework\Exception;
use PHPUnit\Framework\ExpectationFailedException;
use Railt\Contracts\Http\Request\VariablesInterface;
use Railt\Http\Request;
use Railt\Http\Tests\TestCase;

/**
 * Class VariablesTestCase
 */
class VariablesTestCase extends TestCase
{
    /**
     * @return array
     */
    public function iterableProvider(): array
    {
        $generator = static function () {
            yield 'a' => 42;
        };

        return [
            'Generator'     => [$generator()],
            'ArrayIterator' => [new \ArrayIterator(['a' => 42])],
            'array'         => [['a' => 42]],
        ];
    }

    /**
     * @dataProvider iterableProvider
     *
     * @param iterable $iterator
     * @return void
     * @throws ExpectationFailedException
     * @throws Exception
     */
    public function testVariablesCount(iterable $iterator): void
    {
        $request = $this->request($iterator);

        $this->assertCount(1, $request);
    }

    /**
     * @param iterable $variables
     * @return VariablesInterface
     */
    private function request(iterable $variables): VariablesInterface
    {
        return new Request('', $variables);
    }

    /**
     * @dataProvider iterableProvider
     *
     * @param iterable $iterator
     * @return void
     * @throws ExpectationFailedException
     */
    public function testVariablesExisting(iterable $iterator): void
    {
        $request = $this->request($iterator);

        $this->assertTrue($request->hasVariable('a'));
    }

    /**
     * @dataProvider iterableProvider
     *
     * @param iterable $iterator
     * @return void
     * @throws ExpectationFailedException
     */
    public function testVariablesNotExisting(iterable $iterator): void
    {
        $request = $this->request($iterator);

        $this->assertFalse($request->hasVariable('ab'));
        $this->assertFalse($request->hasVariable('A'));
    }

    /**
     * @dataProvider iterableProvider
     *
     * @param iterable $iterator
     * @return void
     * @throws ExpectationFailedException
     */
    public function testVariableValue(iterable $iterator): void
    {
        $request = $this->request($iterator);

        $this->assertSame(42, $request->getVariable('a'));
        $this->assertNull($request->getVariable('xxx'));
    }

    /**
     * @dataProvider iterableProvider
     *
     * @param iterable $iterator
     * @return void
     * @throws ExpectationFailedException
     */
    public function testVariablesFetching(iterable $iterator): void
    {
        $request = $this->request($iterator);

        $this->assertSame(['a' => 42], $request->getVariables());
    }
}


text:
require 'spec_helper'
require 'active_support/core_ext/hash/indifferent_access'

describe Cassette::Authentication::Filter do
  before do
    allow(Cassette::Authentication).to receive(:validate_ticket)
  end

  class ControllerMock
    attr_accessor :params, :request, :current_user
    def self.before_filter(*); end
    include Cassette::Authentication::Filter

    def initialize(params = {}, headers = {})
      self.params = params.with_indifferent_access
      self.request = OpenStruct.new(headers: headers.with_indifferent_access)
    end
  end

  shared_context 'with NOAUTH' do
    before do
      ENV['NOAUTH'] = 'yes'
    end

    after do
      ENV.delete('NOAUTH')
    end
  end

  describe '#validate_raw_role!' do
    let(:controller) { ControllerMock.new }
    let(:current_user) { instance_double(Cassette::Authentication::User) }

    before do
      allow(controller).to receive(:current_user).and_return(current_user)
    end

    it_behaves_like 'with NOAUTH' do
      it 'never checks the role' do
        expect(current_user).not_to receive(:has_raw_role?)
        controller.validate_raw_role!(:something)
      end

      it 'does not raise error' do
        expect { controller.validate_raw_role!(:something) }.not_to raise_error
      end
    end

    it 'forwards to current_user' do
      role = instance_double(String)

      expect(current_user).to receive(:has_raw_role?).with(role).and_return(true)
      controller.validate_raw_role!(role)
    end

    it 'raises a Cassette::Errors::Forbidden when current_user does not have the role' do
      role = instance_double(String)

      expect(current_user).to receive(:has_raw_role?).with(role).and_return(false)
      expect { controller.validate_raw_role!(role) }.to raise_error(Cassette::Errors::Forbidden)
    end
  end

  describe '#validate_role!' do
    let(:controller) { ControllerMock.new }
    let(:current_user) { instance_double(Cassette::Authentication::User) }

    before do
      allow(controller).to receive(:current_user).and_return(current_user)
    end

    it_behaves_like 'with NOAUTH' do
      it 'never checks the role' do
        expect(current_user).not_to receive(:has_role?)
        controller.validate_role!(:something)
      end

      it 'does not raise error' do
        expect { controller.validate_role!(:something) }.not_to raise_error
      end
    end

    it 'forwards to current_user' do
      role = instance_double(String)

      expect(current_user).to receive(:has_role?).with(role).and_return(true)
      controller.validate_role!(role)
    end

    it 'raises a Cassette::Errors::Forbidden when current_user does not have the role' do
      role = instance_double(String)

      expect(current_user).to receive(:has_role?).with(role).and_return(false)
      expect { controller.validate_role!(role) }.to raise_error(Cassette::Errors::Forbidden)
    end
  end

  describe '#validate_authentication_ticket' do
    shared_examples_for 'controller without authentication' do
      it 'does not validate tickets' do
        controller.validate_authentication_ticket
        expect(Cassette::Authentication).not_to have_received(:validate_ticket)
      end

      it 'sets current_user' do
        controller.validate_authentication_ticket
        expect(controller.current_user).to be_present
      end
    end

    it_behaves_like 'with NOAUTH' do
      context 'and no ticket' do
        let(:controller) { ControllerMock.new }

        it_behaves_like 'controller without authentication'
      end

      context 'and a ticket header' do
        let(:controller) do
          ControllerMock.new({}, 'Service-Ticket' => 'le ticket')
        end

        it_behaves_like 'controller without authentication'
      end

      context 'and a ticket param' do
        let(:controller) do
          ControllerMock.new(ticket: 'le ticket')
        end

        it_behaves_like 'controller without authentication'
      end
    end

    context 'with a ticket in the query string *AND* headers' do
      let(:controller) do
        ControllerMock.new({ 'ticket' => 'le other ticket' }, 'Service-Ticket' => 'le ticket')
      end

      it 'should send only the header ticket to validation' do
        controller.validate_authentication_ticket
        expect(Cassette::Authentication).to have_received(:validate_ticket).with('le ticket', Cassette.config.service)
      end
    end

    context 'with a ticket in the query string' do
      let(:controller) do
        ControllerMock.new('ticket' => 'le ticket')
      end

      it 'should send the ticket to validation' do
        controller.validate_authentication_ticket
        expect(Cassette::Authentication).to have_received(:validate_ticket).with('le ticket', Cassette.config.service)
      end
    end

    context 'with a ticket in the Service-Ticket header' do
      let(:controller) do
        ControllerMock.new({}, 'Service-Ticket' => 'le ticket')
      end

      it 'should send the ticket to validation' do
        controller.validate_authentication_ticket
        expect(Cassette::Authentication).to have_received(:validate_ticket).with('le ticket', Cassette.config.service)
      end
    end
  end
end


text:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class JavaList {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        List<Integer> list = new ArrayList<>();
        int n=in.nextInt();
        for (int i=0;i<n;i++) list.add(in.nextInt());
        int q=in.nextInt();
        for (int i=0;i<q;i++) {
            String operation=in.next();
            if (operation.equals("Insert")) list.add(in.nextInt(), in.nextInt());
            else if (operation.equals("Delete")) list.remove(in.nextInt());
        }
        for (int a:list) System.out.print(a+" ");
    }
}


text:
import logging
from storyweb.core import db
from storyweb.model.user import User
from storyweb.model.card import Card, Alias # noqa
from storyweb.model.link import Link # noqa
from storyweb.model.reference import Reference # noqa
from storyweb.model.spider_tag import SpiderTag # noqa

log = logging.getLogger(__name__)

def make_fixtures():
    User.default_user()
    db.session.commit()


text:
<?xml version="1.0"?>
<?xml-model
  href="http://download.ros.org/schema/package_format3.xsd"
  schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>rosclean</name>
  <version>1.15.8</version>
  <description>
    rosclean: cleanup filesystem resources (e.g. log files).
  </description>
  <maintainer email="michel@ekumenlabs.com">Michel Hidalgo</maintainer>
  <maintainer email="jacob@openrobotics.org">Jacob Perron</maintainer>
  <license>BSD</license>

  <url type="website">http://wiki.ros.org/rosclean</url>
  <url type="bugtracker">https://github.com/ros/ros/issues</url>
  <url type="repository">https://github.com/ros/ros</url>

  <author>Ken Conley</author>
  <author email="dthomas@openrobotics.org">Dirk Thomas</author>

  <buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
  <buildtool_depend condition="$ROS_PYTHON_VERSION == 2">python-setuptools</buildtool_depend>
  <buildtool_depend condition="$ROS_PYTHON_VERSION == 3">python3-setuptools</buildtool_depend>

  <exec_depend condition="$ROS_PYTHON_VERSION == 2">python-rospkg</exec_depend>
  <exec_depend condition="$ROS_PYTHON_VERSION == 3">python3-rospkg</exec_depend>
</package>


text:
ALTER TABLE patients
  ALTER COLUMN weight TYPE NUMERIC(4,1),
  ALTER COLUMN height TYPE NUMERIC(3,1);


text:
#ifdef HAVE_CONFIG_H
#include "../../../ext_config.h"
#endif

#include <php.h>
#include "../../../php_ext.h"
#include "../../../ext.h"

#include <Zend/zend_exceptions.h>

#include "kernel/main.h"

ZEPHIR_INIT_CLASS(Phalconry_Mvc_Application_BootstrapInterface) {

	ZEPHIR_REGISTER_INTERFACE(Phalconry\\Mvc\\Application, BootstrapInterface, phalconry, mvc_application_bootstrapinterface, phalconry_mvc_application_bootstrapinterface_method_entry);

	return SUCCESS;

}

/**
 * Boots the application.
 *
 * @param \Phalconry\Mvc\ApplicationInterface app
 * @return void
 */
ZEPHIR_DOC_METHOD(Phalconry_Mvc_Application_BootstrapInterface, boot);


text:
import os.path as path
import sys

ugettext = lambda s: s
proj_dir = path.dirname(path.dirname(__file__))

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'UTC'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en'

LANGUAGES = (
    ('en', ugettext('English')),
    ('ru', ugettext('Russian')),
)

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    path.join(proj_dir, 'static/'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # 'debug_toolbar.middleware.DebugToolbarMiddleware',
)

ATOMIC_REQUESTS = True

INTERNAL_IPS = ('127.0.0.1',)

ROOT_URLCONF = 'vlevitorg.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'vlevitorg.wsgi.application'

LOCALE_PATHS = (path.join(proj_dir, 'locale'),)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 'APP_DIRS': True,
        'DIRS': [path.join(proj_dir, 'templates')],
        'OPTIONS': {
            'loaders': [
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                    'django.template.loaders.app_directories.Loader',
                ]),
            ],
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.i18n'
            ]
        }
    }
]

CONTENT_DIR = path.join(proj_dir, u'content')
BLOG_DIR = path.join(CONTENT_DIR, u'blog')
PAGES_DIR = path.join(CONTENT_DIR, u'pages')

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    # 'django.contrib.admindocs',
    'django.contrib.sitemaps',
    'django_comments',
    'threadedcomments',
    'endless_pagination',
    'raven.contrib.django.raven_compat',
    'vlblog',
    # 'debug_toolbar',
)

COMMENTS_APP = 'threadedcomments'

GPLUS_EXPORT = False
GPLUS_CREDENTIALS_FILE = path.join(proj_dir, 'credentials.json')

# DEBUG_TOOLBAR_PANELS = (
#     'debug_toolbar.panels.version.VersionDebugPanel',
#     'debug_toolbar.panels.timer.TimerDebugPanel',
#     'debug_toolbar.panels.profiling.ProfilingDebugPanel',
#     # 'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
#     'debug_toolbar.panels.headers.HeaderDebugPanel',
#     'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
#     'debug_toolbar.panels.sql.SQLDebugPanel',
#     'debug_toolbar.panels.template.TemplateDebugPanel',
#     'debug_toolbar.panels.signals.SignalDebugPanel',
#     # 'debug_toolbar.panels.logger.LoggingPanel',
# )

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s,%(lineno)d: %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'django.utils.log.NullHandler',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
            'stream': sys.stdout,
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler',
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['console', 'mail_admins'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'vlblog': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': True,
        },
        # 'django.db': {
        #     'handlers': ['console'],
        #     'level': 'DEBUG'
        # },
    }
}

from .local_settings import *


text:
Aker History
============

3.1.0
-----

- Added: Aker::Authorities::Static#valid_credentials! now can set any user
  attribute, including portal and group memberships.  (#25)

- Fixed: The form mode now sets proper Content-Type headers for HTML pages and
  their stylesheets.

- Changed: Aker::Authorities::Static#load! now raises on invalid user
  attributes.

- Fixed: Test suite now passes on ActiveSupport 4.0.0 and Ruby 2.0. (#31)

3.0.4
-----

- Added: The LDAP authority now implements `#amplify!`. (#21)

- Fixed: Documentation for `Aker::Cas::ServiceMode` referenced
  incorrect parameter names.

- Verified compatibility with ActiveSupport 3.1. (ActiveSupport 3.2 seems to
  work also, but is incompatible with part of the test infrastructure.) (#17)

3.0.3
-----

- Added: search_domain configuration option to LDAP authority. (#15)
  This new option is mandatory; the lack of this option in prior
  versions of the authority meant that they would not work with LDAP
  servers other than Northwestern's.

3.0.2
-----

- Added missing LICENSE file. Aker is made available under the MIT
  license. (#9)

- Fixed: `Aker::Cas::Middleware::TicketRemover` now sets its response's
  Content-Type.  `TicketRemover` also now returns a link to the cleaned URI,
  following recommendations set forth in RFC 2616.  (#10)

- Added: `Aker::User#permit?` accepts an `:affiliate_ids` option. (#11)

3.0.1
-----

- Fixed: with AS3, using `active_support/core_ext` requires the i18n
  gem, so add a dependency on it (#5).

3.0.0
-----

- First open-source version.

- Project renamed from "Bcsec" (short for Bioinformatics Core
  security) to "Aker" (ancient Egyptian god of the horizon).

- Bcsec contained several authorities which were specific to NUBIC;
  those have been removed and purged from the git history for the
  project.

- Added :custom_form mode (#1).

Bcsec History
=============

This is the history for the parts of Bcsec which remain in
Aker. Versions that only included changes to code which has been
removed from the open source version have been removed.

2.2.0
-----

- Introduced the concept of "configuration slices" so that extensions
  may add default configuration values. (#5875)

- Introduced mode registration and authority aliases so that named
  modes and authorities can have arbitrary class names. (#5875)

- Introduced the ability to configure rack middleware to be installed
  relative to bcsec (outside of modes). (#5875)

- Bcsec now has a 30 minute session timeout.  (#5156)

- It is now possible to customize the login and logout pages when using the
  `form` mode.  (#5469)

- Added a generic LDAP authority. (#5876)

- Send a permanent redirect after a successful CAS authentication in
  order to prevent the service ticket from showing up in the user's
  browsing history. (#2725)

- Extract and expose the method for determining the CAS service URL
  for a particular request. (See `Bcsec::Cas::ServiceUrl`.)

- Updated JRuby tested version to 1.6.2.

2.1.0
-----

- ActiveRecord / ActiveSupport 3 compatibility. (#2804)

- Fixed: user information is no longer saved in the session in
  non-interactive modes.  (#2757)

2.0.5
-----

- Updated tested platforms to JRuby 1.5.3 and Ruby 1.9.2.  (MRI 1.8.7
  in the specific form of REE 2010.02 remains the same.)

2.0.4
-----

- Changed: the #find_users method on the authorities interface now
  accepts one or more separate criteria.  The separate criteria are
  joined using a logical OR.  All the built-in authorities have been
  updated to support this; custom authorities may need to be updated
  as well.  (#4027)

- Added: `Bcsec::Authorities::Static#load!` will now load arbitrary
  `Bcsec::User` attributes from the YAML file, not just the username,
  password, and authorization information. (#4297)

- Changed: Depend on net-ldap 0.1.1 instead of ruby-net-ldap 0.0.4.
  This new version of the net/ldap library is backwards compatible,
  interface-wise, but it trades 1.8.6- support for 1.9+ support.

2.0.3
-----

- Fixed: static authority now allows different users to have the same
  password. (#4068)

2.0.1
-----

- Added `Bcsec::Authorities::AutomaticAccess`.

2.0.0
-----

- Complete rewrite: better architecture (no sole singletons); rack
  support; better RESTful API authentication support; support for MRI
  1.8.7, JRuby, and YARV 1.9.1; and much more.

1.6.1
-----

- Correct MockAuthenticator-authorized users so that they reflect the
  appropriate group memberships when logging in with CAS (bug #2221)

- Prevent nil dereference in User#in_group? when the user has no groups at all

1.6.0
-----

- Fix nil-sensitivity bug in Bcsec.use_cas (#1994)

- Remove explicit `gem` invocations from library code

- Make minor changes to allow bcsec to run under jruby 1.4.0

1.5.2
-----

- Modify build layout a bit so that the source directory can be used with
  bundler's :path option in sowsear

1.5.0
-----

- Update to use open source versions of bcdatabase and
  schema_qualified_tables.

1.4.8
-----

- Configuration from use_cas now propagates to RailsCasFilter.

1.4.0
-----

- Allow CAS configuration parameters to be passed to use_cas.
  These parameters are passed directly to CASClient::Client; see
  http://rubycas-client.rubyforge.org/ for configuration details.
  These parameters override central configuration.

1.3.0
-----

- Dev: support deploy:tag from git-svn clones

1.2.6
-----

- Added Bcsec::AuthenticateOnlyAuthenticator for when you only need to
  authenticate. It responds to allow_access? and always returns true.

- Added ability to add authenticators with may_access? method only.

- Added rspec-rails version to use when running specs.

1.2.2
-----

- Correct _dependency_ definitions in gemspec.  (Was using _requirements_,
  which are informational only.)  `gem install bcsec` will now install all
  dependent gems.

1.2.1
-----

- Clear the effects of use_cas in Bcsec::Configurator#clear

1.2.0
-----

- Add Bcsec::portal_set? and similar to allow querying whether certain
  config attributes are set without throwing an exception when they aren't.

- Add adapter code in rspec_helper.rb so that rspec-rails can be used as a gem.

1.1.0
-----

- Added publicly-accessible method Bcsec#amplify! to provide bcsec consumers
  with the ability to manually invoke group data retrieval.

1.0.1
-----

- Fix issue when having multiple authenticors and the first one returns no groups

1.0.0
-----

- A user's security groups are cached in the current user object in the
  session.

- In group checks are handled in memory instead of hitting the database every
  time.

- Added dependency on RubyTree gem

0.1.1
-----

- Fix issue where Bcsec::CentralAuthenticationParameters would sometimes not be
  automatically resolved by applications using ActiveSupport's dependency
  loader.

0.1.0
-----

- Add CAS support

- Add MockAuthenticator#load_credentials! to support loading test credentials
  from a file.

0.0.2
-----

- Adapt deploy task to be multi-developer friendly

- Add separate uninstall task to return to published version

0.0.1
-----

- Fix rake tasks for deploy, local install

- Integrate ci_reporter

- Add rudimentary environment support in order to build in hudson

- Made site affiliate portal foreign key explicit

0.0.0
-----

- Extract non-rails-specific bcsec elements from bcsec engine.

- Convert test/unit tests moved from bcsec plugin into rspec specs.  (Shallow
  conversion only so far.)


text:
package com.github.dynamicextensionsalfresco.osgi;

import org.springframework.context.ApplicationContext;

/**
 * Holds constants for well-known names of beans in the OSGI child {@link ApplicationContext}.
 *
 * @author Laurens Fridael
 *
 */
class BeanNames {

	public static final String CONTAINER_FRAMEWORK = "osgi.container.Framework";

	public static final String CONTAINER_FRAMEWORK_MANAGER = "osgi.container.FrameworkManager";

	/**
	 * Constructor made private to prevent instantiation and subclassing.
	 */
	private BeanNames() {
	}
}


text:
import argparse
import importlib

parser = argparse.ArgumentParser( description = 'Input Arguments' )
parser.add_argument( 'inputs' , nargs = 2 )
parser.add_argument( '--load' , dest = 'load' , default = None )
parser.add_argument( '--save' , dest = 'save' , default = [ None ] , nargs = '*' )
parser.add_argument( '--epis' , dest = 'epis' , default = 1e9 )
parser.add_argument( '--run'  , dest = 'run'  , action = 'store_true' )
args = parser.parse_args()

source_string , player_string = args.inputs
source_module = importlib.import_module( 'sources.' + source_string )
player_module = importlib.import_module( 'players.' + player_string )

source = getattr( source_module , source_string )()
player = getattr( player_module , player_string )()
player.parse_args( args )

obsv = source.start()
state = player.start( source , obsv )

episode , n_episodes = 0 , int( args.epis )
while episode < n_episodes:

    actn = player.act( state )                                 # Choose Next Action
    obsv , rewd , done = source.move( actn )                   # Run Next Action On Source
    state = player.learn( state , obsv , actn , rewd , done, episode )  # Learn From This Action

    source.verbose( episode , rewd , done ) # Source Text Output
    player.verbose( episode , rewd , done ) # Player Text Output

    if done: # If Game Is Over
        obsv = source.start()
        state = player.restart( obsv )
        episode += 1


text:
using SuaveControls.MaterialForms;
using SuaveControls.MaterialForms.iOS.Renderers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(BorderlessEditor), typeof(BorderlessEditorRenderer))]
namespace SuaveControls.MaterialForms.iOS.Renderers
{
    public class BorderlessEditorRenderer : EditorRenderer
    {
        public static void Init() { }
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            Control.Layer.BorderWidth = 0;
        }
    }
}


text:
<?php

namespace Oip\MszeBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class OipMszeBundle extends Bundle
{
}


text:
Scene* Failure::createScene(int row){
	auto scene = Scene::create();
	auto layer = Failure::create();
	scene->addChild(layer);

	auto rabbit = Sprite::create();
	rabbit->setPosition(Point(LENGTH_OF_SIDE*WIDTH, LENGTH_OF_SIDE*(row - 0.5f)));
	layer->bindSprite(rabbit);

	auto animate = [&](int frameNumber, Value pngName){
		Vector<SpriteFrame*> frameVec;

		for (int i = 1; i <= frameNumber; i++){
			frameVec.pushBack(SpriteFrame::create(StringUtils::format("%s%d.png", pngName.asString().c_str(), i),
				Rect(0, 0, 100, 100)));
		}

		auto animation = Animation::createWithSpriteFrames(frameVec);
		animation->setLoops(-1);
		animation->setDelayPerUnit(INTERVAL_TIME);

		auto action = Animate::create(animation);
		return action;
	};
	rabbit->runAction(animate(9, Value("RabbitMove")));

	auto moveTo = MoveTo::create(4.0f, Point(LENGTH_OF_SIDE*8.0f, LENGTH_OF_SIDE*4.0f));
	auto callFunc = CallFunc::create([&](){
		Director::getInstance()->replaceScene(TransitionFade::create(2.0f, AnotherFailure::createScene()));
	});
	auto actions = Sequence::create(moveTo, callFunc, NULL);
	rabbit->runAction(actions);

	return scene;
}

void Failure::bindSprite(Sprite* sprite){
	rabbit = sprite;
	this->addChild(rabbit);
}

bool Failure::init(){
	if (!Layer::init())
	{
		return false;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();

	auto background = Sprite::create("mapfinal.png");
	background->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
	this->addChild(background, 0);

	return true;
}


text:
package org.frameworkset.spi.assemble;

/**
 *
Description: 对加载的属性值进行拦截处理,用处理后的值替换原来的值,常用于对加密数据的解密处理

 *

 *
Copyright (c) 2020

 * @Date 2022/4/18
 * @author biaoping.yin
 * @version 1.0
 */
public class PropertyContext {
	/**
	 * 属性名称 如果value是复杂对象,那么property可能为空,那么只需要处理value即可
	 */
	private Object property;
	/**
	 * 属性值
	 */
	private Object value;

	public Object getProperty() {
		return property;
	}

	public void setProperty(Object property) {
		this.property = property;
	}

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}
	@Override
	public String toString(){

		if(property != null) {
			StringBuilder ret = new StringBuilder();
			ret.append(property).append("=").append(value);
			return ret.toString();
		}
		else
			return String.valueOf(value);

	}
}


text:
'use strict';
/*jshint asi:true */

var sectionize = require('../lib/sectionize')

function linenos (lines) {
  return lines
    .filter(function(_, idx) { return idx > 0; })
    .map(function (line, idx) {
      return ++idx + ': ' + line;
    })
    .join(' | ');
}

function printCommaFirst (items) {
  return items.forEach(
    function (item, idx) {
      var comma = idx === 0 ? ' ' : ',';
      console.log('%s \'%s\'', comma, item)
    });
}

function nameParent (statement) {
    if (!statement) return undefined;
    var parent = statement.parent;

    if (parent.id) return parent.id.name;
    if (parent.type) return parent.type;

    return undefined;
}

function sectionizeAndNameParent(code) {
  return sectionize(code).map(nameParent);
}

function locate(statement) {
  return statement && statement.loc ? statement.loc.start.line + ':' + statement.loc.end.line : undefined;
}

function sectionizeAndLocate(code) {
  return sectionize(code).map(locate);
}

module.exports = {
    linenos                 :  linenos
  , printCommaFirst         :  printCommaFirst
  , nameParent              :  nameParent
  , sectionizeAndNameParent :  sectionizeAndNameParent
  , locate                  :  locate
  , sectionizeAndLocate     :  sectionizeAndLocate
};


text:
package nate.reading;

import java.util.LinkedList;
import java.util.List;

/**
 * An object that holds a list of names or descriptions that represent
 * this entity.  There is also a function to ask if a description matches
 * one for this entity.
 */
public class MUCEntity {
  String _templateType; // The type of MUC template (e.g. kidnap, bombing)
  String _slotType; // The MUC slot name.
  List<String> _mentions = null;
  boolean _optional = false; // If true, this entity is from an optional template.

  public MUCEntity(String templateType) {
    _templateType = templateType;
  }

  public boolean isOptional() {
    return _optional;
  }

  public void setOptional(boolean opt) {
    _optional = opt;
  }

  public void addMention(String mention) {
    if( _mentions == null )
      _mentions = new LinkedList<String>();
    _mentions.add(mention);
  }

  public List<String> getMentions() {
    return _mentions;
  }

  public String getTemplateType() { return _templateType; }

  public boolean equals(Object obj) {
    if( this == obj ) return true;
    if( !(obj instanceof MUCEntity) ) return false;
    MUCEntity other = (MUCEntity)obj;

    if( other.getMentions().size() != _mentions.size() )
      return false;

    for( String mention : other.getMentions() ) {
      if( !this._mentions.contains(mention) )
        return false;
    }
    return true;
  }

  public void setType(String t) { _slotType = t; }
  public String type() { return _slotType; }

  public String toString() {
    String str = null;
    if( _mentions != null ) {
      for( String mention : _mentions ) {
        if( str == null ) str = mention;
        else str += " -- " + mention;
      }
      if( _optional ) str += "(opt)";
    }
    return str;
  }
}


text:
//
// Copyright (c) Microsoft Corporation.    All rights reserved.
//

//#define ALLOW_PAUSE

namespace Microsoft.CortexM3OnCMSISCore
{
    using Microsoft.Zelig.Runtime.TargetPlatform.ARMv7;

    using RT    = Microsoft.Zelig.Runtime;
    using CMSIS = Microsoft.DeviceModels.Chipset.CortexM;
    using LLOS  = Zelig.LlilumOSAbstraction.HAL;

    public abstract class Peripherals : RT.Peripherals
    {

        //
        // State
        //

        //
        // Helper Methods
        //

        public override void Initialize()
        {
            RT.BugCheck.AssertInterruptsOff();

            //
            // Faults, never disabled
            //
            CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.HardFault_IRQn       , ProcessorARMv7M.c_Priority__NeverDisabled );
            CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.MemoryManagement_IRQn, ProcessorARMv7M.c_Priority__NeverDisabled );
            CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.BusFault_IRQn        , ProcessorARMv7M.c_Priority__NeverDisabled );
            CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.UsageFault_IRQn      , ProcessorARMv7M.c_Priority__NeverDisabled );

            //
            // System exceptions
            //
            CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.SVCall_IRQn , ProcessorARMv7M.c_Priority__SVCCall );
            CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.SysTick_IRQn, ProcessorARMv7M.c_Priority__SysTick );
            CMSIS.NVIC.SetPriority( (int)ProcessorARMv7M.IRQn_Type.PendSV_IRQn , ProcessorARMv7M.c_Priority__PendSV );
        }

        public override void Activate()
        {
            CMSIS.Drivers.InterruptController.Instance.Initialize();
            CMSIS.Drivers.ContextSwitchTimer.Instance.Initialize();
        }

        public override void EnableInterrupt( uint index )
        {
        }

        public override void DisableInterrupt( uint index )
        {
        }

        public override void CauseInterrupt()
        {
            ProcessorARMv7M.CompleteContextSwitch( );
            //Drivers.InterruptController.Instance.CauseInterrupt( );
        }

        public override void ContinueUnderNormalInterrupt(Continuation dlg)
        {
            Drivers.InterruptController.Instance.ContinueUnderNormalInterrupt(dlg);
        }

        public override void WaitForInterrupt()
        {

            while (true)
            {
                ProcessorARMv7M.WaitForEvent( );
            }

            //ProcessorARMv7M.InitiateContextSwitch( );
            //while(true) ;
        }

        public override void ProcessInterrupt()
        {
            using (RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = RT.ThreadManager.InstallInterruptThread())
            {
                Drivers.InterruptController.Instance.ProcessInterrupt();
            }
        }

        [RT.MemoryRequirements(RT.MemoryAttributes.RAM)]
        public override void ProcessFastInterrupt()
        {
            using (RT.SmartHandles.SwapCurrentThreadUnderInterrupt hnd = RT.ThreadManager.InstallFastInterruptThread())
            {
                Drivers.InterruptController.Instance.ProcessFastInterrupt();
            }
        }

        public override ulong GetPerformanceCounterFrequency()
        {
            return LLOS.Clock.LLOS_CLOCK_GetPerformanceCounterFrequency();
        }

        [RT.Inline]
        [RT.DisableNullChecks()]
        public override uint ReadPerformanceCounter()
        {
            return (uint)LLOS.Clock.LLOS_CLOCK_GetPerformanceCounter();
        }
    }
}


text:
package org.openbaton.vnfm.interfaces.state;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.openbaton.catalogue.api.DeployNSRBody;
import org.openbaton.catalogue.mano.descriptor.NetworkServiceDescriptor;
import org.openbaton.catalogue.mano.descriptor.VirtualNetworkFunctionDescriptor;
import org.openbaton.catalogue.mano.record.NetworkServiceRecord;
import org.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord;
import org.openbaton.catalogue.nfvo.messages.Interfaces.NFVMessage;
import org.openbaton.exceptions.BadFormatException;
import org.openbaton.exceptions.NotFoundException;
import org.springframework.scheduling.annotation.Async;

/** Created by lto on 29.05.17. */
public interface VnfStateHandler {
  Future<Void> handleVNF(
      NetworkServiceDescriptor networkServiceDescriptor,
      NetworkServiceRecord networkServiceRecord,
      DeployNSRBody body,
      Map<String, Set<String>> vduVimInstances,
      VirtualNetworkFunctionDescriptor vnfd,
      String monitoringIp)
      throws NotFoundException, BadFormatException, ExecutionException, InterruptedException;

  @Async
  Future<NFVMessage> executeAction(Future<NFVMessage> nfvMessage)
      throws ExecutionException, InterruptedException;

  @Async
  Future<NFVMessage> executeAction(NFVMessage nfvMessage);

  void terminate(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord);

  @Async
  Future<Void> sendMessageToVNFR(
      VirtualNetworkFunctionRecord virtualNetworkFunctionRecordDest, NFVMessage nfvMessage)
      throws NotFoundException, BadFormatException, ExecutionException, InterruptedException;
}