text:
"""
Bifacial Modeling - modelchain
==============================

Example of bifacial modeling using pvfactors and ModelChain
"""

# %%
# This example shows how to complete a bifacial modeling example using the
# :py:class:`pvlib.modelchain.ModelChain` with the
# :py:func:`pvlib.bifacial.pvfactors.pvfactors_timeseries` function
# to transpose GHI data to both front and rear Plane of Array (POA) irradiance.
#
# Unfortunately ``ModelChain`` does not yet support bifacial simulation
# directly so we have to do the bifacial irradiance simulation ourselves.
# Once the combined front + rear irradiance is known, we can pass that
# to ``ModelChain`` and proceed as usual.
#
# Future versions of pvlib may make it easier to do bifacial modeling
# with ``ModelChain``.

import pandas as pd
from pvlib import pvsystem
from pvlib import location
from pvlib import modelchain
from pvlib.temperature import TEMPERATURE_MODEL_PARAMETERS as PARAMS
from pvlib.bifacial.pvfactors import pvfactors_timeseries
import warnings

# supressing shapely warnings that occur on import of pvfactors
warnings.filterwarnings(action='ignore', module='pvfactors')

# create site location and times characteristics
lat, lon = 36.084, -79.817
tz = 'Etc/GMT+5'
times = pd.date_range('2021-06-21', '2021-6-22', freq='1T', tz=tz)

# create site system characteristics
axis_tilt = 0
axis_azimuth = 180
gcr = 0.35
max_angle = 60
pvrow_height = 3
pvrow_width = 4
albedo = 0.2
bifaciality = 0.75

# load temperature parameters and module/inverter specifications
temp_model_parameters = PARAMS['sapm']['open_rack_glass_glass']
cec_modules = pvsystem.retrieve_sam('CECMod')
cec_module = cec_modules['Trina_Solar_TSM_300DEG5C_07_II_']
cec_inverters = pvsystem.retrieve_sam('cecinverter')
cec_inverter = cec_inverters['ABB__MICRO_0_25_I_OUTD_US_208__208V_']

# create a location for site, and get solar position and clearsky data
site_location = location.Location(lat, lon, tz=tz, name='Greensboro, NC')
solar_position = site_location.get_solarposition(times)
cs = site_location.get_clearsky(times)

# load solar position and tracker orientation for use in pvsystem object
sat_mount = pvsystem.SingleAxisTrackerMount(axis_tilt=axis_tilt,
                                            axis_azimuth=axis_azimuth,
                                            max_angle=max_angle,
                                            backtrack=True,
                                            gcr=gcr)

# created for use in pvfactors timeseries
orientation = sat_mount.get_orientation(solar_position['apparent_zenith'],
                                        solar_position['azimuth'])

# get rear and front side irradiance from pvfactors transposition engine
# explicity simulate on pvarray with 3 rows, with sensor placed in middle row
# users may select different values depending on needs
irrad = pvfactors_timeseries(solar_position['azimuth'],
                             solar_position['apparent_zenith'],
                             orientation['surface_azimuth'],
                             orientation['surface_tilt'],
                             axis_azimuth,
                             times,
                             cs['dni'],
                             cs['dhi'],
                             gcr,
                             pvrow_height,
                             pvrow_width,
                             albedo,
                             n_pvrows=3,
                             index_observed_pvrow=1
                             )

# turn into pandas DataFrame
irrad = pd.concat(irrad, axis=1)

# create bifacial effective irradiance using aoi-corrected timeseries values
irrad['effective_irradiance'] = (
    irrad['total_abs_front'] + (irrad['total_abs_back'] * bifaciality)
)

# %%
# With effective irradiance, we can pass data to ModelChain for
# bifacial simulation.

# dc arrays
array = pvsystem.Array(mount=sat_mount,
                       module_parameters=cec_module,
                       temperature_model_parameters=temp_model_parameters)

# create system object
system = pvsystem.PVSystem(arrays=[array],
                           inverter_parameters=cec_inverter)

# ModelChain requires the parameter aoi_loss to have a value. pvfactors
# applies surface reflection models in the calculation of front and back
# irradiance, so assign aoi_model='no_loss' to avoid double counting
# reflections.
mc_bifi = modelchain.ModelChain(system, site_location, aoi_model='no_loss')
mc_bifi.run_model_from_effective_irradiance(irrad)

# plot results
mc_bifi.results.ac.plot(title='Bifacial Simulation on June Solstice',
                        ylabel='AC Power')


text:
{{<layout}}

{{$pageTitle}}Submit your ERS annual return{{/pageTitle}}
{{$afterHeader}}

{{/afterHeader}}

{{$content}}
  {{>alpha_banner}}
  {{>hmrc_banner}}

	 {{>sub_header_EMI}}

Your end of year return is nearly complete

If you're happy with the information that you've provided submit your return.

														Section
														Your answers

													Spreadsheet name	NameOfSpreadsheet.ods	Change this

													 Are there any qualifying subsidiaries?	Yes	Change this

													Qualifying subsidiaries	Abacus Incorporated	Change this

 To the best of my knowledge and belief the information I have given is correct and complete

							I accept - Submit end of year return

Back

{{/content}}

{{/layout}}

redpajama_set_name: RedPajamaGithub


text:
import {
  PARTICIPANT_LIST_SUCCESS,
  PARTICIPANT_LIST_FAILURE
} from '../actions/ActionTypes'

const initialState = [];

const Participants = (state = initialState, action) => {
  switch(action.type) {
    case PARTICIPANT_LIST_SUCCESS:
      return [ ...action.json ];
    case PARTICIPANT_LIST_FAILURE:
      return [ ...initialState ];
    default:
      return state
  }
};

export default Participants


text:
<?php

namespace Acelot\JsonRpc;

/**
 * Class ResponseAbstract
 * @package Acelot\JsonRpc
 */
abstract class ResponseAbstract implements ResponseInterface
{
    /**
     * @var string|int
     */
    protected $id;

    /**
     * @param int|string $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return int|string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return array
     */
    public function getResponse()
    {
        return array_merge(array(
            'jsonrpc' => Server::PROTOCOL_VERSION,
            'id'      => $this->getId()
        ), $this->getResponseData());
    }
}


text:
import time

import mock
from tests import BaseTestCase

from redash import settings, limiter
from redash.authentication.account import invite_token
from redash.models import User

class TestResetPassword(BaseTestCase):
    def test_shows_reset_password_form(self):
        user = self.factory.create_user(is_invitation_pending=False)
        token = invite_token(user)
        response = self.get_request("/reset/{}".format(token), org=self.factory.org)
        self.assertEqual(response.status_code, 200)

class TestInvite(BaseTestCase):
    def test_expired_invite_token(self):

        with mock.patch("time.time") as patched_time:
            patched_time.return_value = time.time() - (7 * 24 * 3600) - 10
            token = invite_token(self.factory.user)

        response = self.get_request("/invite/{}".format(token), org=self.factory.org)
        self.assertEqual(response.status_code, 400)

    def test_invalid_invite_token(self):
        response = self.get_request("/invite/badtoken", org=self.factory.org)
        self.assertEqual(response.status_code, 400)

    def test_valid_token(self):
        user = self.factory.create_user(is_invitation_pending=True)
        token = invite_token(user)
        response = self.get_request("/invite/{}".format(token), org=self.factory.org)
        self.assertEqual(response.status_code, 200)

    def test_already_active_user(self):
        token = invite_token(self.factory.user)
        self.post_request(
            "/invite/{}".format(token),
            data={"password": "test1234"},
            org=self.factory.org,
        )
        response = self.get_request("/invite/{}".format(token), org=self.factory.org)
        self.assertEqual(response.status_code, 400)

class TestInvitePost(BaseTestCase):
    def test_empty_password(self):
        token = invite_token(self.factory.user)
        response = self.post_request(
            "/invite/{}".format(token), data={"password": ""}, org=self.factory.org
        )
        self.assertEqual(response.status_code, 400)

    def test_invalid_password(self):
        token = invite_token(self.factory.user)
        response = self.post_request(
            "/invite/{}".format(token), data={"password": "1234"}, org=self.factory.org
        )
        self.assertEqual(response.status_code, 400)

    def test_bad_token(self):
        response = self.post_request(
            "/invite/{}".format("jdsnfkjdsnfkj"),
            data={"password": "1234"},
            org=self.factory.org,
        )
        self.assertEqual(response.status_code, 400)

    def test_user_invited_before_invitation_pending_check(self):
        user = self.factory.create_user(details={})
        token = invite_token(user)
        response = self.post_request(
            "/invite/{}".format(token),
            data={"password": "test1234"},
            org=self.factory.org,
        )
        self.assertEqual(response.status_code, 302)

    def test_already_active_user(self):
        token = invite_token(self.factory.user)
        self.post_request(
            "/invite/{}".format(token),
            data={"password": "test1234"},
            org=self.factory.org,
        )
        response = self.post_request(
            "/invite/{}".format(token),
            data={"password": "test1234"},
            org=self.factory.org,
        )
        self.assertEqual(response.status_code, 400)

    def test_valid_password(self):
        user = self.factory.create_user(is_invitation_pending=True)
        token = invite_token(user)
        password = "test1234"
        response = self.post_request(
            "/invite/{}".format(token),
            data={"password": password},
            org=self.factory.org,
        )
        self.assertEqual(response.status_code, 302)
        user = User.query.get(user.id)
        self.assertTrue(user.verify_password(password))
        self.assertFalse(user.is_invitation_pending)

