text:
require_relative 'base'

module Eventick
  class Event < Base
    resource "events/:id"

    attr_accessor :id, :start_at, :title, :tickets, :venue, :slug
    attr_reader :attendees, :all

    # constructors
    def initialize(args={})
      links = args.delete('links')
      args.each do |key, value|
        self.public_send("#{key}=", value)
      end

      self.tickets = links['tickets'].map { |o| Ticket.new(o) } if links
    end

    # class methods
    def self.all
      events_response = Eventick.get path
      events_response['events'].map { |event_response| self.new event_response }
    end

    # class methods
    def self.find_by_id(id)
      events_response = Eventick.get path({ id: id })
      params = events_response['events'].first
      self.new params unless params.empty?
    end

    # instance methods
    def attendees(reload = false)
      if reload || @attendees.nil?
        @attendees = Attendee.all self
      end

      @attendees
    end

    private
    def self.auth_token
      { :auth_token => Eventick.auth_token }
    end
  end
end


text:
app.factory('titleService', function () {
  return {
    title: function () {
      if (arguments.length > 0) {
        document.title = arguments[0];
      }
      return document.title;
    }
  };

});

redpajama_set_name: RedPajamaGithub


text:
The goal of Staticless is to provide a simplified flow for viewing markdown wikis in GitLab similar to GitLab pages but without the need to generate static web pages using builds combined with deploys. Instead Staticless relies on the GitLab API to retrieve pages.

The required [GitLab API](https://docs.gitlab.com/ce/api/wikis.html) was added in GitLab 10.0, Staticless will therefore not work with versions before GitLab 10.0.

**Disclaimer: Staticless is still under development. In its current state bugs, issues, and sudden changes may occur.**

## Running Staticless
For now the only supported way of using Staticless is by using the provided [Docker container](https://store.docker.com/community/images/tellios/staticless). More ways may be added and documented in the future.

### Configuring Staticless
Configurations can be applied using configuration files using the following paths:

1. Working directory `staticless.json` file
2. `Application directory/config/staticless.json` file

#### Configuration properties

An example of this is the JSON configuration here:

```json
{
    "object": {
        "property": "value"
    }
}
```

which is equivalent to the argument `--object.property value` and the environment variable `OBJECT_PROPERTY=value`.

##### Available configuration properties

| Property            | Type     | Description                                                                  |
| ------------------- | -------- | ---------------------------------------------------------------------------- |
| frontend.title      | String   | Title displayed in the web UI.                                               |
| server.address      | String   | Host name or IP address the server will listen on, defaults to `0.0.0.0`.    |
| server.port         | Number   | Ports the server will listen on, defaults to `8080`.                         |
| cache.time          | Number   | Minutes to cache gitlab related items. `0` will disable caching.             |
| sources             | Array    | The available wikis as an array.                                             |
| sources[i].name     | String   | The name of the wiki, used to identify the wiki to users.                    |
| sources[i].homeslug | String   | The wiki slug displayed by default when no page has been selected.           |
| sources[i].apitoken | String   | Token used to authenticate with the GitLab API.                              |
| sources[i].url      | String   | Url to the GitLab instance used, for GitLab.com it is https://gitlab.com/.   |
| sources[i].projectid| Number   | The ID of the GitLab project which contains the WIKI.                        |

### Using Docker
When using docker, both the `server.address` and `server.port` configurations will always be set to their defaults. Changing the port and listener address is instead managed by exposing the container on different ports using docker port mapping.

Start a container instance of Staticless by running the following `docker run` command:

```shell
docker run \
  -d \
  -v "path/to/staticless/config/folder:/opt/app/config" \
  tellios/staticless
```


text:
<?php namespace Operation;

require_once "outputs/Outputs.php";
use Output\Outputs;
use DBConnection;
use AccountInformationException;
use BillingException;
use ServiceAuthentication;

class BillPayment{
    private $acctNum;

    public function __construct(string $acctNum){
        $this->acctNum = $acctNum;
    }

    public function pay(int $billType){
      $output = new Outputs();
      try{
        if ($billType >= 0 && $billType <= 2){
          $billOutput = $this->getBill($billType);
          $chargeAmount = $billOutput->billAmount;
          if($chargeAmount == 0){
            $output->errorMessage = "คุณไม่มียอดค้างชำระสำหรับบิลนี้แล้ว";
          }
          elseif($chargeAmount < 0){
            $output->errorMessage = "พบข้อผิดพลาดบนฐานข้อมูล โปรดติดต่อผู้ดูแลระบบ";
          }
          else{
            $acctInfo = ServiceAuthentication::accountAuthenticationProvider($this->acctNum);
            $newBalance = $acctInfo["accBalance"]-$chargeAmount;
            if($newBalance >= 0){
              DBConnection::saveTransaction($this->acctNum,$newBalance);
              DBConnection::clearCharge($this->acctNum,$billType);

              $output->accountNumber = $this->acctNum;
              $output->accountName = $acctInfo["accName"];
              $output->accountBalance = $newBalance;
            }
            else{
              $output->errorMessage = "ขออภัย, เงินในบัญชีของคุณไม่พอ";
            }
          }

        }
        else{
          $output->errorMessage = "ไม่มีรายการชำระเงินดังกล่าวในระบบ!";
        }
      }
      catch(AccountInformationException $e){
        $output->errMessage = $e->getMessage();
      }
      catch(BillingException $e){
        $output->errMessage = $e->getMessage();
      }

      return $output;
    }
    public function getBill(int $billType){
      $output = new Outputs();
      if ($billType >= 0 && $billType <= 2){
        try{
          $output->billAmount = DBConnection::getCharge($this->acctNum,$billType);
        }
        catch(AccountInformationException $e){
          $output->errMessage = $e->getMessage();
        }
        catch(BillingException $e){
          $output->errMessage = $e->getMessage();
        }
        return $output;
      }
      else{
        $output->errorMessage = "ไม่มีรายการชำระเงินดังกล่าวในระบบ!";
      }
    }
}


text:
package org.wikidata.wdtk.rdf.values;

import org.openrdf.model.Resource;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.rio.RDFHandlerException;
import org.wikidata.wdtk.datamodel.interfaces.DatatypeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.datamodel.interfaces.QuantityValue;
import org.wikidata.wdtk.rdf.OwlDeclarationBuffer;
import org.wikidata.wdtk.rdf.PropertyRegister;
import org.wikidata.wdtk.rdf.RdfWriter;
import org.wikidata.wdtk.rdf.Vocabulary;

public class QuantityValueConverter extends
		BufferedValueConverter<QuantityValue> {

	public QuantityValueConverter(RdfWriter rdfWriter,
			PropertyRegister propertyRegister,
			OwlDeclarationBuffer rdfConversionBuffer) {
		super(rdfWriter, propertyRegister, rdfConversionBuffer);
	}

	@Override
	public Value getRdfValue(QuantityValue value,
			PropertyIdValue propertyIdValue, boolean simple) {
		String datatype = this.propertyRegister
				.setPropertyTypeFromQuantityValue(propertyIdValue, value);

		switch (datatype) {
		case DatatypeIdValue.DT_QUANTITY:
			if (simple) {
				this.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);
				return this.rdfWriter.getLiteral(value.getNumericValue()
						.toString(), RdfWriter.XSD_DECIMAL);
			} else {
				URI valueUri = this.rdfWriter.getUri(Vocabulary
						.getQuantityValueUri(value,
								this.propertyRegister.getUriPrefix()));

				this.rdfConversionBuffer.addObjectProperty(propertyIdValue);
				addValue(value, valueUri);

				return valueUri;
			}
		default:
			logIncompatibleValueError(propertyIdValue, datatype, "quantity");
			return null;
		}
	}

	@Override
	public void writeValue(QuantityValue value, Resource resource)
			throws RDFHandlerException {
		this.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE,
				RdfWriter.WB_QUANTITY_VALUE);
		this.rdfWriter.writeTripleLiteralObject(resource,
				RdfWriter.WB_NUMERIC_VALUE, value.getNumericValue().toString(),
				RdfWriter.XSD_DECIMAL);
		this.rdfWriter.writeTripleLiteralObject(resource,
				RdfWriter.WB_LOWER_BOUND, value.getLowerBound().toString(),
				RdfWriter.XSD_DECIMAL);
		this.rdfWriter.writeTripleLiteralObject(resource,
				RdfWriter.WB_UPPER_BOUND, value.getUpperBound().toString(),
				RdfWriter.XSD_DECIMAL);
	}

}


text:
<?php

namespace Zhmi\ExpertSender\Request\Get;

use Zhmi\ExpertSender\Request;

class Templates extends Request
{
    protected $endPoint = '/Api/Templates';
    protected $responseEntity = 'Zhmi\\ExpertSender\\Response\\TemplatesType';
    function __construct($type = null)
    {
        if ($type !== null)
        {
            $this->urlParams['type'] = $type;
        }
    }

}


text:
layout: post
title: Automaticaly Updating PID for Nagios
---

If you are using nagios to monitor your applications in production, you might have faced the need to regularly configure Nagios with constantly changing PIDs.

We used nagios for monitoring and everytime application servers like tomcat are restarted, nagios needs to be re-configured with new PID. This involves a bit of manual intervention every time and needs the same steps to be followed for re-configuration. Hence why not automate?

Here are the steps that would work to automatically perform this task for tomcat :

### Configuring Tomcat to persist PID ###

*  Update the setenv.sh add these two lines at the beginning of the script
   {% highlight bash %}
   export CATALINA_BASE="/opt/apache-tomcat-7.0.68"
   CATALINA_PID="$CATALINA_BASE/bin/catalina.pid"
   {% endhighlight %}

   Make sure CATALINA_BASE is the directory where tomcat is present and verify that CATALINA_BASE is reachable.

   Sample :

   {% highlight bash %}
   $ cat setenv.sh
   export CATALINA_BASE="/opt/apache-tomcat-7.0.68"
   CATALINA_PID="$CATALINA_BASE/bin/catalina.pid"
   export CATALINA_OPTS="$CATALINA_OPTS -Xms12288m"
   export CATALINA_OPTS="$CATALINA_OPTS -Xmx12288m"
   export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=1024m"
   export CATALINA_OPTS="$CATALINA_OPTS -XX:+HeapDumpOnOutOfMemoryError"
   $ ./startup.sh
   Using CATALINA_BASE:   /opt/apache-tomcat-7.0.68
   Using CATALINA_HOME:   /opt/apache-tomcat-7.0.68
   Using CATALINA_TMPDIR: /opt/apache-tomcat-7.0.68/temp
   Using JRE_HOME:        /usr
   Using CLASSPATH:       /opt/apache-tomcat-7.0.68/bin/bootstrap.jar:
                          /opt/apache-tomcat-7.0.68/bin/tomcat-juli.jar
   Using CATALINA_PID:    /opt/apache-tomcat-7.0.68/bin/catalina.pid
   Tomcat started.
   $ cat catalina.pid
   5340
   {% endhighlight %}

### Setting up password-less SSH Login  ###