class TestLogin(BaseTestCase):
    def test_throttle_login(self):
        limiter.enabled = True
        # Extract the limit from settings (ex: '50/day')
        limit = settings.THROTTLE_LOGIN_PATTERN.split("/")[0]
        for _ in range(0, int(limit)):
            self.get_request("/login", org=self.factory.org)

        response = self.get_request("/login", org=self.factory.org)
        self.assertEqual(response.status_code, 429)

    def test_throttle_password_reset(self):
        limiter.enabled = True
        # Extract the limit from settings (ex: '10/hour')
        limit = settings.THROTTLE_PASS_RESET_PATTERN.split("/")[0]
        for _ in range(0, int(limit)):
            self.get_request("/forgot", org=self.factory.org)

        response = self.get_request("/forgot", org=self.factory.org)
        self.assertEqual(response.status_code, 429)

class TestSession(BaseTestCase):
    # really simple test just to trigger this route
    def test_get(self):
        self.make_request(
            "get", "/default/api/session", user=self.factory.user, org=False
        )


text:
SKIP_ATTRS = %w(metadata uri type)
INDEX_COL_WIDTH = 2

def format_response(response)
  if response.multiple_entities? && response.collection.size > 1
    format_collection response.collection
  else
    format_entity response.entity
  end
end

def col_overhead
  $settings.table_border? ? 3 : 1
end

def format_collection(collection, headers=nil)
  if collection && collection.size > 0
    save_headers = headers ? headers.clone : nil
    save_response collection.response
    metadata = collection_metadata collection, headers
    table border: $settings.table_border? do
      row header: true do
        headers ||= metadata.keys
        column '#', width: INDEX_COL_WIDTH
        headers.each {|header| column header, width: metadata[header][:size] }
      end
      collection.each_with_index do |entity, index|
        row do
          column index+1
          if entity.is_a? Array
            entity.each {|v| column v }
          else
            headers.each {|header| column entity[header]}
          end
        end
      end
    end
    if collection.cursor && agree('Next Page? (Y/N)') {|q| q.default = 'Y'}
      format_collection(collection.next_page, save_headers)
    end
  else
    puts "0 results"
  end
end

def format_entity(entity)
  if entity
    name_cols = value_cols = 0
    entity.data.reject{|k,v| SKIP_ATTRS.include? k}.each do |k,v|
      name_cols = [name_cols, k.size].max
      value_cols = [value_cols, v.to_s.size].max
    end
    table border: $settings.table_border? do
      row header: true do
        name_width = [name_cols, 20].min
        column 'name', width: name_width
        column 'value', width: [value_cols, HighLine.new.output_cols - name_width - (3 * col_overhead)].min
      end
      entity.data.reject{|k,v| SKIP_ATTRS.include? k}.each do |k,v|
        row do
          column(k)
          column(v)
        end
      end
    end
  else
    puts "no data"
  end
end

# return hash { column_name: { max_size: 12, size: 12 }  }
def collection_metadata(collection, headers=nil)
  result = {}
  collection.each do |entity|
    if entity.is_a? Array
      headers.each_with_index do |header, index|
        col = result[header] ||= {}
        size = entity[index].to_s.size
        col[:max_size] = col[:max_size] ? [col[:max_size], size].max : size
      end
    else
      entity.reject{|k,v| headers ? !headers.include?(k) : SKIP_ATTRS.include?(k)}.each do |k,v|
        col = result[k] ||= {}
        size = v.to_s.size
        col[:max_size] = col[:max_size] ? [col[:max_size], size].max : size
      end
    end
  end
  total_size = result.inject(0) do |total, (col,meta)|
    meta[:max_size] = [col.size, meta[:max_size]].max
    total + meta[:max_size]
  end
  terminal_columns = HighLine.new.output_cols
  overhead = (result.keys.size + 2) * col_overhead + INDEX_COL_WIDTH
  if total_size + overhead < terminal_columns
    result.each {|col,meta| meta[:size] = meta[:max_size]}
  else
    col_size = (terminal_columns - overhead) / result.keys.size
    result.each {|col,meta| meta[:size] = col_size}
  end
  result
end


text:
export * from './menu.module';
export * from './menu.component';


text:
@interface JSHomeViewController : JSBaseViewController

@end


text:
<?php

declare(strict_types=1);

namespace phpseclib3\File\ASN1\Maps;

use phpseclib3\File\ASN1;

/**
 * RDNSequence
 *
 * In practice, RDNs containing multiple name-value pairs (called "multivalued RDNs") are rare,
 * but they can be useful at times when either there is no unique attribute in the entry or you
 * want to ensure that the entry's DN contains some useful identifying information.
 *
 * - https://www.opends.org/wiki/page/DefinitionRelativeDistinguishedName
 *
 * @author  Jim Wigginton <terrafrost@php.net>
 */
abstract class RDNSequence
{
    public const MAP = [
        'type' => ASN1::TYPE_SEQUENCE,
        // RDNSequence does not define a min or a max, which means it doesn't have one
        'min' => 0,
        'max' => -1,
        'children' => RelativeDistinguishedName::MAP,
    ];
}


text:
Mugs
================

Mugs is a immutable collections library for JavaScript written in Coffeescript. It is the product of the Bachelors project by Mads Hartmann Jensen.

Building it
-----------