In order to let nagios periodically poll using SSH application servers to check for updated PID, it would need to configure SSH Key-Based Authentication on nagios server. The detailed steps are listed [here](http://www.tecmint.com/ssh-passwordless-login-using-ssh-keygen-in-5-easy-steps/)

### Updating Nagios Configuration ###

Nagios configuration files are structured file where each block is easily parseable. [Pynag](https://github.com/pynag/pynag) has python modules and utilities for reading and updating Nagios configuration. Following are the steps that a shell script needs to achieve :

* Declare all hosts, PID paths for which nagios configuration has to be reloaded.
* Get the latest PID by SSHing to the host.
* Use Pynag to get the current PID
* Use Pynag to update the PID if PID has changed
* Reload nagios

Here is the crude shell script to do the above steps

{% highlight bash %}
#!/bin/bash

#Declare all hosts for which nagios configuration has to be updated
declare -A hosts
hosts=( ["localhost"]="127.0.0.1" )

#Declare all tomacat location/ script to get PID
declare -A tomcats
tomcats=( ["localhost"]="cat /opt/apache-tomcat-8.0.23/bin/catalina.pid" )

#Start updating the nagios configuration

for key in ${!hosts[@]}; do
    latest_pid=$(ssh root@${hosts[${key}]} ${tomcats[${key}]})
    check_command=$(pynag list check_command where object_type=service and \
    host_name="${key}" --cfg_file=../../tests/dataset01/nagios/nagios.cfg \
    --quiet)
    IFS='!' read -ra check_command_STRINGS <<< "$check_command"
    new_command=""
    delimiter="!"
    length=${#check_command_STRINGS[@]}
    for ((i=0;i<=$length;i++)); do
        if [ $i -eq 1 ];then
            new_command+="$latest_pid"$delimiter
            old_pid=${check_command_STRINGS[$i]}
        elif [ ! -z "${check_command_STRINGS[$i]}" -a \
		"${check_command_STRINGS[$i]}" != " " ]; then
            new_command+="${check_command_STRINGS[$i]}"$delimiter
        fi
    done
    new_check_command=${new_command%?}
    update_command=$(pynag update SET check_command=${new_check_command} \
    WHERE host_name="${key}" and object_type=service \
    --cfg_file=../../tests/dataset01/nagios/nagios.cfg --force)
    details_after_update=$(pynag list host_name check_command where \
    object_type=service and host_name="${key}" \
    --cfg_file=../../tests/dataset01/nagios/nagios.cfg --quiet)
    echo "$details_after_update"
done

#When updated, reload nagios
{% endhighlight %}

### Setting up cron job ###
The last step to automate would be to setup a cron job to execute this shell script periodically.


text:
A userscript for Roll20 that automatically switches the character in chat when clicking on a button on their character sheet

[Install from greasyfork.org](https://greasyfork.org/en/scripts/27024-roll20-character-switcher)

## Where does it work?

I tested it on Google Chrome, but since it's not using anything browser specific it should work with any normal browser, like Firefox, Opera, Google Chrome or Vivaldi after installing a monkey.
A monkey is a browserextension running userscripts, the three most likely relevant ones are Tampermonkey, Greasemonkey and Violent Monkey.


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:webflow="http://www.springframework.org/schema/webflow-config"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/webflow-config
           http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.3.xsd">

  <!-- Maps request paths to flows in the flowRegistry; e.g. a path of /hotels/booking looks for a flow with id "hotels/booking". -->
  <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
    <property name="order" value="1"/>
    <property name="flowRegistry" ref="flowRegistry"/>
  </bean>

  <!-- Dispatches requests mapped to flows to FlowHandler implementations -->
  <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
    <property name="flowExecutor" ref="flowExecutor"/>
  </bean>

  <!-- Executes flows: the entry point into the Spring Web Flow system -->
  <webflow:flow-executor id="flowExecutor">
  <!--
  <webflow:flow-execution-listeners>
    <webflow:listener ref="securityFlowExecutionListener" />
  </webflow:flow-execution-listeners>
  -->

  </webflow:flow-executor>

  <!-- The registry of executable flow definitions -->
  <webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices" base-path="/WEB-INF/flows">
    <webflow:flow-location-pattern value="/**/flow.xml"/>
  </webflow:flow-registry>

  <!-- Plugs in a custom creator for Web Flow views -->
  <webflow:flow-builder-services id="flowBuilderServices" view-factory-creator="mvcViewFactoryCreator"
                                 conversion-service="defaultConversionService"
                                 development="true" validator="validator"/>

  <!-- Configures Web Flow to use Tiles to create views for rendering; Tiles allows for applying consistent layouts to your views -->
  <bean id="mvcViewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
    <property name="viewResolvers">
      <list>
        <!--
        <ref bean="ajaxViewResolver" />
         -->

        <ref bean="viewResolver"/>
      </list>
    </property>
    <property name="useSpringBeanBinding" value="true"/>
  </bean>

  <!-- Bootstraps JSR-303 validation and exposes it through Spring's Validator interface -->
  <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

  <!-- Installs a listener to apply Spring Security authorities -->
  <!--
  <bean id="securityFlowExecutionListener" class="org.springframework.webflow.security.SecurityFlowExecutionListener" />
   -->

</beans>


text:
/**
 *
 */
package com.bar.foo.math;

/**
 * This class provides a square 3x3 matrix composed of floats as an alternative
 * to the JavaFX library. This class includes mathematical operations for
 * matrices and other constructs.
 *

 * Methods may return a reference to {@code this} or a reference to the
 * specified cache {@code Matrix3f}. It is highly recommended to pay
 * attention to the documentation of methods in this class.
 *

 *

 * This class additionally provides static matrices representing the zero and
 * identity matrices as a convenience. Note that if you plan to manipulate these
 * values, DO NOT MANIPULATE THESE VALUES! Instead, use
 * copies of them by calling the copy constructor, e.g.,
 * {@code new Matrix3f(Matrix3f.ZERO)} or by using them with the set operation,
 * e.g., {@code myMatrix.set(Matrix3f.IDENTITY)}.
 *

 *
 * @author Jordan Deyton
 *
 */
public class Matrix3f {

	/**
	 * The zero-matrix.
	 *

	 * DO NOT MANIPULATE THIS MATRIX! Instead, use a copy
	 * of it by calling the copy constructor, e.g.,
	 * {@code new Matrix3f(Matrix3f.ZERO)}.
	 *

	 */
	public static final Matrix3f ZERO = new Matrix3f();
	/**
	 * The identity-matrix.
	 *

	 * DO NOT MANIPULATE THIS MATRIX! Instead, use a copy
	 * of it by calling the copy constructor, e.g.,
	 * {@code new Matrix3f(Matrix3f.IDENTITY)}.
	 *

	 */
	public static final Matrix3f IDENTITY = new Matrix3f(1f, 0f, 0f, 0f, 1f,
			0f, 0f, 0f, 1f);

	/**
	 * First row, first element.
	 */
	public float m00;
	/**
	 * First row, second element.
	 */
	public float m01;
	/**
	 * First row, third element.
	 */
	public float m02;
	/**
	 * Second row, first element.
	 */
	public float m10;
	/**
	 * Second row, second element.
	 */
	public float m11;
	/**
	 * Second row, third element.
	 */
	public float m12;
	/**
	 * Third row, first element.
	 */
	public float m20;
	/**
	 * Third row, second element.
	 */
	public float m21;
	/**
	 * Third row, third element.
	 */
	public float m22;

	/**
	 * The default constructor. Creates a zero matrix.
	 */
	public Matrix3f() {
		// Zero out the values.
		m00 = m01 = m02 = 0f;
		m10 = m11 = m12 = 0f;
		m20 = m21 = m22 = 0f;
		return;
	}

	/**
	 * Creates a matrix with the specified elements. A value {@code mij}
	 * corresponds to the element in the ith row and jth column.
	 * Indexing starts at 0.
	 *
	 * @param m00
	 *            First row, first element.
	 * @param m01
	 *            First row, second element.
	 * @param m02
	 *            First row, third element.
	 * @param m10
	 *            Second row, first element.
	 * @param m11
	 *            Second row, second element.
	 * @param m12
	 *            Second row, third element.
	 * @param m20
	 *            Third row, first element.
	 * @param m21
	 *            Third row, second element.
	 * @param m22
	 *            Third row, third element.
	 */
	public Matrix3f(float m00, float m01, float m02, float m10, float m11,
			float m12, float m20, float m21, float m22) {
		this.m00 = m00;
		this.m01 = m01;
		this.m02 = m02;
		this.m10 = m10;
		this.m11 = m11;
		this.m12 = m12;
		this.m20 = m20;
		this.m21 = m21;
		this.m22 = m22;
		return;
	}

	/**
	 * Creates a matrix using the specified vectors to populate the matrix. Each
	 * vector corresponds to a row, e.g., the first vector's x, y, and z values
	 * make up the first row in the matrix.
	 *
	 * @param v0
	 *            The first row of float elements.
	 * @param v1
	 *            The second row of float elements.
	 * @param v2
	 *            The third row of float elements.
	 */
	public Matrix3f(Vector3f v0, Vector3f v1, Vector3f v2) {
		this(v0, v1, v2, true);
	}

	/**
	 * Creates a matrix using the specified vectors to populate the matrix. Each
	 * vector corresponds to either a row or a column in the matrix depending on
	 * the boolean argument.
	 *
	 * @param v0
	 *            The first row/column of float elements.
	 * @param v1
	 *            The second row/column of float elements.
	 * @param v2
	 *            The third row/column of float elements.
	 * @param rowVectors
	 *            If true, then each vector corresponds to a row
	 *            in the matrix (this is the same as calling
	 *            {@link #Matrix3f(Vector3f, Vector3f, Vector3f)}). If
	 *            false, then each vector corresponds to a column
	 *            in the matrix.
	 */
	public Matrix3f(Vector3f v0, Vector3f v1, Vector3f v2, boolean rowVectors) {
		if (rowVectors) {
			m00 = v0.x;
			m01 = v0.y;
			m02 = v0.z;
			m10 = v1.x;
			m11 = v1.y;
			m12 = v1.z;
			m20 = v2.x;
			m21 = v2.y;
			m22 = v2.z;
		} else {
			m00 = v0.x;
			m01 = v1.x;
			m02 = v2.x;
			m10 = v0.y;
			m11 = v1.y;
			m12 = v2.y;
			m20 = v0.z;
			m21 = v1.z;
			m22 = v2.z;
		}
		return;
	}

	/**
	 * A copy constructor. Creates a matrix with the same values as the
	 * specified matrix or zeroes if the matrix is null.
	 *
	 * @param matrix
	 *            The matrix to copy.
	 */
	public Matrix3f(Matrix3f matrix) {
		if (matrix != null) {
			m00 = matrix.m00;
			m01 = matrix.m01;
			m02 = matrix.m02;
			m10 = matrix.m10;
			m11 = matrix.m11;
			m12 = matrix.m12;
			m20 = matrix.m20;
			m21 = matrix.m21;
			m22 = matrix.m22;
		} else {
			// Zero out the values.
			m00 = m01 = m02 = 0f;
			m10 = m11 = m12 = 0f;
			m20 = m21 = m22 = 0f;
		}
		return;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object object) {
		boolean equals = (this == object);
		if (!equals && object instanceof Matrix3f) {
			Matrix3f matrix = (Matrix3f) object;
			equals = (Float.compare(m00, matrix.m00) == 0
					&& Float.compare(m01, matrix.m01) == 0
					&& Float.compare(m02, matrix.m02) == 0
					&& Float.compare(m10, matrix.m10) == 0
					&& Float.compare(m11, matrix.m11) == 0
					&& Float.compare(m12, matrix.m12) == 0
					&& Float.compare(m20, matrix.m20) == 0
					&& Float.compare(m21, matrix.m21) == 0 && Float.compare(
					m22, matrix.m22) == 0);
		}
		return equals;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		int hash = Float.hashCode(m00);
		hash = hash * 31 + Float.hashCode(m01);
		hash = hash * 31 + Float.hashCode(m02);
		hash = hash * 31 + Float.hashCode(m10);
		hash = hash * 31 + Float.hashCode(m11);
		hash = hash * 31 + Float.hashCode(m12);
		hash = hash * 31 + Float.hashCode(m20);
		hash = hash * 31 + Float.hashCode(m21);
		return hash * 31 + Float.hashCode(m22);
	}

	/**
	 * Sets the values of the matrix to the specified elements. A value
	 * {@code mij} corresponds to the element in the ith row and
	 * jth column. Indexing starts at 0.
	 *
	 * @param m00
	 *            First row, first element.
	 * @param m01
	 *            First row, second element.
	 * @param m02
	 *            First row, third element.
	 * @param m10
	 *            Second row, first element.
	 * @param m11
	 *            Second row, second element.
	 * @param m12
	 *            Second row, third element.
	 * @param m20
	 *            Third row, first element.
	 * @param m21
	 *            Third row, second element.
	 * @param m22
	 *            Third row, third element.
	 * @return A reference to this matrix.
	 */
	public Matrix3f set(float m00, float m01, float m02, float m10, float m11,
			float m12, float m20, float m21, float m22) {
		this.m00 = m00;
		this.m01 = m01;
		this.m02 = m02;
		this.m10 = m10;
		this.m11 = m11;
		this.m12 = m12;
		this.m20 = m20;
		this.m21 = m21;
		this.m22 = m22;
		return this;
	}

	/**
	 * Sets the values of the matrix to the same values in the given vectors.
	 * Each vector corresponds to a row, e.g., the first vector's x, y, and z
	 * values make up the first row in the matrix.
	 *
	 * @param v0
	 *            The first row of float elements.
	 * @param v1
	 *            The second row of float elements.
	 * @param v2
	 *            The third row of float elements.
	 * @return A reference to this matrix.
	 */
	public Matrix3f set(Vector3f v0, Vector3f v1, Vector3f v2) {
		return set(v0, v1, v2, true);
	}

	/**
	 * Sets the values of the matrix to the same values in the given vectors.
	 * Each vector corresponds to either a row or a column in the matrix
	 * depending on the boolean argument.
	 *
	 * @param v0
	 *            The first row/column of float elements.
	 * @param v1
	 *            The second row/column of float elements.
	 * @param v2
	 *            The third row/column of float elements.
	 * @param rowVectors
	 *            If true, then each vector corresponds to a row
	 *            in the matrix (this is the same as calling
	 *            {@link #set(Vector3f, Vector3f, Vector3f)}). If false,
	 *            then each vector corresponds to a column in the matrix.
	 * @return
	 */
	public Matrix3f set(Vector3f v0, Vector3f v1, Vector3f v2,
			boolean rowVectors) {
		if (rowVectors) {
			m00 = v0.x;
			m01 = v0.y;
			m02 = v0.z;
			m10 = v1.x;
			m11 = v1.y;
			m12 = v1.z;
			m20 = v2.x;
			m21 = v2.y;
			m22 = v2.z;
		} else {
			m00 = v0.x;
			m01 = v1.x;
			m02 = v2.x;
			m10 = v0.y;
			m11 = v1.y;
			m12 = v2.y;
			m20 = v0.z;
			m21 = v1.z;
			m22 = v2.z;
		}
		return this;
	}

	/**
	 * Sets the values of the matrix to the same values in the specified matrix.
	 *
	 * @param matrix
	 *            The matrix whose values will be copied.
	 * @return A reference to this matrix.
	 */
	public Matrix3f set(Matrix3f matrix) {
		m00 = matrix.m00;
		m01 = matrix.m01;
		m02 = matrix.m02;
		m10 = matrix.m10;
		m11 = matrix.m11;
		m12 = matrix.m12;
		m20 = matrix.m20;
		m21 = matrix.m21;
		m22 = matrix.m22;
		return this;
	}

	/**
	 * Sets the specified row of the matrix to the specified values.
	 *
	 * @param row
	 *            The row, indexed from 0 (values other than 0, 1, and 2 will be
	 *            ignored).
	 * @param x
	 *            The first element in the row.
	 * @param y
	 *            The second element in the row.
	 * @param z
	 *            The third element in the row.
	 * @return A reference to this matrix.
	 */
	public Matrix3f setRow(int row, float x, float y, float z) {
		if (row == 0) {
			m00 = x;
			m01 = y;
			m02 = z;
		} else if (row == 1) {
			m10 = x;
			m11 = y;
			m12 = z;
		} else if (row == 2) {
			m20 = x;
			m21 = y;
			m22 = z;
		}
		return this;
	}

	/**
	 * Sets the specified row of the matrix to the values stored in the
	 * specified vector.
	 *
	 * @param row
	 *            The row, indexed from 0 (values other than 0, 1, and 2 will be
	 *            ignored).
	 * @param vector
	 *            The x, y, and z of the vector will be the first, second, and
	 *            third elements in the row of the matrix.
	 * @return A reference to this matrix.
	 */
	public Matrix3f setRow(int row, Vector3f vector) {
		if (row == 0) {
			m00 = vector.x;
			m01 = vector.y;
			m02 = vector.z;
		} else if (row == 1) {
			m10 = vector.x;
			m11 = vector.y;
			m12 = vector.z;
		} else if (row == 2) {
			m20 = vector.x;
			m21 = vector.y;
			m22 = vector.z;
		}
		return this;
	}

	/**
	 * Sets the specified column of the matrix to the specified values.
	 *
	 * @param column
	 *            The column, indexed from 0 (values other than 0, 1, and 2 will
	 *            be ignored).
	 * @param x
	 *            The first element in the column.
	 * @param y
	 *            The second element in the column.
	 * @param z
	 *            The third element in the column.
	 * @return A reference to this matrix.
	 */
	public Matrix3f setColumn(int column, float x, float y, float z) {
		if (column == 0) {
			m00 = x;
			m10 = y;
			m20 = z;
		} else if (column == 1) {
			m01 = x;
			m11 = y;
			m21 = z;
		} else if (column == 2) {
			m02 = x;
			m12 = y;
			m22 = z;
		}
		return this;
	}

	/**
	 * Sets the specified row of the matrix to the values stored in the
	 * specified vector.
	 *
	 * @param column
	 *            The column, indexed from 0 (values other than 0, 1, and 2 will
	 *            be ignored).
	 * @param vector
	 *            The x, y, and z of the vector will be the first, second, and
	 *            third elements in the column of the matrix.
	 * @return A reference to this matrix.
	 */
	public Matrix3f setColumn(int column, Vector3f vector) {
		if (column == 0) {
			m00 = vector.x;
			m10 = vector.y;
			m20 = vector.z;
		} else if (column == 1) {
			m01 = vector.x;
			m11 = vector.y;
			m21 = vector.z;
		} else if (column == 2) {
			m02 = vector.x;
			m12 = vector.y;
			m22 = vector.z;
		}
		return this;
	}

	/**
	 * Sets the specified element to the specified value.
	 *

	 * Note: The values can be accessed directly by setting one of
	 * {@link #m00}, {@link #m01}, ... {@link #m22}. This method must resort to
	 * nested switches, so it is not terribly effecient. It is provided for
	 * convenience.
	 *

	 *
	 * @param row
	 *            The row of the element, either 0, 1, or 2.
	 * @param column
	 *            The column of the element, either 0, 1, or 2.
	 * @param value
	 *            The new value of the specified element.
	 * @return A reference to this matrix.
	 */
	public Matrix3f set(int row, int column, float value) {
		switch (row) {
		case 0:
			switch (column) {
			case 0:
				m00 = value;
				break;
			case 1:
				m01 = value;
				break;
			case 2:
				m02 = value;
				break;
			}
			break;
		case 1:
			switch (column) {
			case 0:
				m10 = value;
				break;
			case 1:
				m11 = value;
				break;
			case 2:
				m12 = value;
				break;
			}
			break;
		case 2:
			switch (column) {
			case 0:
				m20 = value;
				break;
			case 1:
				m21 = value;
				break;
			case 2:
				m22 = value;
				break;
			}
			break;
		}
		return this;
	}

	/**
	 * Multiplies this matrix by the given matrix and stores the result in
	 * this matrix.
	 *
	 * @param matrix
	 *            The matrix against which to multiply this one.
	 * @return A reference to this matrix.
	 */
	public Matrix3f multiply(Matrix3f matrix) {
		return multiply(matrix, this);
	}

	/**
	 * Multiplies this matrix by the given matrix and stores the result in the
	 * cache matrix.
	 *
	 * @param matrix
	 *            The matrix against which to multiply this one.
	 * @param cache
	 *            The matrix in which to store the computed values.
	 * @return A reference to the cache.
	 */
	public Matrix3f multiply(Matrix3f matrix, Matrix3f cache) {
		float p00 = m00 * matrix.m00 + m01 * matrix.m10 + m02 * matrix.m20;
		float p10 = m10 * matrix.m00 + m11 * matrix.m10 + m12 * matrix.m20;
		float p20 = m20 * matrix.m00 + m21 * matrix.m10 + m22 * matrix.m20;

		float p01 = m00 * matrix.m01 + m01 * matrix.m11 + m02 * matrix.m21;
		float p11 = m10 * matrix.m01 + m11 * matrix.m11 + m12 * matrix.m21;
		float p21 = m20 * matrix.m01 + m21 * matrix.m11 + m22 * matrix.m21;

		float p02 = m00 * matrix.m02 + m01 * matrix.m12 + m02 * matrix.m22;
		float p12 = m10 * matrix.m02 + m11 * matrix.m12 + m12 * matrix.m22;
		float p22 = m20 * matrix.m02 + m21 * matrix.m12 + m22 * matrix.m22;

		if (cache != null) {
			cache.set(p00, p01, p02, p10, p11, p12, p20, p21, p22);
		} else {
			cache = new Matrix3f(p00, p01, p02, p10, p11, p12, p20, p21, p22);
		}
		return cache;
	}

	/**
	 * Multiplies this matrix by the given vector and stores the result in a new
	 * vector.
	 *
	 * @param vector
	 *            The vector against which to multiply this matrix.
	 * @return A new vector containing the result.
	 */
	public Vector3f multiply(Vector3f vector) {
		return multiply(vector, null);
	}

	/**
	 * Multiplies this matrix by the given vector and stores the result in the
	 * cache vector.
	 *
	 * @param vector
	 *            The vector against which to multiply this matrix.
	 * @param cache
	 *            The vector in which to store the computed values.
	 * @return A reference to the cache.
	 */
	public Vector3f multiply(Vector3f vector, Vector3f cache) {
		float x = m00 * vector.x + m01 * vector.y + m02 * vector.z;
		float y = m10 * vector.x + m11 * vector.y + m12 * vector.z;
		float z = m20 * vector.x + m21 * vector.y + m22 * vector.z;

		if (cache != null) {
			cache.set(x, y, z);
		} else {
			cache = new Vector3f(x, y, z);
		}
		return cache;
	}

}


text:
using System;
using System.Drawing;
using System.Collections.Generic;
using Gtk;

using LynnaLib;

namespace LynnaLab
{
    [System.ComponentModel.ToolboxItem(true)]
    public class TilesetViewer : TileGridViewer
    {
        public Project Project {
            get {
                if (tileset == null)
                    return null;
                return tileset.Project;
            }
        }

        public Tileset Tileset
        {
            get { return tileset; }
        }

        protected override Bitmap Image {
            get {
                if (Tileset == null)
                    return null;
                return Tileset.GetFullCachedImage();
            }
        }

        Tileset tileset;

        public TilesetViewer() : base()
        {
            TileWidth = 16;
            TileHeight = 16;
            Width = 16;
            Height = 16;
            Selectable = true;
            SelectedIndex = 0;
        }

        public void SetTileset(Tileset t) {
            if (tileset != null)
                tileset.TileModifiedEvent -= ModifiedTileCallback;
            t.TileModifiedEvent += ModifiedTileCallback;

            tileset = t;

            tileset.LazyTileRedraw((f) => GLib.Idle.Add(new GLib.IdleHandler(f)));

            tileset.ResetAnimation();
            tileset.DrawAllTiles();

            this.QueueDraw();
        }

        void ModifiedTileCallback(object sender, int tile) {
            QueueDraw();
        }

        protected override bool OnButtonPressEvent(Gdk.EventButton ev)
        {
            // Insert button press handling code here.
            return base.OnButtonPressEvent(ev);
        }

        protected override void OnSizeAllocated(Gdk.Rectangle allocation)
        {
            base.OnSizeAllocated(allocation);
            // Insert layout code here.
        }
    }
}


text:
var crypto = require('crypto'),
    algorithm = 'aes-256-ctr',
    password = '1';
function HuffmanNode(weight,cha){
    this.weight = weight;
    this.cha = cha;
    this.leftchild = 0;
    this.rightchild = 0;
    this.parent = 0;
}
function FalseNode(weight,pos){
    this.weight = weight;
    this.pos = pos;
}
function chastr(strweight,strch){
    this.strweight = strweight;
    this.strch = strch;
}
function BuildHuffmanTree(weights,n){
    var Huffmantreefalse = [];
    var Huffmantreetrue = [];
    //n = weights.length;
    var m = 2*n - 1;
    var count = 0;
    /*初始化*/
    for (var i = 0; i < n; i++) {
        Huffmantreefalse[i] = new FalseNode(weights[i].strweight,i);
        Huffmantreetrue[i] = new HuffmanNode(weights[i].strweight,weights[i].strch);
    }
    for (; i < m; i++) {
        Huffmantreefalse[i] = new FalseNode(Infinity,i);
        Huffmantreetrue[i] = new HuffmanNode(0,0);
    }
    for(i = n;i < m;i++){
        /*Huffmantreefalse.weight.sort(ascOrder);*/
        for(var j = 0; j < Huffmantreefalse.length-1; j++){
            for(var k = j; k < Huffmantreefalse.length-1; k++){
                if(Huffmantreefalse[k].weight > Huffmantreefalse[k+1].weight){
                var temp = new FalseNode(Huffmantreefalse[k+1].weight,Huffmantreefalse[k+1].pos);
                Huffmantreefalse[k+1] = Huffmantreefalse[k];
                Huffmantreefalse[k] = temp;
                }
            }
        }
        var leftchild = Huffmantreefalse.shift();
        var rightchild = Huffmantreefalse.shift();
        count += 2;
        var l = leftchild.pos;
        var r = rightchild.pos;
        var lw = leftchild.weight;
        var rw = rightchild.weight;
        Huffmantreetrue[l].parent = i;
        Huffmantreetrue[r].parent = i;
        Huffmantreetrue[i].leftchild = l;
        Huffmantreetrue[i].rightchild = r;
        Huffmantreetrue[i].weight = lw + rw;
        Huffmantreefalse[i-count].weight = Huffmantreetrue[i].weight;
    }
    return Huffmantreetrue;
}
function CodeHuffmanTree(Huffmantreetrue,n){
    var everystr = [];
    var cd = [];
    for(var i = 0; i < n; i++){
        var start = n-1;
        for(var c = i,f = Huffmantreetrue[i].parent; f != 0; c = f,f = Huffmantreetrue[f].parent){
            if (Huffmantreetrue[f].leftchild == c) cd[--start] = '0';
            else cd[--start] = '1';
        }
        everystr[i] = strcopy(cd,start);
    }
    return everystr;
}
function strcopy(str,start){
    var s = '';
    for(;str[start];start++){
        s += str[start];
    }
    return s;
}
//function displayHuffmanTree(everystr,strch){
//	document.getElementById("results").value = document.getElementById("results").value + "\n" + strch + "\t"+ everystr;
//}
    //var str = document.getElementById("myID").value;
function translate(charstr,chstr,everystr){
    var charray = [];
    for(var i = 0; i < charstr.length; i++){
        for(var j = 0; j < chstr.length; j++){
            if(charstr[i] == chstr[j].strch){
                charray = charray + "" + everystr[j] + "" + "2";
            }
        }
    }
    return charray;
}
//////translate后可以进行加密解密
function decode(chaarray,huffmantree){
    var eachdecode = "";
    var huffmanstr = "";
    var i = -1,j = 0;
    var leng = chaarray.length;
    var par = huffmantree.length - 1;
    while(leng > 0){
        eachdecode = "";
        for(i++;i < chaarray.length; i++){
            if(chaarray[i] == 2){
                break;
            }
            eachdecode += chaarray[i] + "";
            leng--;
        }
        leng--;
        //chaarray.splice(0, i);
        var f = par;
        while(!(huffmantree[f].leftchild == 0 && huffmantree[f].rightchild == 0)){
            if(eachdecode[j] == 0){
                f = huffmantree[f].leftchild;
            }
            else f = huffmantree[f].rightchild;
            j++;
        }
        huffmanstr += huffmantree[f].cha;
        j = 0;
    }
    return huffmanstr;
}
function executeHuffman(str){
    var charstr = str.split("");
    var strweight = [];
    var strch = [];
    var chstr = [];
    var i = 0,j = 0,temp,l = charstr.length;
    while(l > 0){/////////若字符串长度为零则跳出循环
        i = 0;
        strweight[j] = 0;
        strch[j] = charstr[0];
        temp = charstr[0];
        strch[j] = temp;
        while(i != l){
            if(charstr[i] == temp){
                charstr.splice(i,1);
                l--;
                strweight[j]++;
            }
            else i++;
        }
        j++;
    }
    for(var k = 0; k < strweight.length; k++){
        chstr[k] = new chastr(strweight[k],strch[k]);
    }
    return chstr;
}
function encrypt_impl(text){
    var cipher = crypto.createCipher(algorithm,password)
    var crypted = cipher.update(text,'utf8','hex')
    crypted += cipher.final('hex');
    return crypted;
}
function decrypt_impl(text){
    var decipher = crypto.createDecipher(algorithm,password);
    var dec = decipher.update(text,'hex','utf8');
    dec += decipher.final('utf8');
    return dec;
}
module.exports = {
    encrypt_impl: encrypt_impl,
    decrypt_impl: decrypt_impl,
    executeHuffman: executeHuffman,
    BuildHuffmanTree: BuildHuffmanTree,
    CodeHuffmanTree: CodeHuffmanTree,
    translate: translate,
    decode: decode
};


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AngularBreezeWebAPI.Model.Views
{
    [Table("Prospect.vdmMainSearchData")]
    public class MainSearchData
    {
        public int? SalesPersonID { get; set; }

        [StringLength(101)]
        public string SalesPerson { get; set; }

        [Key]
        [Column(Order = 0)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CompanyID { get; set; }

        [Key]
        [Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CompanyDisplayID { get; set; }

        [Key]
        [Column(Order = 2)]
        [StringLength(120)]
        public string CompanyName { get; set; }

        public int? StreetNumber_P { get; set; }

        [StringLength(302)]
        public string StreetAddress_P { get; set; }

        [StringLength(60)]
        public string City_P { get; set; }

        [StringLength(50)]
        public string State_P { get; set; }

        [StringLength(10)]
        public string ZipCode_P { get; set; }

        public int? StreetNumber_M { get; set; }

        [StringLength(302)]
        public string StreetAddress_M { get; set; }

        [StringLength(60)]
        public string City_M { get; set; }

        [StringLength(50)]
        public string State_M { get; set; }

        [StringLength(10)]
        public string ZipCode_M { get; set; }

        [StringLength(50)]
        public string ServiceBureau { get; set; }

        [StringLength(50)]
        public string Acct { get; set; }

        [StringLength(50)]
        public string bank { get; set; }

        [StringLength(200)]
        public string Attorney { get; set; }

        public int? Emply { get; set; }

        [Key]
        [Column(Order = 3, TypeName = "numeric")]
        public decimal CompanyTotal { get; set; }

        [Key]
        [Column(Order = 4)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int TotalAnnualValue { get; set; }

        public int? TotalInvalidScore { get; set; }

        [StringLength(1)]
        public string Freq { get; set; }

        [StringLength(42)]
        public string OfficePhone { get; set; }

        [Key]
        [Column(Order = 5)]
        public bool OutOfBusiness { get; set; }

        public DateTime? OOB_AsOfDate { get; set; }

        public int? CompanyInterest { get; set; }

        public int? InterestLevel { get; set; }

        public DateTime? Call_TP { get; set; }

        public DateTime? Call_ToDo { get; set; }

        public DateTime? Call_Comp { get; set; }

        public DateTime? Call_Cancel { get; set; }

        public DateTime? Mailing_TP { get; set; }

        public DateTime? Mailing_Comp { get; set; }

        public DateTime? NewsLetter_TP { get; set; }

        public DateTime? NewsLetter_ToDo { get; set; }

        public DateTime? NewsLetter_Comp { get; set; }

        public DateTime? Sample_TP { get; set; }

        public DateTime? Sample_ToDo { get; set; }

        public DateTime? Sample_Comp { get; set; }

        public DateTime? Quote_TP { get; set; }

        public DateTime? Quote_ToDo { get; set; }

        public DateTime? Quote_Comp { get; set; }

        public DateTime? Quote_Cancel { get; set; }

        public DateTime? References_TP { get; set; }

        public DateTime? References_ToDo { get; set; }

        public DateTime? References_Comp { get; set; }

        public DateTime? References_Cancel { get; set; }

        public DateTime? Appt_TP { get; set; }

        public DateTime? Appt_ToDo { get; set; }

        public DateTime? Appt_Comp { get; set; }

        public DateTime? Appt_Cancel { get; set; }

        public DateTime? UseSys_TP { get; set; }

        public DateTime? UseSys_ToDo { get; set; }

        public DateTime? UseSys_Comp { get; set; }

        public DateTime? UseSys_Cancel { get; set; }

        public DateTime? Verbal_TP { get; set; }

        public DateTime? Contracts_TP { get; set; }

        public DateTime? Contracts_ToDo { get; set; }

        public DateTime? Contracts_Comp { get; set; }

        public DateTime? Contracts_Cancel { get; set; }

        public DateTime? StartDate_TP { get; set; }

        public DateTime? StartDate_ToDo { get; set; }

        public DateTime? StartDate_Comp { get; set; }

        public DateTime? StartDate_Cancel { get; set; }

        public DateTime? TermDate_TP { get; set; }

        public DateTime? TermDate_ToDo { get; set; }

        public DateTime? TermDate_Comp { get; set; }

        public DateTime? TermDate_Cancel { get; set; }

        public int? DMPSClientNumber { get; set; }

        [Key]
        [Column(Order = 6)]
        public bool DMPSCurrent { get; set; }

        [Key]
        [Column(Order = 7)]
        public bool DMPSFormer { get; set; }

        public int? DMClientNumber { get; set; }

        [Key]
        [Column(Order = 8)]
        public bool DMCurrent { get; set; }

        [Key]
        [Column(Order = 9)]
        public bool DMFormer { get; set; }

        public int? DMRMClientNumber { get; set; }

        [Key]
        [Column(Order = 10)]
        public bool DMRMCurrent { get; set; }

        [Key]
        [Column(Order = 11)]
        public bool DMRMFormer { get; set; }

        public int? DMFSClientNumber { get; set; }

        [Key]
        [Column(Order = 12)]
        public bool DMFSCurrent { get; set; }

        [Key]
        [Column(Order = 13)]
        public bool DMFSFormer { get; set; }

        [StringLength(50)]
        public string PriorServiceBureau { get; set; }

        [StringLength(500)]
        public string LastMailingTemplate { get; set; }

        [Key]
        [Column(Order = 14)]
        public bool GetsNewsLetter { get; set; }

        public DateTime? Sort_ToDo { get; set; }

        [Key]
        [Column(Order = 15)]
        public DateTime CreateDate { get; set; }

        public int? DMRelatedDirector { get; set; }

        [Key]
        [Column(Order = 16)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ADOFilterFlag { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using Microsoft.Reporting.WebForms;

namespace MvcReportViewer
{
    /// <summary>
    /// Interface which stores data sources for Local Report (.rdlc)
    /// </summary>
    public interface ILocalReportDataSourceProvider
    {
        /// <summary>
        /// Saves report data source.
        /// </summary>
        /// <param name="reportControlId">Internal MvcReportViewer instance ID.</param>
        /// <param name="dataSource">Report Data Source.</param>
        void Add(Guid reportControlId, ReportDataSource dataSource);

        /// <summary>
        /// Gets data sources used for the report.
        /// </summary>
        /// <param name="reportControlId">Internal MvcReportViewer instance ID.</param>
        /// <returns>The list of data sources.</returns>
        IEnumerable<ReportDataSource> Get(Guid reportControlId);
    }
}


text:
using Microsoft.Toolkit.Forms.UI.Controls;
using RelhaxModpack.Utilities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Threading;

namespace RelhaxModpack.Automation
{
    /// <summary>
    /// The delegate to invoke when a browser event occurs.
    /// </summary>
    /// <param name="sender">The sending object.</param>
    /// <param name="e">Event arguments.</param>
    public delegate void BrowserManagerDelegate(object sender, EventArgs e);

    /// <summary>
    /// Provides a managed implementation to use a browser of any API to navigate and extract text from a web page.
    /// </summary>
    public class BrowserManager : IAutomationBrowser, IDisposable
    {
        /// <summary>
        /// Occurs when a web page has been fully downloaded and rendered by the browser.
        /// </summary>
        /// <remarks>This may fire multiple times if the loaded page has dynamic content (e.g. AJAX, javascript).</remarks>
        /// <seealso cref="NavigationCompleted"/>
        public event BrowserManagerDelegate DocumentCompleted;

        /// <summary>
        /// Occurs when the web browser has finished navigating to the new content. This does not mean that the new content has been fully parsed.
        /// </summary>
        /// <seealso cref="DocumentCompleted"/>
        public event BrowserManagerDelegate NavigationCompleted;

        /// <summary>
        /// The time, in milliseconds, to wait after the first NavigationCompleted event is fired (or a previous wait).
        /// </summary>
        /// <remarks>The total wait time can be calculated as WaitTimeMs * WaitCounts.</remarks>
        /// <seealso cref="WaitCounts"/>
        public int WaitTimeMs { get; set; } = 2000;

        /// <summary>
        /// The number of times the browser manager should wait for WaitTimeMs after the first NavigationCompleted event is fired.
        /// </summary>
        /// <remarks>The total wait time can be calculated as WaitTimeMs * WaitCounts.</remarks>
        /// <seealso cref="WaitTimeMs"/>
        public int WaitCounts { get; set; } = 3;

        /// <summary>
        /// Get the web browser as a control object.
        /// </summary>
        protected IAutomationBrowser browser;

        /// <summary>
        /// The type of browser object that is created in this BrowserManager instance.
        /// </summary>
        protected BrowserType browserType;

        /// <summary>
        /// The dispatcher used to create and interface with the browser object.
        /// </summary>
        protected Dispatcher dispatcher;

        /// <summary>
        /// Used to determine if the browser object is being managed on a thread other then the one this manager instance is using.
        /// </summary>
        protected bool OnCustomThread;

        /// <summary>
        /// The synchronization mechanism used for waiting until a browser has finished asynchronously loading a web page. This is thread safe.
        /// </summary>
        protected ManualResetEvent manualResetEvent;

        /// <summary>
        /// The counter for how many waits of WaitCounts have been completed.
        /// </summary>
        /// <seealso cref="WaitCounts"/>
        protected int browserFinishedLoadingScriptsCounter;

        /// <summary>
        /// Occurs when the browser object has been instanced.
        /// </summary>
        public event BrowserManagerDelegate BrowserCreated;

        /// <summary>
        /// Creates an instance of the BrowserManager class.
        /// </summary>
        /// <param name="browserType">The type of browser to create.</param>
        /// <param name="dispatcher">The dispatcher to use for creating and interfacing with the browser object.</param>
        /// <remarks>If the dispatcher argument is null, then a new UI thread will be created and a dispatcher will be assigned.</remarks>
        public BrowserManager(BrowserType browserType, Dispatcher dispatcher = null)
        {
            this.browserType = browserType;
            this.dispatcher = dispatcher;
            this.OnCustomThread = this.dispatcher == null;
        }

        /// <summary>
        /// Get the type of browser object that was created.
        /// </summary>
        public BrowserType BrowserType
        { get { return browserType; } }

        /// <summary>
        /// Get the browser as a control object.
        /// </summary>
        public Control Browser
        {
            get
            { return browser.Browser; }
        }

        /// <summary>
        /// Gets or sets the height of the browser control.
        /// </summary>
        public int Height
        {
            get
            { return Browser.Height; }
            set
            { Browser.Height = value; }
        }

        /// <summary>
        /// Gets or sets the width of the browser control.
        /// </summary>
        public int Width
        {
            get
            { return Browser.Width; }
            set
            { Browser.Width = value; }
        }

        /// <summary>
        /// Return the currently parsed html document from the browser object.
        /// </summary>
        /// <returns>The currently parsed html document as a string.</returns>
        /// <remarks>Most implementations only return the document's "outer html" section, which may not include the document header.</remarks>
        public string GetHtmlDocument()
        {
            string htmlDocument = null;
            this.dispatcher.Invoke(() => htmlDocument = browser.GetHtmlDocument());
            return htmlDocument;
        }

        /// <summary>
        /// Start a navigation to the given url.
        /// </summary>
        /// <param name="url">The resource to navigate to.</param>
        public void Navigate(string url)
        {
            browser.Navigate(url);
        }

        /// <summary>
        /// Creates a thread to be used to manage the browser object, if dispatcher is null.
        /// </summary>
        protected void SetDispatcher()
        {
            if (dispatcher != null)
                return;

            Thread thread = new Thread(() =>
            {
                this.dispatcher = Dispatcher.CurrentDispatcher;
                Dispatcher.Run();
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();
            while (this.dispatcher == null)
                Thread.Sleep(1);
        }

        /// <summary>
        /// Asynchronously tells the browser to navigate to a web page and wait for the designated amount of time and counts.
        /// </summary>
        /// <param name="url">The url to have the browser navigate to.</param>
        /// <param name="token">The cancellation token to allow the user to cancel the web page navigation.</param>
        /// <returns>True if the web navigation completed successfully, false otherwise.</returns>
        public async Task<bool> NavigateWithDelayAsync(string url, CancellationToken token)
        {
            browserFinishedLoadingScriptsCounter = 0;
            SetDispatcher();

            this.dispatcher.Invoke(() => this.CreateBrowser());

            manualResetEvent = new ManualResetEvent(false);

            browser.DocumentCompleted += (sender, args) =>
            {
                Logging.Debug("The browser reports document completed");
                manualResetEvent.Set();
            };

            Logging.Debug("Browser dispatch navigate start");
            this.dispatcher.InvokeAsync(() =>
            {
                this.Navigate(url);
            });
            Logging.Debug("Browser dispatch navigate finish, wait on ManualResetEvent");

            await Task.Run(() => { manualResetEvent.WaitOne(); });

            if (this.browser == null)
            {
                Logging.Debug("Browser was disposed, cancel or error happened");
                return false;
            }

            //now wait for the timeout
            //this wait allows the browser to finish loading external scripts
            Logging.Info(LogOptions.ClassName, "The browser task events completed, wait additional {0} counts", WaitCounts);
            while (browserFinishedLoadingScriptsCounter < WaitCounts)
            {
                if (token != null && token.IsCancellationRequested)
                {
                    Logging.Debug("Cancel happened");
                    return false;
                }
                await Task.Delay(WaitTimeMs);
                Logging.Info(LogOptions.ClassName, "Waiting {0} of {1} counts", ++browserFinishedLoadingScriptsCounter, WaitCounts);
            }

            return true;
        }

        /// <summary>
        /// Initializes the browser object.
        /// </summary>
        protected void CreateBrowser()
        {
            switch (browserType)
            {
                case BrowserType.WebBrowser:
                    browser = new AutomationWebBrowser();
                    break;
                case BrowserType.WebView:
                    browser = new AutomationWebViewWrapper();
                    break;
                case BrowserType.WebView2:
                default:
                    throw new NotImplementedException();
            }
            browser.DocumentCompleted += DocumentCompleted;
            browser.NavigationCompleted += DocumentCompleted;
            BrowserCreated?.Invoke(this, new EventArgs());
        }

        /// <summary>
        /// Cancels a browser navigation operation.
        /// </summary>
        public void Cancel()
        {
            Logging.Debug(LogOptions.ClassName, "Cancel called for Browser Manager");
            this.browser.Cancel();
            DisposeBrowser();
            this.manualResetEvent.Set();
        }

        /// <summary>
        /// Releases all resources used by the BrowserManger instance.
        /// </summary>
        public void Dispose()
        {
            DisposeBrowser();
            manualResetEvent.Dispose();
            if (this.OnCustomThread)
                ShutdownDispatcher();

            if (DocumentCompleted != null)
                DocumentCompleted = null;

            if (NavigationCompleted != null)
                NavigationCompleted = null;
        }

        /// <summary>
        /// Dispose of the browser object.
        /// </summary>
        public void DisposeBrowser()
        {
            this.dispatcher.Invoke(() =>
            {
                if (browser != null)
                {
                    if (!browser.Browser.IsDisposed)
                    {
                        browser.Cancel();
                        browser.Dispose();
                    }
                }
            });
        }

        /// <summary>
        /// Shutdown the dispatcher object.
        /// </summary>
        /// <remarks>This should only be called when the dispatcher has been created inside this class. Otherwise you could be invoking shutdown on the currently running dispatcher (that the application is running on).</remarks>
        protected void ShutdownDispatcher()
        {
            this.dispatcher.ShutdownFinished += (sender, args) =>
            {
                this.dispatcher = null;
            };
            this.dispatcher.InvokeShutdown();
        }
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms, CPP #-}

module Main where

import System.IO
import Unison.Hash.Extra ()
import Unison.Codebase.Store (Store)
import Unison.Reference (Reference)
import Unison.Runtime.Address
import Unison.Symbol.Extra ()
import Unison.Term.Extra ()
import Unison.Var (Var)
import qualified Unison.ABT as ABT
import qualified Unison.BlockStore.FileBlockStore as FBS
import qualified Unison.Cryptography as C
import qualified Unison.Builtin as Builtin
#ifdef leveldb
import qualified Unison.Codebase.LeveldbStore as DBStore
#else
import qualified Unison.Codebase.FileStore as FileStore
#endif
import qualified Unison.Codebase as Codebase
import qualified Unison.CodebaseServer as CodebaseServer
import qualified Unison.Reference as Reference
import qualified Unison.Runtime.ExtraBuiltins as EB
import qualified Unison.Symbol as Symbol
import qualified Unison.Term as Term
import qualified Unison.View as View
import qualified Unison.Util.Logger as L

hash :: Var v => Term.Term v -> Reference
hash (Term.Ref' r) = r
hash t = Reference.Derived (ABT.hash t)

store :: IO (Store IO (Symbol.Symbol View.DFO))
#ifdef leveldb
store = DBStore.make "store"
#else
store = FileStore.make "store"
#endif

makeRandomAddress :: C.Cryptography k syk sk skp s h c -> IO Address
makeRandomAddress crypt = Address <$> C.randomBytes crypt 64

main :: IO ()
main = do
  mapM_ (`hSetEncoding` utf8) [stdout, stdin, stderr]
  store' <- store
  logger <- L.atomic (L.atInfo L.toStandardError)
  let crypto = C.noop "dummypublickey"
  blockStore <- FBS.make' (makeRandomAddress crypto) makeAddress "Index"
  builtins0 <- pure $ Builtin.make logger
  builtins1 <- EB.make logger blockStore crypto
  codebase <- pure $ Codebase.make hash store'
  Codebase.addBuiltins (builtins0 ++ builtins1) store' codebase
  CodebaseServer.server 8080 codebase


text:
using namespace sourcekitd;
using namespace sourcekitd::trace;
using namespace llvm;

//===----------------------------------------------------------------------===//
// General
//===----------------------------------------------------------------------===//

static uint64_t tracing_session = llvm::sys::TimeValue::now().msec();

uint64_t trace::getTracingSession() {
  return tracing_session;
}

static void append(xpc_object_t Contents, uint64_t Value) {
  xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND, Value);
}

static void append(xpc_object_t Contents, ActionKind Value) {
  append(Contents, static_cast<uint64_t>(Value));
}

static void append(xpc_object_t Contents, OperationKind Value) {
  append(Contents, static_cast<uint64_t>(Value));
}

static void append(xpc_object_t Contents, llvm::StringRef Value) {
  xpc_array_set_string(Contents, XPC_ARRAY_APPEND, Value.data());
}

static void append(xpc_object_t Contents, const StringPairs &Files) {
  append(Contents, Files.size());
  std::for_each(Files.begin(), Files.end(),
                [&] (const std::pair<std::string, std::string> &File) {
                  append(Contents, File.first);
                  append(Contents, File.second);
                });
}

template <typename U>
struct llvm::yaml::SequenceTraits<std::vector<U>> {
  static size_t size(IO &Io, std::vector<U> &Vector) {
    return Vector.size();
  }
  static U &element(IO &Io, std::vector<U> &Vector, size_t Index) {
    return Vector[Index];
  }
};

template <>
struct llvm::yaml::MappingTraits<SwiftArguments> {
  static void mapping(IO &Io, SwiftArguments &Args) {

    Io.mapOptional("PrimaryFile", Args.PrimaryFile, std::string());
    Io.mapRequired("CompilerArgs", Args.Args);
  }
};

static std::string serializeCompilerArguments(const SwiftArguments &Args) {
  // Serialize compiler instance
  std::string OptionsAsYaml;
  llvm::raw_string_ostream OptionsStream(OptionsAsYaml);
  llvm::yaml::Output YamlOutput(OptionsStream);
  YamlOutput << const_cast<SwiftArguments &>(Args);
  OptionsStream.flush();
  return OptionsAsYaml;
}

//===----------------------------------------------------------------------===//
// Trace consumer
//===----------------------------------------------------------------------===//

class XpcTraceConsumer : public SourceKit::trace::TraceConsumer {
public:
  virtual ~XpcTraceConsumer() = default;

  // Operation previously started with startXXX has finished
  virtual void operationFinished(uint64_t OpId) override;

  // Trace start of SourceKit operation
  virtual void operationStarted(uint64_t OpId, OperationKind OpKind,
                                const SwiftInvocation &Inv,
                                const StringPairs &OpArgs) override;
};

// Trace start of SourceKit operation
void XpcTraceConsumer::operationStarted(uint64_t OpId,
                                        OperationKind OpKind,
                                        const SwiftInvocation &Inv,
                                        const StringPairs &OpArgs) {
  xpc_object_t Contents = xpc_array_create(nullptr, 0);
  append(Contents, ActionKind::OperationStarted);
  append(Contents, OpId);
  append(Contents, OpKind);
  append(Contents, serializeCompilerArguments(Inv.Args));
  append(Contents, Inv.Files);
  append(Contents, OpArgs);
  trace::sendTraceMessage(Contents);
}

// Operation previously started with startXXX has finished
void XpcTraceConsumer::operationFinished(uint64_t OpId) {
  xpc_object_t Contents = xpc_array_create(nullptr, 0);
  append(Contents, trace::ActionKind::OperationFinished);
  append(Contents, OpId);
  trace::sendTraceMessage(Contents);
}

static XpcTraceConsumer Instance;

void trace::initialize() {
  SourceKit::trace::registerConsumer(&Instance);
}


text:
<!DOCTYPE html>

		<meta charset=utf-8>
		<title>FanoLug - Fortunae Lug</title>
		<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel=stylesheet type='text/css'>

FanoLUG

			Il FanoLUG è il gruppo di utenti Linux di Fano.

			Per partecipare e seguire le attività iscrivetevi alla mailing list, seguite Twitter, Facebook o Github. Esiste anche un chat su Telegram.

			Per comunicazioni dirette scrivete una email.

                Follow @fanolug

                Tweet

		Tweets by @fanolug


text:
function get_thrower() {
  "use strict";
  return Object.getOwnPropertyDescriptor(arguments, "callee").get;
}

var f = (function(v) {
  "use asm";
  function fun() {
    switch (v) {}
  }
  return {
    fun: fun
  };
})(get_thrower()).fun;

%OptimizeFunctionOnNextCall(f);
f();


text:
var fs = require('fs')
var ghsign = require('ghsign')
var request = require('request')
var verifiers = {}

module.exports.signer = signer
module.exports.verify = verify

ghsign = ghsign(function (username, cb) {
  fs.readFile('./public-keys/' + username + '.keys', 'utf-8', function (_, keys) {
    if (keys) return cb(null, keys)
    request('https://github.com/' + username + '.keys', function (_, response) {
      var keys = response.statusCode === 200 && response.body
      if (!keys) return cb(new Error('Could not find public keys for ' + username))
      fs.mkdir('./public-keys', function () {
        fs.writeFile('./public-keys/' + username + '.keys', keys, function () {
          cb(null, keys)
        })
      })
    })
  })
})

function signer (username) {
  return ghsign.signer(username)
}

function verify (username, message, signature, cb) {
  var vfy = verifiers[username]
  if (!verifiers[username]) verifiers[username] = vfy = ghsign.verifier(username)
  if (!vfy || !username || !signature) return cb(null, false)

  vfy(message, signature, cb)
}


text:
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [rightscale_selfservice](#rightscale_selfservice)
  - [Quick Start](#quick-start)
  - [Authentication](#authentication)
  - [CLI](#cli)
    - [Template Includes](#template-includes)
  - [Testing](#testing)
    - [Suite](#suite)
    - [Template](#template)
    - [Case](#case)
      - [Compile](#compile)
      - [Execute](#execute)
      - [Operations](#operations)
  - [API Client](#api-client)
    - [Supported Services, Resources and Actions](#supported-services-resources-and-actions)
    - [How it works](#how-it-works)
      - [Href Tokens](#href-tokens)
      - [Automatic Multipart](#automatic-multipart)
    - [Some examples...](#some-examples)
      - [Authentication](#authentication-1)
      - [Service Versions](#service-versions)
      - [Executing Actions](#executing-actions)
        - [List operations](#list-operations)
        - [Show a template](#show-a-template)
        - [Get RestClient::Request Instead of Executing Action](#get-restclientrequest-instead-of-executing-action)
        - [Format Errors](#format-errors)
        - [Multipart Detection](#multipart-detection)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

rightscale_selfservice
======================

A rubygem with a self service [API client](#api-client), and buncha useful [CLI](#cli) bits for
RightScale Self Service, including a test harness for Cloud Application Templates

Travis Build Status: [<img src="https://travis-ci.org/rgeyer/rightscale_selfservice.png" />](https://travis-ci.org/rgeyer/rightscale_selfservice)

## Quick Start

```
gem install rightscale_selfservice
```

Setup some [Authentication](#authentication) details

Explore the [CLI](#cli).
```
rightscale_selfservice help
```

Explore the [API Client](#api-client).

## Authentication

rightscale_selfservice can authenticate with the APIs using (roughly) the same
properties as [right_api_client](https://github.com/rightscale/right_api_client).

The only additional required property is "selfservice_url".

The CLI can use a .yml file containing those properties or have them passed in
on the commandline.  The API Client accepts an input hash with these same
properties.

An example .yml file can be found [here](https://github.com/rightscale/right_api_client/blob/v1.5.24/config/login.yml.example)

A working .yml file might look like;
```
:account_id: 12345
:email: user@domain.com
:password: password
:api_url: https://us-4.rightscale.com
:selfservice_url: https://selfservice-4.rightscale.com
```

## CLI

### Template Includes
For any of the template commands, the template will be preprocessed
to replace any #include:/path/to/another/cat/file with the contents of that file.

This allows for shared libraries to be built and stored along side your CATs.

Example:

Main template
```
name 'cat-with-includes'
rs_ca_ver 20131202
short_description 'has some includes'

#include:../definitions/foo.cat.rb
```

foo.cat.rb
```
define foo() return @clouds do
  @clouds = rs.clouds.get()
end
```

Results in
```
name 'cat-with-includes'
rs_ca_ver 20131202
short_description 'has some includes'

###############################################################################
# BEGIN Include from ../definitions/foo.cat.rb
###############################################################################
define foo() return @clouds do
  @clouds = rs.clouds.get()
end
###############################################################################
# END Include from ../definitions/foo.cat.rb
###############################################################################
```

You can simply run the preprocessor on your CAT and get a file with all the
appropriate includes with the "preprocess" command.

```
rightscale_selfservice template preprocess ~/Code/cat/somecat.cat.rb -o /tmp/processedcat.cat.rb
```

Then maybe check if all your syntax is good by using the API to "compile" your CAT

```
rightscale_selfservice template compile ~/Code/cat/somecat.cat.rb --auth-file=~./.right_api_client/login.yml
```

If that works, maybe start up a Cloud App from it

```
rightscale_selfservice template execute ~/Code/cat/somecat.cat.rb --auth-file=~/.right_api_client/login.yml
```

## Testing

Included as a framework for performing functional tests of your Cloud
Application Templates (CATs). Tests are performed as part of a [Suite](#suite)
which contains one or more [Template](#template), which have one or more test
[Case](#case).

### Suite
A suite is currently defined simply by the [glob](http://ruby-doc.org/core-1.9.3/Dir.html#method-c-glob)
you pass either to the [CLI](#cli) or the test suite class.

I might consider creating a config file or other options, but for now the suite
is basically just a container.

The suite will interrogate the files found by the input glob, and create
individual [Template](#template) classes.

### Template
A template is a 1-to-1 match with a CAT file found by the [Suite](#suite).

The template class will interrogate the contents of the CAT and create individual
[Case](#case) classes.

### Case
There are three types of cases, which are defined by comments in the CAT.

#### Compile
Merely checks if the CAT will compile successfully. When a template is tagged
to include a compile test case every other test will be ignored.

To create a test template which will only be tested for successful compile add
the following to the top of the template
```
#test:compile_only=true
```

#### Execute
This checks if the CAT will execute and reach a desired state.

If no tags are added to a template, an execute test case will be automatically
run, with the assumption that it's expected execution_state is "running".

To create a test template with an execute test case which will succeed if the
CAT launches successfully.

```
#test:execution_state=running
```

For the negative test case, where a CAT which launches and fails is actually a
successful test.

```
#test:execution_state=failed
```

There are also scenarios where a successful test should end in a specified state
but because of external issues (system bugs, reusable definitions, etc) the
opposite state is reached. In this case you can specify both the desired state
as the "execution_state" as well as an "execution_alternate_state".

If the CAT launches and reaches the alternate state the test case will be marked
as "FAILED (EXPECTED)", and if it reaches the desired state it will be marked
"FIXED"

```
#test:execution_state=running
#test:execution_alternate_state=failed
```

#### Operations
Once a template has been successfully launched, any operation test cases will
be run.

An example of a CAT with two operations which should be run as test cases;
```
#test:execution_state=running
#test:execution_alternate_state=failed

name "Foo"
rs_ca_ver 20131202
short_description "Foo"

#test_operation:execution_state=completed
#test_operation:execution_alternate_state=failed
#test_operation_param:key=val
#test_operation_param:key1=val1
#test_operation_param:key2=val2
operation "one" do
  description "one"
  definition "foo"
end

#test_operation:execution_state=completed
#test_operation:execution_alternate_state=failed
#test_operation_param:key=val
#test_operation_param:key1=val1
#test_operation_param:key2=val2
operation "two" do
  description "two"
  definition "foo"
end

define foo() do

end
```

This will run the operations named "one" and "two" with the specified
test_operation_param(s) as inputs to the operation. It will evaluate success
or failure based on the "execution_state" specified.

This has the same functionality as [Execute](#execute) in that you can specify
a desired and alternative state.

## API Client

The [CLI](#cli) bits consume the API client which is deployed with this gem. The
goal of this API client is to be as "dumb" and lightweight as is practical.

In practical terms this means that the client doesn't make assumptions about the
return values from the API, and does not attempt to turn them into ruby objects.

In fact, the default "language" of this client is
[Rest Client](http://rubygems.org/gems/rest-client) requests and responses.

The API client does handle some of the more mundane things for you though, such
as authenticating with the API using various means (access_token, refresh_token,
email & password), and assembling the correct URL for a particular resource
action.

### Supported Services, Resources and Actions
The client fetches metadata about the SelfService API using a Rake task which
generates a JSON file which is deployed with the client/gem.  This means that
a given version of the client supports the API interface as it existed at the
time that version of the client/gem was created.

Fear not, supporting the latest functionality is as simple as.

```
rake update_inteface_json
# Bump the gemspec
rake gem
gem push pkg/<new gem file>
```

### How it works
You can access a specific action with the following syntax.

```
client.<service_name>(<optional_service_version>).<resource_name>.<action_name>(<optional_params_hash>,<optional_boolean>)
```

Where;
 * service_name is one of the (currently 3) services listed the [docs](http://support.rightscale.com/12-Guides/Self-Service#Self-Service_API)
 * optional_service_version is a string version of the service
 * resource_name is the resource you'd like to operate on (E.G. template, execution, operation, etc.)
 * action_name is the action you'd like to take (index, show, create, etc.)
 * optional_params_hash is the parameters you wish to pass to that action
 * optional_boolean if not supplied, a RestClient::Request will be created and
    executed and a RestClient::Response will be returned. If supplied and true
    a ready to execute RestClient::Request will be returned

#### Href Tokens
If the Href for a particular action contains tokens, any parameter passed to the
action with the same name as that token will be substituted in the request.

Take a [show](#show-a-template) action on the template resource for example.

The Href is;
```
/collections/:collection_id/templates/:id
```

Which contains the token :id.  In order to specify the template id while calling
the action, put it in as a parameter.

```
client.designer.templates.show(:id => "abc123")
```

The Href will have :id substituted with "abc123", and the id parameter will be
stripped from the body of the request.

#### Automatic Multipart
The client automatically URL encodes parameters and puts them in the body.  But
if you pass any Ruby object which has the methods "path" and "read" (basically
any file or IO resource) it'll assume you're performing a multipart request
and build the RestClient::Request accordingly.

See the [Multipart Detection](#multipart-detection) example..

### Some examples...

#### Authentication
Create the client with email and password
```
client = RightScaleSelfService::Client.new(
  :email => "user@domain.com",
  :password => "password",
  :selfservice_url => "https://selfservice-4.rightscale.com",
  :api_url => "https://us-4.rightscale.com"
)
```

Or with an access token
```
client = RightScaleSelfService::Client.new(
  :access_token => "access_token",
  :selfservice_url => "https://selfservice-4.rightscale.com",
  :api_url => "https://us-4.rightscale.com"
)
```

Or with a refresh token
```
client = RightScaleSelfService::Client.new(
  :refresh_token => "refresh_token",
  :selfservice_url => "https://selfservice-4.rightscale.com",
  :api_url => "https://us-4.rightscale.com"
)
```

#### Service Versions
You can specify which version of a service you want.  If you don't the "newest"
version will be used.

Get version 1.1 (which doesn't presently exist) of the "manager" service
```
client.manager("1.1")
```

Just use the latest version of the "manager" service
```
client.manager
```

#### Executing Actions

##### List operations
```
client.manager.operation.index
```

##### Show a template
```
client.designer.template.show(:id => "abc123")
```

##### Get RestClient::Request Instead of Executing Action
```
request = client.catalog.application.index({}, true)
request.execute
```

##### Format Errors
```
begin
  client.designer.template.compile(:source => some_source_file)
rescue RestClient::ExceptionWithResponse => e
  puts "Failed to compile the template"
  puts RightScaleSelfService::Api::Client.format_error(e)
end
```

##### Multipart Detection
This'll automatically format the payload for RestClient::Request as a multipart
request, rather than a standard request with a URL encoded body.
```
file = File.open("some.cat.rb", "rb")
client.designer.template.create(:source => file)
```


text:
/*jshint strict: false, maxlen: 500 */
/*global require, assertEqual, assertNotEqual, AQL_EXPLAIN, AQL_EXECUTE */

////////////////////////////////////////////////////////////////////////////////
/// @brief tests for filters
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////

function optimizerFiltersTestSuite () {

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief filters that should be optimized away
////////////////////////////////////////////////////////////////////////////////

    testOptimizeAwayFalseFilter : function () {
      var queries = [
        "FOR i IN 1..10 FILTER i == 1 && false RETURN i",
        "FOR i IN 1..10 FILTER (i == 1 || i == 2) && false RETURN i",
        "FOR i IN 1..10 FILTER false && i == 1 RETURN i",
        "FOR i IN 1..10 FILTER false && (i == 1 || i == 2) RETURN i",
        "FOR i IN 1..10 FILTER IS_STRING(i) && false RETURN i",
        "FOR i IN 1..10 FILTER false && IS_STRING(i) RETURN i",
        "FOR i IN 1..10 FILTER false && RAND() RETURN i"
      ];

      queries.forEach(function(query) {
        var plan = AQL_EXPLAIN(query).plan;
        var nodeTypes = plan.nodes.map(function(node) {
          return node.type;
        });

        assertEqual("SingletonNode", nodeTypes[0], query);
        assertNotEqual(-1, nodeTypes.indexOf("NoResultsNode"), query);
        assertEqual("ReturnNode", nodeTypes[nodeTypes.length - 1], query);

        var results = AQL_EXECUTE(query).json;
        assertEqual([ ], results, query);
      });
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief filters that should be optimized away
////////////////////////////////////////////////////////////////////////////////

    testOptimizeAwayTrueFilter : function () {
      var queries = [
        "FOR i IN 1..10 FILTER i == 1 || true RETURN i",
        "FOR i IN 1..10 FILTER i == 1 || i == 2 || true RETURN i",
        "FOR i IN 1..10 FILTER true || i == 1 RETURN i",
        "FOR i IN 1..10 FILTER true || i == 1 || i == 2 RETURN i",
        "FOR i IN 1..10 FILTER IS_STRING(i) || true RETURN i",
        "FOR i IN 1..10 FILTER true || IS_STRING(i) RETURN i"
      ];

      queries.forEach(function(query) {
        var plan = AQL_EXPLAIN(query).plan;
        var nodeTypes = plan.nodes.map(function(node) {
          return node.type;
        });

        assertEqual("SingletonNode", nodeTypes[0], query);
        assertEqual(-1, nodeTypes.indexOf("FilterNode"), query);
        assertEqual("ReturnNode", nodeTypes[nodeTypes.length - 1], query);

        var results = AQL_EXECUTE(query).json;
        assertEqual([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ], results, query);
      });
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief filters that should not be optimized away
////////////////////////////////////////////////////////////////////////////////

    testKeepFilter : function () {
      var queries = [
        "FOR i IN 1..10 FILTER false || i == 1 RETURN i",
        "FOR i IN 1..10 FILTER i == 1 || false RETURN i",
        "FOR i IN 1..10 FILTER IS_STRING(i) || false RETURN i",
        "FOR i IN 1..10 FILTER false || IS_STRING(i) RETURN i",
        "FOR i IN 1..10 FILTER i == 1 || i == 2 RETURN i",
        "FOR i IN 1..10 FILTER i == 1 || (i == 2 && true) RETURN i",
        "FOR i IN 1..10 FILTER true && i == 1 RETURN i",
        "FOR i IN 1..10 FILTER true && (i == 1 || i == 2) RETURN i",
        "FOR i IN 1..10 FILTER IS_STRING(i) && true RETURN i",
        "FOR i IN 1..10 FILTER true && IS_STRING(i) RETURN i"
      ];

      queries.forEach(function(query) {
        var plan = AQL_EXPLAIN(query).plan;
        var nodeTypes = plan.nodes.map(function(node) {
          return node.type;
        });

        assertEqual("SingletonNode", nodeTypes[0], query);
        assertNotEqual(-1, nodeTypes.indexOf("FilterNode"), query);
        assertEqual("ReturnNode", nodeTypes[nodeTypes.length - 1], query);
      });
    }

  };
}

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////

jsunity.run(optimizerFiltersTestSuite);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:


text:
/* ###
 * IP: GHIDRA
 *
 * 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 agent.dbgmodel.dbgmodel.concept;

import agent.dbgmodel.dbgmodel.main.KeyStore;
import agent.dbgmodel.dbgmodel.main.ModelObject;

/**
 * A wrapper for {@code IStringDisplayableConcept} and its newer variants.
 */
public interface StringDisplayableConcept extends Concept {

	String toDisplayString(ModelObject contextObject, KeyStore metadata);

}


text:
from . import application

from . import mqtt
from . import windows
from . import external
from . import network

def main():
    application.init()
    network.init()
    mqtt.init()
    windows.init()
    external.init()

    application.main_loop()

if __name__ == "__main__":
    main()


text:
===========================
python-fitparse Documention
===========================

.. toctree::
   :maxdepth: 2

   api

Introduction
============

The :mod:`fitparse` module is a Python library for parsing
`ANT <http://www.thisisant.com>`_/`Garmin <http://www.garmin.com>`_ ``.FIT``
files.

The FIT (Flexible and Interoperable Data Transfer) file protocol is specified
by `ANT <http://www.thisisant.com>`_ in its FIT SDK. It's a common file format
used internally on embedded fitness computers, for example on the Edge and
Forerunner series of `Garmin <http://www.garmin.com>`_ products.

Quickstart Guide
----------------

TODO

Installation
------------

Using ``pip``
~~~~~~~~~~~~~

The easiest way to grab :mod:`fitparse` is using ``pip``,

::

    $ pip install fitparse

From github
~~~~~~~~~~~

Navigate to `dtcooper/python-fitparse <https://github.com/dtcooper/python-fitparse>`_
on github and clone the latest version::

    $ git clone git@github.com:dtcooper/python-fitparse.git
    $ cd python-fitparse
    $ python setup.py install

Requirements
~~~~~~~~~~~~

The following are required to install :mod:`fitparse`,

* `Python <http://www.python.org/>`_ 3.6 and above

API Documentation
-----------------

If you are looking for information on a specific function, class or method,
this part of the documentation is for you.

.. toctree::
   :maxdepth: 2

   api

Usage Examples
--------------

Here's a simple program to print all the record fields in an activity file::

    from fitparse import FitFile

    fitfile = FitFile('/home/dave/garmin-activities/2012-12-19-16-14-54.fit')

    # Get all data messages that are of type record
    for record in fitfile.get_messages('record'):

        # Go through all the data entries in this record
        for record_data in record:

            # Print the records name and value (and units if it has any)
            if record_data.units:
                print(" * %s: %s %s" % (
                    record_data.name, record_data.value, record_data.units,
                ))
            else:
                print(" * %s: %s" % (record_data.name, record_data.value))
        print()

License
-------

.. include:: ../LICENSE
   :literal:


text:
namespace Atata
{
    /// <summary>
    /// Represents any element containing number content.
    /// Default search finds the first occurring element.
    /// </summary>
    /// <typeparam name="TOwner">The type of the owner page object.</typeparam>
    public class Number<TOwner> : Content<decimal?, TOwner>
            where TOwner : PageObject<TOwner>
    {
    }
}


text:
<?php

declare(strict_types=1);

namespace KarlosAgudo\Fixtro\CodeQualityTool\Checker;

use KarlosAgudo\Fixtro\CodeQualityTool\Contexts\CommandContext;
use KarlosAgudo\Fixtro\CodeQualityTool\Events\FixtroEvent;
use Symfony\Component\Console\Output\OutputInterface;

class CheckersRunner
{
	/** @var array */
	private $checkers;
	/** @var CommandContext */
	private $context;

	/**
	 * CheckersRunner constructor.
	 *
	 * @param array          $checkers
	 * @param CommandContext $context
	 */
	public function __construct(array $checkers, CommandContext $context)
	{
		$this->checkers = $checkers;
		$this->context = $context;
	}

	/**
	 * @param OutputInterface $output
	 *
	 * @return bool
	 *
	 * @throws \KarlosAgudo\Fixtro\CodeQualityTool\Exceptions\ExecutionStoppedByEvent
	 */
	public function run(OutputInterface $output)
	{
		$failed = false;
		foreach ($this->checkers as $checker) {
			$eventAnalyzerName = $this->getEventName($checker);
			$preExecute = $this->context->throwEvent('analyzer.'.$eventAnalyzerName.'.pre',
													 $this->context->getConfig(), []);
			if ('PASS-SIGNAL' === $preExecute) {
				$this->context->getLogger()->info('[SKIPPED] Skipped by event');
				continue;
			}

			$checker->startProcess();
			list($info, $errors) = $checker->showResults();
			$result = $this->context->throwEvent('analyzer.'.$eventAnalyzerName.'.after', $info, $errors);

			if (FixtroEvent::class === get_class($result)) {
				$info = $result->getInfo();
				$errors = $result->getError();
			}

			$this->showInfo($output, $errors, $info);

			if (count($errors)) {
				$this->showErrors($output, $errors);
				$failed = true;

				break;
			}
		}

		return !$failed;
	}

	/**
	 * @param AbstractChecker $checker
	 *
	 * @return string
	 */
	private function getEventName(AbstractChecker $checker): string
	{
		$shortName = (new \ReflectionClass($checker))->getShortName();
		$analyzerConfigKey = lcfirst($shortName);

		return strtolower($analyzerConfigKey);
	}

	/**
	 * @param OutputInterface $output
	 * @param array           $errors
	 * @param array           $info
	 */
	private function showInfo(OutputInterface $output, array $errors, array $info)
	{
		if (!count($errors) || $output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
			foreach ($info as $line) {
				$output->writeln($line);
			}
		}
	}

	/**
	 * @param OutputInterface $output
	 * @param array           $errors
	 */
	private function showErrors(OutputInterface $output, array $errors)
	{
		foreach ($errors as $error) {
			$output->writeln("<error>$error</error>");
		}
	}
}


text:
package nxt.http;

import nxt.Nxt;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;

import javax.servlet.http.HttpServletRequest;

public final class Scan extends APIServlet.APIRequestHandler {

    static final Scan instance = new Scan();

    private Scan() {
        super(new APITag[] {APITag.DEBUG}, "numBlocks", "height", "validate");
    }

    @Override
    JSONStreamAware processRequest(HttpServletRequest req) {
        JSONObject response = new JSONObject();
        try {
            boolean validate = "true".equalsIgnoreCase(req.getParameter("validate"));
            int numBlocks = 0;
            try {
                numBlocks = Integer.parseInt(req.getParameter("numBlocks"));
            } catch (NumberFormatException e) {}
            int height = -1;
            try {
                height = Integer.parseInt(req.getParameter("height"));
            } catch (NumberFormatException ignore) {}
            long start = System.currentTimeMillis();
            try {
                Nxt.getBlockchainProcessor().setGetMoreBlocks(false);
                if (numBlocks > 0) {
                    Nxt.getBlockchainProcessor().scan(Nxt.getBlockchain().getHeight() - numBlocks + 1, validate);
                } else if (height >= 0) {
                    Nxt.getBlockchainProcessor().scan(height, validate);
                } else {
                    response.put("error", "invalid numBlocks or height");
                    return response;
                }
            } finally {
                Nxt.getBlockchainProcessor().setGetMoreBlocks(true);
            }
            long end = System.currentTimeMillis();
            response.put("done", true);
            response.put("scanTime", (end - start)/1000);
        } catch (RuntimeException e) {
            response.put("error", e.toString());
        }
        return response;
    }

    @Override
    final boolean requirePost() {
        return true;
    }

    @Override
    boolean requirePassword() {
        return true;
    }
}


text:
// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// License:   Licensed under MIT license (see license.js)
// ==========================================================================
/*globals module ok equals same test Sample */
var basic, baseTypes, bindingPage, testView, design;

module('SC.DesignCoder', {
  setup: function () {
    basic = SC.Page.design({});
    testView = SC.View.extend({});
    testView.Designer = SC.ViewDesigner.extend({
      designProperties: ['s', 'n', 'b', 'a', 'h', 'valueBinding']
    });

    baseTypes = SC.Page.create({
      needsDesigner: true,
      mainView: testView.design({s:'string',n:12,b:false,a:[1, 2, 3],h:{a:'b',c:'d'}})
    });

    bindingPage = SC.Page.create({
      number: 12,
      needsDesigner: true,
      mainView: testView.design({valueBinding: SC.Binding.from('.page.number')})//.create() //to get it to run on the binding itself...
    });

  },

  teardown: function () {
  }
});

test('Verify basic page file encoding', function () {
  design = SC.DesignCoder.encode(basic);
  equals(design.trim(), 'SC.Page.design({})', 'basic page encoded');
});

test('Verify view in page encoding', function () {
  baseTypes.awake();
  design = SC.DesignCoder.encode(baseTypes);
  equals(design.trim(),'SC.Page.design({mainView: SC.View.design({s: "string",n: 12,b: false,a: [1,2,3],h: {"a": "b","c": "d"}})})', 'basic types encoded');
});

test('Verify binding in page encoding', function () {
  SC.RunLoop.begin();
  bindingPage.awake();
  bindingPage.get('mainView');
  SC.RunLoop.end();

  design = SC.DesignCoder.encode(bindingPage);
  equals(design.trim(),'SC.Page.design({mainView: SC.View.design({valueBinding: SC.Binding.from(\'.page.number\')})})', 'binding types encoded');
});


text:
package com.metova.android.test;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    public void onCreate( Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
    }
}


text:
#ifndef LIB_UTIL_SYS_H
#define LIB_UTIL_SYS_H

#include <stdbool.h>

int util_sys_get_dev_addr(const char *dev, char *addr);
bool util_sys_dev_is_partition(dev_t dev);
int util_sys_get_partnum(dev_t dev);
int util_sys_get_base_dev(dev_t dev, dev_t *base_dev);

#endif /** LIB_UTIL_SYS_H @} */


text:
<?php

namespace PhlyRestfully\Listener;

use PhlyRestfully\ApiProblem;
use PhlyRestfully\View\RestfulJsonModel;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\Http\Request as HttpRequest;
use Zend\Mvc\MvcEvent;
use Zend\View\Model\ModelInterface;

/**
 * ApiProblemListener
 *
 * Provides a listener on the render event, at high priority.
 *
 * If the MvcEvent represents an error, then its view model and result are
 * replaced with a RestfulJsonModel containing an API-Problem payload.
 */
class ApiProblemListener implements ListenerAggregateInterface
{
    /**
     * Default values to match in Accept header
     *
     * @var string
     */
    protected static $acceptFilter = 'application/hal+json,application/api-problem+json,application/json';

    /**
     * @var \Zend\Stdlib\CallbackHandler[]
     */
    protected $listeners = array();

    /**
     * Constructor
     *
     * Set the accept filter, if one is passed
     *
     * @param string $filter
     */
    public function __construct($filter = null)
    {
        if (is_string($filter) && !empty($filter)) {
            self::$acceptFilter = $filter;
        }
    }

    /**
     * @param EventManagerInterface $events
     */
    public function attach(EventManagerInterface $events)
    {
        $this->listeners[] = $events->attach(MvcEvent::EVENT_RENDER, __CLASS__ . '::onRender', 1000);
    }

    /**
     * @param EventManagerInterface $events
     */
    public function detach(EventManagerInterface $events)
    {
        foreach ($this->listeners as $index => $listener) {
            if ($events->detach($listener)) {
                unset($this->listeners[$index]);
            }
        }
    }

    /**
     * Listen to the render event
     *
     * @param MvcEvent $e
     */
    public static function onRender(MvcEvent $e)
    {
        // only worried about error pages
        if (!$e->isError()) {
            return;
        }

        // and then, only if we have an Accept header...
        $request = $e->getRequest();
        if (!$request instanceof HttpRequest) {
            return;
        }

        $headers = $request->getHeaders();
        if (!$headers->has('Accept')) {
            return;
        }

        // ... that matches certain criteria
        $accept = $headers->get('Accept');
        $match  = $accept->match(self::$acceptFilter);
        if (!$match || $match->getTypeString() == '*/*') {
            return;
        }

        // Next, do we have a view model in the result?
        // If not, nothing more to do.
        $model = $e->getResult();
        if (!$model instanceof ModelInterface) {
            return;
        }

        // Marshall the information we need for the API-Problem response
        $httpStatus       = $e->getResponse()->getStatusCode();
        $exception        = $model->getVariable('exception');

        if ($exception instanceof \Exception) {
            $apiProblem = new ApiProblem($httpStatus, $exception);
        } else {
            $apiProblem = new ApiProblem($httpStatus, $model->getVariable('message'));
        }

        // Create a new model with the API-Problem payload, and reset
        // the result and view model in the event using it.
        $model = new RestfulJsonModel(array('payload' => $apiProblem));
        $model->setTerminal(true);
        $e->setResult($model);
        $e->setViewModel($model);
    }
}