You need to have [coffeescript](http://coffeescript.org) and [cake](http://coffeescript.org/#cake) installed

Simple run

    cake build

Now you should be able to run the files in `examples/client-side/`.

Running the tests
-----------------

### Qunit

First you can you compile the coffeescript into javascript. Simply run 'cake build'. Now point your favorite browser at test/index.html and what the result of running all of the qunit tests

### JSCoverage

As above you need to run 'cake build' followed by 'cake jscoverage'. Now point your browser at http://127.0.0.1:8080/jscoverage.html?test/index.html to see the coverage of running the tests.


text:
This directory contains instructions and Kubernetes manifests for overriding the default in-cluster PostgreSQL databases (`accountsdb` + `ledgerdb`) with Google Cloud SQL.

For a multicluster/multi-region setup, see [this doc](multi-region.md) for instructions.

![diagram](arch.png)

## How it works

The setup scripts provided will provision a Cloud SQL instance in your Google Cloud Project. The script will then create two databases - one for the **accounts DB**, one for the **ledger DB**. This replaces the two separate PostgreSQL StatefulSets used in Bank of Anthos by default.

## Setup

1. **Create a [Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects)** if you don't already have one.

2. **Set environment variables** corresponding to your project, desired GCP region/zone, and the Kubernetes namespace into which you want to deploy Bank of Anthos.

```
export PROJECT_ID="my-project"
export DB_REGION="us-east1"
export ZONE="us-east1-b"
export CLUSTER="my-cluster-name"
export NAMESPACE="default"
```

3. **Enable the [GKE API](https://cloud.google.com/kubernetes-engine/docs/reference/rest)**. This may take a few minutes.

```
gcloud services enable container.googleapis.com
```

4. **Create a GKE cluster** with [Workload Identity](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity#overview) enabled. Workload Identity lets you use a Kubernetes service account like a Google Cloud service account, giving your pods granular Google Cloud API permissions - in this case, permission for the Bank of Anthos Pods to access Cloud SQL.

```
gcloud container clusters create $CLUSTER \
	--project=$PROJECT_ID --zone=$ZONE \
	--machine-type=e2-standard-4 --num-nodes=4 \
	--workload-pool="$PROJECT_ID.svc.id.goog"
```

5. **Run the Workload Identity setup script** for your new cluster. This script creates a Google Service Account (GSA) and Kubernetes Service Account (KSA), associates them together, then grants the service account permission to access Cloud SQL.

```
./setup_workload_identity.sh
```

6. **Run the Cloud SQL instance create script**. This takes a few minutes to complete.

```
./create_cloudsql_instance.sh
```

7. **Create a Cloud SQL admin demo secret** in your GKE cluster. This gives your in-cluster Cloud SQL client a username and password to access Cloud SQL. (Note that admin/admin credentials are for demo use only and should never be used in a production environment.)

```
export INSTANCE_NAME='bank-of-anthos-db'
export INSTANCE_CONNECTION_NAME=$(gcloud sql instances describe $INSTANCE_NAME --format='value(connectionName)')

kubectl create secret -n $NAMESPACE generic cloud-sql-admin \
 --from-literal=username=admin --from-literal=password=admin \
 --from-literal=connectionName=$INSTANCE_CONNECTION_NAME
```

8. **Deploy Bank of Anthos** to your cluster. Each backend Deployment (`userservice`, `contacts`, `transactionhistory`, `balancereader`, and `ledgerwriter`) is configured with a [Cloud SQL Proxy](https://cloud.google.com/sql/docs/mysql/sql-proxy#what_the_proxy_provides) sidecar container. Cloud SQL Proxy provides a secure TLS connection between the backend GKE pods and your Cloud SQL instance.

This command will also deploy two Kubernetes Jobs, to populate the accounts and ledger dbs with Tables and test data.

```
kubectl apply -n $NAMESPACE -f ./kubernetes-manifests/config.yaml
kubectl apply -n $NAMESPACE -f ./populate-jobs
kubectl apply -n $NAMESPACE -f ./kubernetes-manifests
```

9. Wait a few minutes for all the pods to be `RUNNING`. (Except for the two `populate-` Jobs. They should be marked `0/3 - Completed` when they finish successfully.)

```
NAME                                  READY   STATUS      RESTARTS   AGE
balancereader-d48c8d84c-j7ph7         2/2     Running     0          2m56s
contacts-bbfdbb97f-vzxmv              2/2     Running     0          2m55s
frontend-65c78dd78c-tsq26             1/1     Running     0          2m55s
ledgerwriter-774b7bf7b9-jpz7l         2/2     Running     0          2m54s
loadgenerator-f489d8858-q2n46         1/1     Running     0          2m54s
populate-accounts-db-wrh4m            0/3     Completed   0          2m54s
populate-ledger-db-422cr              0/3     Completed   0          2m53s
transactionhistory-747476548c-j2zqx   2/2     Running     0          2m53s
userservice-7f6df69544-nskdf          2/2     Running     0          2m53s
```

10. Access the Bank of Anthos frontend at the frontend service `EXTERNAL_IP`, then log in as `test-user` with the pre-populated credentials added to the Cloud SQL-based `accounts-db`. You should see the pre-populated transaction data show up, from the Cloud SQL-based `ledger-db`. You're done!


text:
/*
Description : This controller is to handle login and logout operations.
Author : Darshani S

*/

(function() {

    function loginController($scope, $rootScope, authentication, $location, constants, $crypthmac) {

        $scope.login = function() {

            //send SHA512 hashed password JSON to login API
            var credentials = {
                "userName": $scope.credentials.userName,
                "password": $crypthmac.encrypt($scope.credentials.password, "")
            }

            authentication.login(credentials)
                .error(function(err) {
                    $scope.errorMessage = constants.msgUsernamePasswordFailure;
                })
                .then(function(data) {
                    $scope.errorMessage = "";
                    $location.path('profile')
                });

        };
        $scope.sendForgotEmail = function() {
            authentication
                .resetUserPasswordEmail($scope.credentials.userName)
                .success(function(data) {
                    console.log("Data : " + JSON.stringify(data));
                    swal({ html: true, title: "", text: data.message });
                    $location.path('login')
                })
                .error(function(err) {
                    console.log(err);
                    swal({ html: true, title: "", text: error.message });
                    $location.path('login')
                })
        };

    };

    loginController.$inject = ['$scope', '$rootScope', 'authentication', '$location', 'constants', '$crypthmac'];

    angular.module("employeeApp").controller("loginController", loginController);
}());


text:
package errorutil

import (
	"errors"
	"net/http"
	"testing"

	oerrors "github.com/objenious/errors"
)

type retryable bool

func (err retryable) Error() string {
	if err {
		return "true"
	}
	return "false"
}

func (err retryable) Retryable() bool {
	return bool(err)
}

func TestIsRetryable(t *testing.T) {
	tests := []struct {
		err  error
		want bool
	}{
		{nil, false},
		{RetryableError(nil), false},
		{NotRetryableError(nil), false},
		{oerrors.Wrap(RetryableError(nil), "bar"), false},

		{errors.New("foo"), false},
		{oerrors.New("foo"), false},
		{oerrors.Wrap(errors.New("foo"), "bar"), false},

		{RetryableError(errors.New("foo")), true},
		{RetryableError(oerrors.New("foo")), true},
		{oerrors.Wrap(RetryableError(errors.New("foo")), "bar"), true},

		{RetryableError(NotRetryableError(errors.New("foo"))), true},
		{NotRetryableError(errors.New("foo")), false},
		{NotRetryableError(oerrors.New("foo")), false},
		{oerrors.Wrap(NotRetryableError(errors.New("foo")), "bar"), false},

		{httpError(http.StatusBadGateway), true},
		{oerrors.Wrap(httpError(http.StatusBadGateway), "bar"), true},
		{httpError(http.StatusInternalServerError), true},
		{oerrors.Wrap(httpError(http.StatusInternalServerError), "bar"), true},
		{httpError(http.StatusGatewayTimeout), true},
		{oerrors.Wrap(httpError(http.StatusGatewayTimeout), "bar"), true},
		{httpError(429), true},
		{oerrors.Wrap(httpError(429), "bar"), true},
		{httpError(http.StatusNotFound), false},
		{oerrors.Wrap(httpError(http.StatusNotFound), "bar"), false},
		{NotFoundError(errors.New("foo")), false},
		{httpError(http.StatusBadRequest), false},
		{oerrors.Wrap(httpError(http.StatusBadRequest), "bar"), false},
		{InvalidError(errors.New("foo")), false},
		{httpError(http.StatusForbidden), false},
		{oerrors.Wrap(httpError(http.StatusForbidden), "bar"), false},
		{ForbiddenError(errors.New("foo")), false},

		{NotRetryableError(httpError(http.StatusBadGateway)), false},
		{NotRetryableError(oerrors.Wrap(httpError(http.StatusBadGateway), "bar")), false},
		{NotRetryableError(httpError(http.StatusInternalServerError)), false},
		{NotRetryableError(oerrors.Wrap(httpError(http.StatusInternalServerError), "bar")), false},
		{NotRetryableError(httpError(http.StatusGatewayTimeout)), false},
		{NotRetryableError(oerrors.Wrap(httpError(http.StatusGatewayTimeout), "bar")), false},
		{NotRetryableError(httpError(429)), false},
		{NotRetryableError(oerrors.Wrap(httpError(429), "bar")), false},
		{NotRetryableError(httpError(http.StatusNotFound)), false},
		{NotRetryableError(oerrors.Wrap(httpError(http.StatusNotFound), "bar")), false},
		{NotRetryableError(NotFoundError(errors.New("foo"))), false},
		{NotRetryableError(httpError(http.StatusBadRequest)), false},
		{NotRetryableError(oerrors.Wrap(httpError(http.StatusBadRequest), "bar")), false},
		{NotRetryableError(InvalidError(errors.New("foo"))), false},
		{NotRetryableError(httpError(http.StatusForbidden)), false},
		{NotRetryableError(oerrors.Wrap(httpError(http.StatusForbidden), "bar")), false},
		{NotRetryableError(ForbiddenError(errors.New("foo"))), false},

		{retryable(false), false},
		{retryable(true), true},
		{NotRetryableError(retryable(false)), false},
		{NotRetryableError(retryable(true)), false},
	}
	for _, tt := range tests {
		got := IsRetryable(tt.err)
		if got != tt.want {
			t.Errorf("IsRetryable(%q): got: %v, want %v", tt.err, got, tt.want)
		}
	}
}

func ExampleIsRetryable() {
	err := errors.New("some error")
	IsRetryable(err) // will return false
	err = RetryableError(err)
	IsRetryable(err) // will return true
	//err = NotRetryableError(err)
	IsRetryable(err) // will return false
}

func TestIsNotRetryable(t *testing.T) {
	tests := []struct {
		err  error
		want bool
	}{
		{nil, false},
		{RetryableError(nil), false},
		{NotRetryableError(nil), false},
		{oerrors.Wrap(RetryableError(nil), "bar"), false},
		{NotRetryableError(oerrors.Wrap(RetryableError(nil), "bar")), false},

		{errors.New("foo"), false},
		{oerrors.New("foo"), false},
		{oerrors.Wrap(errors.New("foo"), "bar"), false},

		{RetryableError(errors.New("foo")), false},
		{NotRetryableError(errors.New("foo")), true},
		{NotRetryableError(RetryableError(errors.New("foo"))), true},
		{RetryableError(oerrors.New("foo")), false},
		{NotRetryableError(RetryableError(oerrors.New("foo"))), true},
		{NotRetryableError(oerrors.New("foo")), true},
		{oerrors.Wrap(RetryableError(errors.New("foo")), "bar"), false},
		{oerrors.Wrap(NotRetryableError(errors.New("foo")), "bar"), true},
		{NotRetryableError(oerrors.Wrap(RetryableError(errors.New("foo")), "bar")), true},
		{RetryableError(NotRetryableError(oerrors.Wrap(RetryableError(errors.New("foo")), "bar"))), false},

		{retryable(false), true},
		{retryable(true), false},
	}
	for _, tt := range tests {
		got := IsNotRetryable(tt.err)
		if got != tt.want {
			t.Errorf("IsRetryable(%q): got: %v, want %v", tt.err, got, tt.want)
		}
	}
}

func ExampleIsNotRetryable() {
	err := errors.New("some error")
	IsNotRetryable(err) // will return false
	err = RetryableError(err)
	IsNotRetryable(err) // will return false
}

func TestNewRetryableError(t *testing.T) {
	err := NewRetryableError("retryable error")
	if IsNotRetryable(err) {
		t.Errorf("NewRetryableError must return a retryable error")
	}
	if err.Error() != "retryable error" {
		t.Errorf("NewRetryableError: expected :%s, got %s", "test", err.Error())
	}
}

func ExampleNewRetryableError() {
	err := NewRetryableError("test")
	IsRetryable(err) // will return true
}

func TestNewRetryableErrorf(t *testing.T) {
	err := NewRetryableErrorf("retryable error %s", "formatted")
	if IsNotRetryable(err) {
		t.Errorf("NewRetryableErrorf must return a retryable error")
	}
	if err.Error() != "retryable error formatted" {
		t.Errorf("NewRetryableErrorf: expected :%s, got %s", "retryable error formatted", err.Error())
	}
}

func ExampleNewRetryableErrorf() {
	err := NewRetryableErrorf("Unable to read data for device %d", 70)
	IsRetryable(err) // will return true
}


text:
class Epubquicklook < Cask
  version :latest
  sha256 :no_check

  url 'http://people.ict.usc.edu/~leuski/programming/EPUBQuickLookPlugin.dmg'
  homepage 'http://people.ict.usc.edu/~leuski/programming/epub-quickview.php'

  pkg 'EpubQuickLook.pkg'
  uninstall :pkgutil => 'net.leuski.epubQuicklookPlugin.epub.pkg'
end


text:
#pragma once
#include <aws/forecast/ForecastService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ForecastService
{
namespace Model
{

  /**
   *
Provides information about the Explainability resource.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_FORECASTSERVICE_API ExplainabilityInfo
  {
  public:
    ExplainabilityInfo();
    ExplainabilityInfo(Aws::Utils::Json::JsonView jsonValue);
    ExplainabilityInfo& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The Amazon Resource Name (ARN) of the Explainability.

     */
    inline const Aws::String& GetExplainabilityArn() const{ return m_explainabilityArn; }

    /**
     *
The Amazon Resource Name (ARN) of the Explainability.

     */
    inline bool ExplainabilityArnHasBeenSet() const { return m_explainabilityArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the Explainability.

     */
    inline void SetExplainabilityArn(const Aws::String& value) { m_explainabilityArnHasBeenSet = true; m_explainabilityArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the Explainability.

     */
    inline void SetExplainabilityArn(Aws::String&& value) { m_explainabilityArnHasBeenSet = true; m_explainabilityArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the Explainability.

     */
    inline void SetExplainabilityArn(const char* value) { m_explainabilityArnHasBeenSet = true; m_explainabilityArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the Explainability.

     */
    inline ExplainabilityInfo& WithExplainabilityArn(const Aws::String& value) { SetExplainabilityArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the Explainability.

     */
    inline ExplainabilityInfo& WithExplainabilityArn(Aws::String&& value) { SetExplainabilityArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the Explainability.

     */
    inline ExplainabilityInfo& WithExplainabilityArn(const char* value) { SetExplainabilityArn(value); return *this;}

    /**
     *
The status of the Explainability. States include:

     * ACTIVE

 CREATE_PENDING,
     * CREATE_IN_PROGRESS, CREATE_FAILED

     * CREATE_STOPPING, CREATE_STOPPED

     * DELETE_PENDING, DELETE_IN_PROGRESS,
     * DELETE_FAILED

     */
    inline const Aws::String& GetStatus() const{ return m_status; }

    /**
     *
The status of the Explainability. States include:

     * ACTIVE

 CREATE_PENDING,
     * CREATE_IN_PROGRESS, CREATE_FAILED

     * CREATE_STOPPING, CREATE_STOPPED

     * DELETE_PENDING, DELETE_IN_PROGRESS,
     * DELETE_FAILED

     */
    inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }

    /**
     *
The status of the Explainability. States include:

     * ACTIVE

 CREATE_PENDING,
     * CREATE_IN_PROGRESS, CREATE_FAILED

     * CREATE_STOPPING, CREATE_STOPPED

     * DELETE_PENDING, DELETE_IN_PROGRESS,
     * DELETE_FAILED

     */
    inline void SetStatus(const Aws::String& value) { m_statusHasBeenSet = true; m_status = value; }

    /**
     *
The status of the Explainability. States include:

     * ACTIVE

 CREATE_PENDING,
     * CREATE_IN_PROGRESS, CREATE_FAILED

     * CREATE_STOPPING, CREATE_STOPPED

     * DELETE_PENDING, DELETE_IN_PROGRESS,
     * DELETE_FAILED

     */
    inline void SetStatus(Aws::String&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }

    /**
     *
The status of the Explainability. States include:

     * ACTIVE

 CREATE_PENDING,
     * CREATE_IN_PROGRESS, CREATE_FAILED

     * CREATE_STOPPING, CREATE_STOPPED

     * DELETE_PENDING, DELETE_IN_PROGRESS,
     * DELETE_FAILED

     */
    inline void SetStatus(const char* value) { m_statusHasBeenSet = true; m_status.assign(value); }

    /**
     *
The status of the Explainability. States include:

     * ACTIVE

 CREATE_PENDING,
     * CREATE_IN_PROGRESS, CREATE_FAILED

     * CREATE_STOPPING, CREATE_STOPPED

     * DELETE_PENDING, DELETE_IN_PROGRESS,
     * DELETE_FAILED

     */
    inline ExplainabilityInfo& WithStatus(const Aws::String& value) { SetStatus(value); return *this;}

    /**
     *
The status of the Explainability. States include:

     * ACTIVE

 CREATE_PENDING,
     * CREATE_IN_PROGRESS, CREATE_FAILED

     * CREATE_STOPPING, CREATE_STOPPED

     * DELETE_PENDING, DELETE_IN_PROGRESS,
     * DELETE_FAILED

     */
    inline ExplainabilityInfo& WithStatus(Aws::String&& value) { SetStatus(std::move(value)); return *this;}

    /**
     *
The status of the Explainability. States include:

     * ACTIVE

 CREATE_PENDING,
     * CREATE_IN_PROGRESS, CREATE_FAILED

     * CREATE_STOPPING, CREATE_STOPPED

     * DELETE_PENDING, DELETE_IN_PROGRESS,
     * DELETE_FAILED

     */
    inline ExplainabilityInfo& WithStatus(const char* value) { SetStatus(value); return *this;}

  private:

    Aws::String m_explainabilityArn;
    bool m_explainabilityArnHasBeenSet = false;

    Aws::String m_status;
    bool m_statusHasBeenSet = false;
  };

} // namespace Model
} // namespace ForecastService
} // namespace Aws


text:
<?php
namespace AliyunMNS\Exception;

use AliyunMNS\Exception\MnsException;

class QueueNotExistException extends MnsException
{
}

?>


text:
package org.apache.geode.internal.cache.tier.sockets;

import static org.apache.geode.cache.client.PoolFactory.DEFAULT_SUBSCRIPTION_MESSAGE_TRACKING_TIMEOUT;
import static org.apache.geode.test.dunit.VM.getHostName;
import static org.apache.geode.test.dunit.VM.getVM;
import static org.assertj.core.api.Assertions.assertThat;

import java.io.Serializable;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.rules.CacheRule;
import org.apache.geode.test.dunit.rules.ClientCacheRule;
import org.apache.geode.test.dunit.rules.DistributedRule;
import org.apache.geode.test.junit.categories.ClientServerTest;
import org.apache.geode.test.junit.rules.serializable.SerializableTestName;

/**
 * TRAC #36995: gemfire.MessageTrackingTimeout should be set via configuration params for
 * BridgeLoader/BridgeWriter
 */
@Category({ClientServerTest.class})
public class MessageTrackingTimeoutRegressionTest implements Serializable {

  private static final int USER_SPECIFIED_MESSAGE_TRACKING_TIMEOUT = 54321;

  private String uniqueName;
  private String hostName;

  private int port1;
  private int port2;
  private int port3;

  private VM server1;
  private VM server2;
  private VM server3;

  @Rule
  public DistributedRule distributedRule = new DistributedRule();

  @Rule
  public CacheRule cacheRule = new CacheRule();

  @Rule
  public ClientCacheRule clientCacheRule = new ClientCacheRule();

  @Rule
  public SerializableTestName testName = new SerializableTestName();

  @Before
  public void setUp() throws Exception {
    server1 = getVM(0);
    server2 = getVM(1);
    server3 = getVM(2);

    uniqueName = getClass().getSimpleName() + "_" + testName.getMethodName();
    hostName = getHostName();

    port1 = server1.invoke(this::createServerCache);
    port2 = server2.invoke(this::createServerCache);
    port3 = server3.invoke(this::createServerCache);
  }

  @Test
  public void poolCreationUsesDefaultMessageTrackingTimeout() {
    createClientCacheWithDefaultMessageTrackingTimeout();

    assertThat(PoolManager.find(uniqueName).getSubscriptionMessageTrackingTimeout())
        .isEqualTo(DEFAULT_SUBSCRIPTION_MESSAGE_TRACKING_TIMEOUT);
  }

  @Test
  public void poolCreationUsesSetSubscriptionMessageTrackingTimeoutIfSpecified() {
    createClientCache();

    assertThat(findPool(uniqueName).getSubscriptionMessageTrackingTimeout())
        .isEqualTo(USER_SPECIFIED_MESSAGE_TRACKING_TIMEOUT);
  }

  private int createServerCache() throws Exception {
    cacheRule.createCache();

    // no region is created on server

    CacheServer cacheServer = cacheRule.getCache().addCacheServer();
    cacheServer.setPort(0);
    cacheServer.start();
    return cacheServer.getPort();
  }

  private void createClientCache() {
    clientCacheRule.createClientCache();

    PoolManager.createFactory().addServer(hostName, port1)
        .addServer(hostName, port2).addServer(hostName, port3).setSubscriptionEnabled(true)
        .setSubscriptionRedundancy(-1).setSubscriptionMessageTrackingTimeout(54321)
        .setIdleTimeout(-1).setPingInterval(200).create(uniqueName);
  }

  private void createClientCacheWithDefaultMessageTrackingTimeout() {
    clientCacheRule.createClientCache();

    PoolManager.createFactory().addServer(hostName, port1)
        .addServer(hostName, port2).addServer(hostName, port3).create(uniqueName);
  }

  private PoolImpl findPool(String name) {
    return (PoolImpl) PoolManager.find(name);
  }
}


text:
function CancelBatch(batch)

%CancelBatch - Cancel batch job.
%
%  USAGE
%
%    CancelBatch(batch)
%
%    batch          batch parameter returned by StartBatch
%
%  SEE
%
%    See also StartBatch, GetBatch, BatchInfo, CleanBatches, Store, Recall.
%

% Copyright (C) 2010-2011 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.

% Check number of parameters
if nargin < 1,
	error('Incorrect number of parameters (type ''help CancelBatch'' for details).');
end
if prod(size(batch)) ~=1 || ~isa(batch,'timer') || ~isvalid(batch) || ~strcmp(get(batch,'Tag'),'BatchJob'),
	error('Incorrect parameter (type ''help CancelBatch'' for details).');
end

k = input('Are you sure you wish to cancel this batch (y/N)? ','s');
if isempty(k) || ~strcmp(lower(k(1)),'y'), return; end

delete(batch);


text:
/**
 * Created by tanvir on 11/15/16.
 */

import  {Component} from "angular2/core";
import {ContactComponent} from "./contact.component";
import {ContactService} from "./contact.service";
import {Contact} from  "./contact";
import {OnInit} from "angular2/src/core/linker/interfaces";

@Component(
  {
    selector: "contact-list",
    template: `

    <ul>
          <li *ngFor="#contact of contacts"
          (click)="onSelect(contact)"
        [class.clicked]="selectedContact === contact ">
              {{contact.firstName}} {{contact.lastName | uppercase}}

          </li>
     </ul>

     <contact *ngIf="selectedContact !== null" [contact]="selectedContact"></contact>

`,
    directives: [ContactComponent],
    providers: [ContactService],
    styleUrls: ["../src/css/contact-list.css"]
  }
)

export class ContactListComponent implements OnInit{

  public contacts: Contact[];

  public selectedContact = null;

  constructor(private contactService: ContactService) {}

  onSelect(contact){
    this.selectedContact = contact;
  }

  getContacts(){
    this.contactService.getContacts().then((contacts: Contact[]) => this.contacts = contacts);
  }

  ngOnInit():any{

    this.getContacts();

  }

}


text:
require('simple_require');
var simple_requires_come_before_here;


text:
// Copyright (c) Microsoft Corporation. All Rights Reserved.
// Licensed under the MIT License.

using Datasync.Common.Test;
using Datasync.Common.Test.Models;
using Microsoft.Datasync.Client;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Threading.Tasks;
using Xunit;

namespace Microsoft.Datasync.Integration.Test.Client.RemoteTableOfT
{
    [ExcludeFromCodeCoverage]
    public class GetItemAsync_Tests : BaseOperationTest
    {
        [Fact]
        [Trait("Method", "GetItemAsync")]
        public async Task GetItemAsync_Basic()
        {
            // Arrange
            var id = GetRandomId();
            var expected = MovieServer.GetMovieById(id)!;

            // Act
            var response = await table.GetItemAsync(id).ConfigureAwait(false);

            // Assert
            AssertEx.SystemPropertiesMatch(expected, response);
            Assert.Equal<IMovie>(expected, response);
        }

        [Fact]
        [Trait("Method", "GetItemAsync")]
        public async Task GetItemAsync_NotFound()
        {
            // Arrange
            const string id = "not-found";

            // Act
            var exception = await Assert.ThrowsAsync<DatasyncInvalidOperationException>(() => table.GetItemAsync(id)).ConfigureAwait(false);

            // Assert
            Assert.NotNull(exception.Request);
            Assert.NotNull(exception.Response);
            Assert.Equal(HttpStatusCode.NotFound, exception.Response?.StatusCode);
        }

        [Fact]
        [Trait("Method", "GetItemAsync")]
        public async Task GetItemAsync_GetIfNotSoftDeleted()
        {
            // Arrange
            var id = GetRandomId();
            var expected = MovieServer.GetMovieById(id)!;

            // Act
            var response = await soft.GetItemAsync(id).ConfigureAwait(false);

            // Assert
            AssertEx.SystemPropertiesMatch(expected, response);
            Assert.Equal<IMovie>(expected, response);
        }

        [Fact]
        [Trait("Method", "GetItemAsync")]
        public async Task GetItemAsync_GoneIfSoftDeleted()
        {
            // Arrange
            var id = GetRandomId();
            await MovieServer.SoftDeleteMoviesAsync(x => x.Id == id).ConfigureAwait(false);
            var expected = MovieServer.GetMovieById(id)!;

            // Act
            var exception = await Assert.ThrowsAsync<DatasyncInvalidOperationException>(() => soft.GetItemAsync(id)).ConfigureAwait(false);

            // Assert
            Assert.NotNull(exception.Request);
            Assert.NotNull(exception.Response);
            Assert.Equal(HttpStatusCode.Gone, exception.Response?.StatusCode);
        }
    }
}


text:
import { RecordService } from './record_service';
import { CollectionService } from './collection_service';
import { UserService } from './user_service';
import { Collection } from '../models/collection';
import { Record } from '../models/record';
import { MockService } from './mock_service';
import { MockCollection } from '../models/mock_collection';
import { MockCollectionService } from './mock_collection_service';
import { Mock } from '../models/mock';

export class UserCollectionService {

    static async getUserCollections(userId: string): Promise<{ collections: Collection[], recordsList: { [key: string]: Record[] } }> {

        let collections = await this.getUserProjectCollections(userId);

        const recordsList = await RecordService.getByCollectionIds(collections.map(o => o.id), false, true);

        return { collections, recordsList };
    }

    static async getUserMockCollections(userId: string): Promise<{ mockCollections: MockCollection[], mockList: { [key: string]: Mock[] } }> {

        let mockCollections = await this.getUserProjectMockCollections(userId);

        const mockList = await MockService.getByCollectionIds(mockCollections.map(o => o.id), false);

        return { mockCollections, mockList };
    }

    static async getUserProjectCollections(userId: string): Promise<Collection[]> {
        const user = await UserService.getUserById(userId, true);

        if (!user) {
            return [];
        }

        const projectIds = user.projects.map(t => t.id);

        return await CollectionService.getByProjectIds(projectIds);
    }

    static async getUserProjectMockCollections(userId: string): Promise<MockCollection[]> {
        const user = await UserService.getUserById(userId, true);

        if (!user) {
            return [];
        }

        const projectIds = user.projects.map(t => t.id);

        return await MockCollectionService.getByProjectIds(projectIds);
    }
}


text:
package consul

import (
	"fmt"
	"strings"

	"github.com/golang/glog"
	"github.com/hashicorp/consul/api"

	"istio.io/pilot/model"
)

const (
	protocolTagName = "protocol"
	externalTagName = "external"
)

func convertLabels(labels []string) model.Labels {
	out := make(model.Labels, len(labels))
	for _, tag := range labels {
		vals := strings.Split(tag, "|")
		// Labels not of form "key|value" are ignored to avoid possible collisions
		if len(vals) > 1 {
			out[vals[0]] = vals[1]
		} else {
			glog.Warningf("Tag %v ignored since it is not of form key|value", tag)
		}
	}
	return out
}

func convertPort(port int, name string) *model.Port {
	if name == "" {
		name = "http"
	}

	return &model.Port{
		Name:     name,
		Port:     port,
		Protocol: convertProtocol(name),
	}
}

func convertService(endpoints []*api.CatalogService) *model.Service {
	name, addr, external := "", "", ""

	ports := make(map[int]*model.Port)
	for _, endpoint := range endpoints {
		name = endpoint.ServiceName

		port := convertPort(endpoint.ServicePort, endpoint.NodeMeta[protocolTagName])

		if svcPort, exists := ports[port.Port]; exists && svcPort.Protocol != port.Protocol {
			glog.Warningf("Service %v has two instances on same port %v but different protocols (%v, %v)",
				name, port.Port, svcPort.Protocol, port.Protocol)
		} else {
			ports[port.Port] = port
		}

		// TODO This will not work if service is a mix of external and local services
		// or if a service has more than one external name
		if endpoint.NodeMeta[externalTagName] != "" {
			external = endpoint.NodeMeta[externalTagName]
		}
	}

	svcPorts := make(model.PortList, 0, len(ports))
	for _, port := range ports {
		svcPorts = append(svcPorts, port)
	}

	out := &model.Service{
		Hostname:     serviceHostname(name),
		Ports:        svcPorts,
		Address:      addr,
		ExternalName: external,
	}

	return out
}

func convertInstance(instance *api.CatalogService) *model.ServiceInstance {
	labels := convertLabels(instance.ServiceTags)
	port := convertPort(instance.ServicePort, instance.NodeMeta[protocolTagName])

	addr := instance.ServiceAddress
	if addr == "" {
		addr = instance.Address
	}

	return &model.ServiceInstance{
		Endpoint: model.NetworkEndpoint{
			Address:     addr,
			Port:        instance.ServicePort,
			ServicePort: port,
		},

		Service: &model.Service{
			Hostname: serviceHostname(instance.ServiceName),
			Address:  instance.ServiceAddress,
			Ports:    model.PortList{port},
			// TODO ExternalName come from metadata?
			ExternalName: instance.NodeMeta[externalTagName],
		},
		Labels: labels,
	}
}

// serviceHostname produces FQDN for a consul service
func serviceHostname(name string) string {
	// TODO include datacenter in Hostname?
	// consul DNS uses "redis.service.us-east-1.consul" -> "[<optional_tag>].<svc>.service.[<optional_datacenter>].consul"
	return fmt.Sprintf("%s.service.consul", name)
}

// parseHostname extracts service name from the service hostname
func parseHostname(hostname string) (name string, err error) {
	parts := strings.Split(hostname, ".")
	if len(parts) < 1 {
		err = fmt.Errorf("missing service name from the service hostname %q", hostname)
		return
	}
	name = parts[0]
	return
}

func convertProtocol(name string) model.Protocol {
	switch name {
	case "tcp":
		return model.ProtocolTCP
	case "udp":
		return model.ProtocolUDP
	case "grpc":
		return model.ProtocolGRPC
	case "http":
		return model.ProtocolHTTP
	case "http2":
		return model.ProtocolHTTP2
	case "https":
		return model.ProtocolHTTPS
	case "mongo":
		return model.ProtocolMongo
	case "redis":
		return model.ProtocolRedis
	case "":
		// fallthrough to default protocol
	default:
		glog.Warningf("unsupported protocol value: %s", name)
	}
	return model.ProtocolTCP
}


text:
typedef void PAvoid;
typedef uint8_t PAbool;
typedef char PAchar;

typedef int8_t PAbyte;
typedef int16_t PAshort;
typedef int32_t PAint;
typedef int64_t PAlong;

typedef uint8_t PAubyte;
typedef uint16_t PAushort;
typedef uint32_t PAuint;
typedef uint64_t PAulong;

typedef float PAfloat;
typedef double PAdouble;

#endif // __COMMON_H__


text:
package com.fanxin.huangfangyi.main.uvod.ui.base;

import android.content.Context;

import com.fanxin.huangfangyi.R;
import com.ucloud.player.widget.v2.UVideoView;

import java.util.List;

/**
 * Created by leewen on 2015/8/11.
 */
public class UMenuItemHelper {
    private static final String TAG = "UMenuItemHelper";
    private static UMenuItem mMainMenuItem;
    private static UMenuItemHelper instance;
    private static Context mContext;
    private UMenuItemHelper(Context context) {
        mContext = context;
        mMainMenuItem = new UMenuItem.Builder().title(mContext.getResources().getString(R.string.menu_main_title))
                .index(0)
                .builder();
    }

    public static UMenuItemHelper getInstance(Context context) {
        if (instance == null) {
            synchronized (UMenuItemHelper.class) {
                if (instance == null) {
                    instance = new UMenuItemHelper(context);
                }
            }
        }
        return instance;
    }

    private String get(String[] names, String types[], String type) {
        for(int i =0; i < types.length; i++) {
            if (type.equalsIgnoreCase(types[i])) {
                return names[i];
            }
        }
        return type;
    }

   public UMenuItem buildVideoDefinitationMenuItem(List<UVideoView.DefinitionType> definitions, int index) {
        UMenuItem menuItem = new UMenuItem.Builder().title(mContext.getResources().getString(R.string.menu_item_title_definition)).index(index).builder();
        String[] retNames = mContext.getResources().getStringArray(R.array.pref_definition_names);
        String[] retValues = mContext.getResources().getStringArray(R.array.pref_definition_values);
        for(UVideoView.DefinitionType definition: definitions) {
            String title = get(retNames, retValues, definition.name());
            menuItem.childs.add(new UMenuItem.Builder().title(title).type(title).parent(menuItem).builder());
        }
        return menuItem;
    }

    public UMenuItem buildVideoDecoderMenuItem(int defaultSelect) {
       return buildVideoMenuItem(
               mContext.getResources().getString(R.string.menu_item_title_decoder),
               R.array.pref_decoder_names,
               R.array.pref_decoder_values,
               defaultSelect);
    }

    public UMenuItem buildVideoRatioMenuItem(int defaultSelect) {
        return buildVideoMenuItem(
                mContext.getResources().getString(R.string.menu_item_title_ratio),
                R.array.pref_screen_ratio_names,
                R.array.pref_screen_ratio_values,
                defaultSelect);
    }

    public UMenuItem buildVideoMenuItem(String title, int resNameId, int resValueId, int defaultSelect) {
        UMenuItem menuItem = new UMenuItem.Builder().title(title).index(defaultSelect).builder();
        String[] retNames = mContext.getResources().getStringArray(resNameId);
        String[] types = mContext.getResources().getStringArray(resValueId);
        for(int i = 0; i < retNames.length; i++) {
            menuItem.childs.add(new UMenuItem.Builder().title(retNames[i]).type(types[i] + "").parent(menuItem).builder());
        }
        return menuItem;
    }

    public UMenuItem register(UMenuItem child) {
        if (mMainMenuItem != null && !mMainMenuItem.childs.contains(child)) {
            mMainMenuItem.childs.add(child);
        }
        return mMainMenuItem;
    }

    public UMenuItem register(UMenuItem child, int location) {
        if (mMainMenuItem != null && !mMainMenuItem.childs.contains(child)) {
            mMainMenuItem.childs.add(location, child);
        }
        return mMainMenuItem;
    }

    public UMenuItem unRegister(UMenuItem child) {
        if (mMainMenuItem != null && mMainMenuItem.childs.contains(child)) {
            mMainMenuItem.childs.remove(child);
        }
        return mMainMenuItem;
    }

    public UMenuItem getMainMenu() {
        return mMainMenuItem;
    }

    public void release() {
        if (mMainMenuItem != null && mMainMenuItem.childs != null) {
            mMainMenuItem.childs.clear();
            instance = null;
            mMainMenuItem = null;
        }
    }
}


text:
class AddMoipIdColumnToUsersTable < ActiveRecord::Migration
  def change
    add_column :users, :moip_code, :string
  end
end


text:
/*
 * TIFF Library.
 */
#include "tiffiop.h"
#include <string.h>

/************************************************************************/
/*                            TIFFCleanup()                             */
/************************************************************************/

/**
 * Auxiliary function to free the TIFF structure. Given structure will be
 * completetly freed, so you should save opened file handle and pointer
 * to the close procedure in external variables before calling
 * _TIFFCleanup(), if you will need these ones to close the file.
 *
 * @param tif A TIFF pointer.
 */

void
TIFFCleanup(TIFF* tif)
{
	/*
         * Flush buffered data and directory (if dirty).
         */
	if (tif->tif_mode != O_RDONLY)
		TIFFFlush(tif);
	(*tif->tif_cleanup)(tif);
	TIFFFreeDirectory(tif);

	if (tif->tif_dirlist)
		_TIFFfree(tif->tif_dirlist);

	/*
         * Clean up client info links.
         */
	while( tif->tif_clientinfo )
	{
		TIFFClientInfoLink *link = tif->tif_clientinfo;

		tif->tif_clientinfo = link->next;
		_TIFFfree( link->name );
		_TIFFfree( link );
	}

	if (tif->tif_rawdata && (tif->tif_flags&TIFF_MYBUFFER))
		_TIFFfree(tif->tif_rawdata);
	if (isMapped(tif))
		TIFFUnmapFileContents(tif, tif->tif_base, (toff_t)tif->tif_size);

	/*
         * Clean up custom fields.
         */
	if (tif->tif_fields && tif->tif_nfields > 0) {
		uint32 i;

		for (i = 0; i < tif->tif_nfields; i++) {
			TIFFField *fld = tif->tif_fields[i];
			if (fld->field_bit == FIELD_CUSTOM &&
			    strncmp("Tag ", fld->field_name, 4) == 0) {
				_TIFFfree(fld->field_name);
				_TIFFfree(fld);
			}
		}

		_TIFFfree(tif->tif_fields);
	}

        if (tif->tif_nfieldscompat > 0) {
                uint32 i;

                for (i = 0; i < tif->tif_nfieldscompat; i++) {
                        if (tif->tif_fieldscompat[i].allocated_size)
                                _TIFFfree(tif->tif_fieldscompat[i].fields);
                }
                _TIFFfree(tif->tif_fieldscompat);
        }

	_TIFFfree(tif);
}

/************************************************************************/
/*                            TIFFClose()                               */
/************************************************************************/

/**
 * Close a previously opened TIFF file.
 *
 * TIFFClose closes a file that was previously opened with TIFFOpen().
 * Any buffered data are flushed to the file, including the contents of
 * the current directory (if modified); and all resources are reclaimed.
 *
 * @param tif A TIFF pointer.
 */

void
TIFFClose(TIFF* tif)
{
	TIFFCloseProc closeproc = tif->tif_closeproc;
	thandle_t fd = tif->tif_clientdata;

	TIFFCleanup(tif);
	(void) (*closeproc)(fd);
}

/* vim: set ts=8 sts=8 sw=8 noet: */

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 8
 * fill-column: 78
 * End:
 */


text:
#if NET452
#else
using Microsoft.AspNetCore.Http;
#endif
using System.Net.Http;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CacheCow.Server.Headers
{
    public static class CacheCowHeaderExtensions
    {
        /// <summary>
        /// Extracts CacheCowHeader (server) if one exists
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static CacheCowHeader GetCacheCowHeader(
            this HttpResponseMessage response)
        {
            CacheCowHeader header = null;
            if (response.Headers.Contains(CacheCowHeader.Name))
            {
                CacheCowHeader.TryParse(response.Headers.GetValues(CacheCowHeader.Name).FirstOrDefault(), out header);
            }

            return header;
        }

#if NET452
#else
        /// <summary>
        /// Extracts CacheCowHeader (server) if one exists
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static CacheCowHeader GetCacheCowHeader(
            this HttpResponse response)
        {
            CacheCowHeader header = null;
            if (response.Headers.ContainsKey(CacheCowHeader.Name))
            {
                CacheCowHeader.TryParse(response.Headers[CacheCowHeader.Name], out header);
            }

            return header;
        }
#endif
    }
}


text:
package org.killbill.billing.plugin.adyen.client.payment.service;

import java.math.BigDecimal;
import java.util.Currency;
import java.util.UUID;

import org.killbill.billing.plugin.adyen.TestRemoteBase;
import org.killbill.billing.plugin.adyen.client.model.OrderData;
import org.killbill.billing.plugin.adyen.client.model.PaymentData;
import org.killbill.billing.plugin.adyen.client.model.PaymentModificationResponse;
import org.killbill.billing.plugin.adyen.client.model.PaymentProvider;
import org.killbill.billing.plugin.adyen.client.model.PaymentType;
import org.killbill.billing.plugin.adyen.client.model.PurchaseResult;
import org.killbill.billing.plugin.adyen.client.model.SplitSettlementData;
import org.killbill.billing.plugin.adyen.client.model.UserData;
import org.killbill.billing.plugin.adyen.client.model.paymentinfo.CreditCard;
import org.testng.Assert;
import org.testng.annotations.Test;

import static org.testng.Assert.assertFalse;

public class TestRemoteAdyenPaymentServiceProviderPort extends TestRemoteBase {

    @Test(groups = "slow")
    public void testAuthorizeAndMultiplePartialCaptures() throws Exception {
        final BigDecimal authAmount = BigDecimal.TEN;
        final PaymentData<CreditCard> paymentData = new PaymentData<CreditCard>();
        paymentData.setPaymentTxnInternalRef(UUID.randomUUID().toString());
        paymentData.setPaymentInfo(getCreditCard());
        final OrderData orderData = new OrderData();
        final UserData userData = new UserData();
        final String termUrl = null;
        final SplitSettlementData splitSettlementData = null;

        final PurchaseResult authorizeResult = adyenPaymentServiceProviderPort.authorise(authAmount, paymentData, orderData, userData, termUrl, splitSettlementData);
        // Adyen's unique reference that is associated with the payment
        Assert.assertNotNull(authorizeResult.getPspReference());
        // Result of the payment. The possible values are Authorised, Refused, Error or Received (as with a Dutch Direct Debit)
        Assert.assertEquals(authorizeResult.getResultCode(), "Authorised");
        // The authorisation code if the payment was successful. Blank otherwise
        Assert.assertNotNull(authorizeResult.getAuthCode());
        // Adyen's mapped refusal reason, populated if the payment was refused
        Assert.assertNull(authorizeResult.getReason());

        final BigDecimal captureAmount = new BigDecimal("5");
        final PaymentProvider paymentProvider = paymentData.getPaymentInfo().getPaymentProvider();
        final String pspReference = authorizeResult.getPspReference();

        // First capture
        final PaymentModificationResponse capture1Result = adyenPaymentServiceProviderPort.capture(captureAmount, paymentProvider, pspReference, splitSettlementData);
        Assert.assertNotNull(capture1Result.getPspReference());
        Assert.assertEquals(capture1Result.getResponse(), "[capture-received]");

        // Second capture
        final PaymentModificationResponse capture2Result = adyenPaymentServiceProviderPort.capture(captureAmount, paymentProvider, pspReference, splitSettlementData);
        Assert.assertNotNull(capture2Result.getPspReference());
        Assert.assertEquals(capture2Result.getResponse(), "[capture-received]");
    }

    @Test(groups = "slow")
    public void testAuthorizeAndVoid() throws Exception {
        final BigDecimal authAmount = BigDecimal.TEN;
        final PaymentData<CreditCard> paymentData = new PaymentData<CreditCard>();
        paymentData.setPaymentTxnInternalRef(UUID.randomUUID().toString());
        paymentData.setPaymentInfo(getCreditCard());
        final OrderData orderData = new OrderData();
        final UserData userData = new UserData();
        final String termUrl = null;
        final SplitSettlementData splitSettlementData = null;

        final PurchaseResult authorizeResult = adyenPaymentServiceProviderPort.authorise(authAmount, paymentData, orderData, userData, termUrl, splitSettlementData);
        Assert.assertNotNull(authorizeResult.getPspReference());
        Assert.assertEquals(authorizeResult.getResultCode(), "Authorised");
        Assert.assertNotNull(authorizeResult.getAuthCode());
        Assert.assertNull(authorizeResult.getReason());

        final PaymentProvider paymentProvider = paymentData.getPaymentInfo().getPaymentProvider();
        final String pspReference = authorizeResult.getPspReference();

        final PaymentModificationResponse voidResult = adyenPaymentServiceProviderPort.cancel(paymentProvider, pspReference, splitSettlementData);
        Assert.assertNotNull(voidResult.getPspReference());
        Assert.assertEquals(voidResult.getResponse(), "[cancel-received]");
    }

    @Test(groups = "slow")
    public void testAuthorizeCaptureAndRefund() throws Exception {
        final BigDecimal authAmount = BigDecimal.TEN;
        final PaymentData<CreditCard> paymentData = new PaymentData<CreditCard>();
        paymentData.setPaymentTxnInternalRef(UUID.randomUUID().toString());
        paymentData.setPaymentInfo(getCreditCard());
        final OrderData orderData = new OrderData();
        final UserData userData = new UserData();
        final String termUrl = null;
        final SplitSettlementData splitSettlementData = null;

        final PurchaseResult authorizeResult = adyenPaymentServiceProviderPort.authorise(authAmount, paymentData, orderData, userData, termUrl, splitSettlementData);
        Assert.assertNotNull(authorizeResult.getPspReference());
        Assert.assertEquals(authorizeResult.getResultCode(), "Authorised");
        Assert.assertNotNull(authorizeResult.getAuthCode());
        Assert.assertNull(authorizeResult.getReason());

        //noinspection UnnecessaryLocalVariable
        final BigDecimal captureAmount = authAmount;
        final PaymentProvider paymentProvider = paymentData.getPaymentInfo().getPaymentProvider();
        final String capturePspReference = authorizeResult.getPspReference();

        final PaymentModificationResponse captureResult = adyenPaymentServiceProviderPort.capture(captureAmount, paymentProvider, capturePspReference, splitSettlementData);
        Assert.assertNotNull(captureResult.getPspReference());
        Assert.assertEquals(captureResult.getResponse(), "[capture-received]");

        //noinspection UnnecessaryLocalVariable
        final BigDecimal refundAmount = captureAmount;
        final String refundPspReference = captureResult.getPspReference();

        final PaymentModificationResponse refundResult = adyenPaymentServiceProviderPort.refund(refundAmount, paymentProvider, refundPspReference, splitSettlementData);
        Assert.assertNotNull(refundResult.getPspReference());
        Assert.assertEquals(refundResult.getResponse(), "[refund-received]");
    }

    @Test(groups = "slow")
    public void testAuthorizeAndBadVoid() throws Exception {
        final BigDecimal authAmount = BigDecimal.TEN;
        final PaymentData<CreditCard> paymentData = new PaymentData<CreditCard>();
        paymentData.setPaymentTxnInternalRef(UUID.randomUUID().toString());
        paymentData.setPaymentInfo(getCreditCard());
        final OrderData orderData = new OrderData();
        final UserData userData = new UserData();
        final String termUrl = null;
        final SplitSettlementData splitSettlementData = null;

        final PurchaseResult authorizeResult = adyenPaymentServiceProviderPort.authorise(authAmount, paymentData, orderData, userData, termUrl, splitSettlementData);
        Assert.assertNotNull(authorizeResult.getPspReference());
        Assert.assertEquals(authorizeResult.getResultCode(), "Authorised");
        Assert.assertNotNull(authorizeResult.getAuthCode());
        Assert.assertNull(authorizeResult.getReason());

        final PaymentProvider paymentProvider = paymentData.getPaymentInfo().getPaymentProvider();
        final String pspReference = UUID.randomUUID().toString();

        final PaymentModificationResponse voidResult = adyenPaymentServiceProviderPort.cancel(paymentProvider, pspReference, splitSettlementData);
        assertFalse(voidResult.isTechnicallySuccessful());
    }

    private CreditCard getCreditCard() {
        final PaymentProvider paymentProvider = new PaymentProvider(adyenConfigProperties);
        paymentProvider.setCurrency(Currency.getInstance(DEFAULT_CURRENCY.name()));
        paymentProvider.setCountryIsoCode(DEFAULT_COUNTRY);
        paymentProvider.setPaymentType(PaymentType.CREDITCARD);

        final CreditCard paymentInfo = new CreditCard(paymentProvider);
        paymentInfo.setCcHolderName("Dupont");
        paymentInfo.setCcNumber(CC_NUMBER);
        paymentInfo.setValidUntilMonth(CC_EXPIRATION_MONTH);
        paymentInfo.setValidUntilYear(CC_EXPIRATION_YEAR);
        paymentInfo.setCcSecCode(CC_VERIFICATION_VALUE);

        return paymentInfo;
    }
}


text:
```
# make/activate a venv if you wish
pip install flask
pip install twilio

git clone https://github.com/tr3buchet/gatecontrol.git
cd gatecontrol

cp gatecontrol.conf ~/.gatecontrol/gatecontrol.conf
# edit ~/.gatecontrol/gatecontrol.conf for your setup
```

## run
python gatecontrol.py


text:
body {
    margin-top: 50px; /* Required margin for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */
}

.image-bg-fluid-height,
.image-bg-fixed-height {
    text-align: center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
}

.image-bg-fluid-height {
	background: url('https://cbi-blog.s3.amazonaws.com/blog/wp-content/uploads/2014/05/EdTech_ipad.jpg') no-repeat center center scroll;
    padding: 100px 0;
}

.image-bg-fixed-height {
	background: url('https://cbi-blog.s3.amazonaws.com/blog/wp-content/uploads/2014/05/EdTech_ipad.jpg') no-repeat center center scroll;
    height: 450px;
}

.img-center {
	margin: 0 auto;
}

section {
    padding: 75px 0;
}

.section-heading {
    margin: 30px 0;
    font-size: 4em;
}

.section-lead {
    margin: 30px 0;
}

.section-paragraph {
    margin: 30px 0;
}

footer {
    margin: 50px 0;
}

@media(max-width:768px) {
    section {
        padding-top: 25px;
        padding-bottom: 25px;
    }

    .section-heading {
        font-size: 2em;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.srotya</groupId>
    <artifactId>srotya-parent</artifactId>
    <version>0.5.6</version>
  </parent>
  <groupId>com.srotya.flume</groupId>
  <artifactId>flume-kinesis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>flume-kinesis</name>
  <description>Kinesis Source and Sink for Apache Flume</description>
  <properties>
    <flume.version>1.6.0</flume.version>
    <kinesis.version>1.11.6</kinesis.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-kinesis</artifactId>
      <version>${kinesis.version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.6.2</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.flume</groupId>
      <artifactId>flume-ng-core</artifactId>
      <version>${flume.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.10.19</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>src/test/resources</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </testResource>
    </testResources>
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>single</goal>
            </goals>
            <phase>package</phase>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <url>https://github.com/srotya/flume-kinesis</url>
  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
    </license>
  </licenses>
  <developers>
    <developer>
      <id>asharma</id>
      <name>Ambud Sharma</name>
      <organization>Srotya</organization>
    </developer>
  </developers>
  <scm>
    <connection>scm:git:git@github.com:srotya/flume-kinesis.git</connection>
    <developerConnection>scm:git:git@github.com:srotya/flume-kinesis.git</developerConnection>
    <url>https://github.com/srotya/flume-kinesis.git</url>
    <tag>HEAD</tag>
  </scm>
</project>


text:
*> \brief \b CTRT06
*
*  =========== DOCUMENTATION ===========
*
* Online html documentation available at
*            http://www.netlib.org/lapack/explore-html/
*
*  Definition:
*  ===========
*
*       SUBROUTINE CTRT06( RCOND, RCONDC, UPLO, DIAG, N, A, LDA, RWORK,
*                          RAT )
*
*       .. Scalar Arguments ..
*       CHARACTER          DIAG, UPLO
*       INTEGER            LDA, N
*       REAL               RAT, RCOND, RCONDC
*       ..
*       .. Array Arguments ..
*       REAL               RWORK( * )
*       COMPLEX            A( LDA, * )
*       ..
*
*
*> \par Purpose:
*  =============
*>
*> \verbatim
*>
*> CTRT06 computes a test ratio comparing RCOND (the reciprocal
*> condition number of a triangular matrix A) and RCONDC, the estimate
*> computed by CTRCON.  Information about the triangular matrix A is
*> used if one estimate is zero and the other is non-zero to decide if
*> underflow in the estimate is justified.
*> \endverbatim
*
*  Arguments:
*  ==========
*
*> \param[in] RCOND
*> \verbatim
*>          RCOND is REAL
*>          The estimate of the reciprocal condition number obtained by
*>          forming the explicit inverse of the matrix A and computing
*>          RCOND = 1/( norm(A) * norm(inv(A)) ).
*> \endverbatim
*>
*> \param[in] RCONDC
*> \verbatim
*>          RCONDC is REAL
*>          The estimate of the reciprocal condition number computed by
*>          CTRCON.
*> \endverbatim
*>
*> \param[in] UPLO
*> \verbatim
*>          UPLO is CHARACTER
*>          Specifies whether the matrix A is upper or lower triangular.
*>          = 'U':  Upper triangular
*>          = 'L':  Lower triangular
*> \endverbatim
*>
*> \param[in] DIAG
*> \verbatim
*>          DIAG is CHARACTER
*>          Specifies whether or not the matrix A is unit triangular.
*>          = 'N':  Non-unit triangular
*>          = 'U':  Unit triangular
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*>          N is INTEGER
*>          The order of the matrix A.  N >= 0.
*> \endverbatim
*>
*> \param[in] A
*> \verbatim
*>          A is COMPLEX array, dimension (LDA,N)
*>          The triangular matrix A.  If UPLO = 'U', the leading n by n
*>          upper triangular part of the array A contains the upper
*>          triangular matrix, and the strictly lower triangular part of
*>          A is not referenced.  If UPLO = 'L', the leading n by n lower
*>          triangular part of the array A contains the lower triangular
*>          matrix, and the strictly upper triangular part of A is not
*>          referenced.  If DIAG = 'U', the diagonal elements of A are
*>          also not referenced and are assumed to be 1.
*> \endverbatim
*>
*> \param[in] LDA
*> \verbatim
*>          LDA is INTEGER
*>          The leading dimension of the array A.  LDA >= max(1,N).
*> \endverbatim
*>
*> \param[out] RWORK
*> \verbatim
*>          RWORK is REAL array, dimension (N)
*> \endverbatim
*>
*> \param[out] RAT
*> \verbatim
*>          RAT is REAL
*>          The test ratio.  If both RCOND and RCONDC are nonzero,
*>             RAT = MAX( RCOND, RCONDC )/MIN( RCOND, RCONDC ) - 1.
*>          If RAT = 0, the two estimates are exactly the same.
*> \endverbatim
*
*  Authors:
*  ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2011
*
*> \ingroup complex_lin
*
*  =====================================================================
      SUBROUTINE CTRT06( RCOND, RCONDC, UPLO, DIAG, N, A, LDA, RWORK,
     $                   RAT )
*
*  -- LAPACK test routine (version 3.4.0) --
*  -- LAPACK is a software package provided by Univ. of Tennessee,    --
*  -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
*     November 2011
*
*     .. Scalar Arguments ..
      CHARACTER          DIAG, UPLO
      INTEGER            LDA, N
      REAL               RAT, RCOND, RCONDC
*     ..
*     .. Array Arguments ..
      REAL               RWORK( * )
      COMPLEX            A( LDA, * )
*     ..
*
*  =====================================================================
*
*     .. Parameters ..
      REAL               ZERO, ONE
      PARAMETER          ( ZERO = 0.0E+0, ONE = 1.0E+0 )
*     ..
*     .. Local Scalars ..
      REAL               ANORM, BIGNUM, EPS, RMAX, RMIN
*     ..
*     .. External Functions ..
      REAL               CLANTR, SLAMCH
      EXTERNAL           CLANTR, SLAMCH
*     ..
*     .. Intrinsic Functions ..
      INTRINSIC          MAX, MIN
*     ..
*     .. Executable Statements ..
*
      EPS = SLAMCH( 'Epsilon' )
      RMAX = MAX( RCOND, RCONDC )
      RMIN = MIN( RCOND, RCONDC )
*
*     Do the easy cases first.
*
      IF( RMIN.LT.ZERO ) THEN
*
*        Invalid value for RCOND or RCONDC, return 1/EPS.
*
         RAT = ONE / EPS
*
      ELSE IF( RMIN.GT.ZERO ) THEN
*
*        Both estimates are positive, return RMAX/RMIN - 1.
*
         RAT = RMAX / RMIN - ONE
*
      ELSE IF( RMAX.EQ.ZERO ) THEN
*
*        Both estimates zero.
*
         RAT = ZERO
*
      ELSE
*
*        One estimate is zero, the other is non-zero.  If the matrix is
*        ill-conditioned, return the nonzero estimate multiplied by
*        1/EPS; if the matrix is badly scaled, return the nonzero
*        estimate multiplied by BIGNUM/TMAX, where TMAX is the maximum
*        element in absolute value in A.
*
         BIGNUM = ONE / SLAMCH( 'Safe minimum' )
         ANORM = CLANTR( 'M', UPLO, DIAG, N, N, A, LDA, RWORK )
*
         RAT = RMAX*( MIN( BIGNUM / MAX( ONE, ANORM ), ONE / EPS ) )
      END IF
*
      RETURN
*
*     End of CTRT06
*
      END


text:
class Kaui::AuditLog

  def self.description(log)
    if log.changed_by.present?
      changed_str = "#{log.change_type} by #{log.changed_by.strip}"
      if log.reason_code.blank? && log.comments.blank?
        changed_str
      elsif log.reason_code.blank?
        "#{changed_str}: #{log.comments.strip}"
      elsif log.comments.blank?
        "#{changed_str}: #{log.reason_code.strip}"
      else
        "#{changed_str} (#{log.reason_code.strip} #{log.comments.strip})"
      end
    end
  end
end


text:
package com.fererlab.nio;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

public class BlockingClient {

    private String hostname = "localhost";
    private int port = 8992;

    public static void main(String[] args) {
        new BlockingClient();
    }

    public BlockingClient() {
        for (int i = 0; i < 10; i++) {
            final int currentClientIndex = i;
            new Thread() {
                @Override
                public void run() {
                    doRequest(currentClientIndex);
                }
            }.start();
        }
    }

    private void doRequest(int currentClientIndex) {
        try {
            Socket socket = new Socket(InetAddress.getByName(hostname), port); // open connection
            BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
            OutputStreamWriter osw = new OutputStreamWriter(bos);
            osw.write("this is client " + currentClientIndex);
            osw.flush();

            BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
            InputStreamReader inputStreamReader = new InputStreamReader(bufferedInputStream);
            StringBuilder stringBuilder = new StringBuilder();
            int read;
            while ((read = inputStreamReader.read()) != 13) {
                char readChar = (char) read;
                if (read == -1) {
                    break;
                }
                stringBuilder.append(readChar);
            }
            System.out.println(currentClientIndex + ": response: " + stringBuilder.toString().trim());
            socket.close();
        } catch (Exception e) {
            System.out.println("----- [" + currentClientIndex + "] exception e: " + e.getMessage());
        }
    }
}