text:
package database

import (
	"fmt"
	"strings"

	"kube-helper/util"

	"github.com/urfave/cli"
	"google.golang.org/api/sqladmin/v1beta4"
)

func CmdCleanup(c *cli.Context) error {

	configContainer, err := configLoader.LoadConfigFromPath(c.String("config"))

	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}

	sqlService, err := serviceBuilder.GetSQLService()

	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}

	branches, err := branchLoader.LoadBranches(configContainer.Bitbucket)

	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	databases, err := getDatabases(sqlService, configContainer.Cluster.ProjectID, configContainer.Database.Instance)

	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}

	for _, database := range databases {
		if !strings.HasPrefix(database, configContainer.Database.PrefixBranchDatabase) {
			continue
		}

		branch := strings.TrimPrefix(database, configContainer.Database.PrefixBranchDatabase)

		if util.Contains(branches, branch) == false {
			operation, err := sqlService.Databases.Delete(configContainer.Cluster.ProjectID, configContainer.Database.Instance, database).Do()
			if err != nil {
				return cli.NewExitError(err.Error(), 1)
			}
			err = waitForOperationToFinish(sqlService, operation, configContainer.Cluster.ProjectID, "delete of database")
			if err != nil {
				return cli.NewExitError(err.Error(), 1)
			}

			fmt.Fprintf(writer, "Removed database %s", database)
		}
	}

	return nil
}

func getDatabases(sqlService *sqladmin.Service, projectID string, instance string) ([]string, error) {
	list, err := sqlService.Databases.List(projectID, instance).Do()

	if err != nil {
		return nil, err
	}

	var databases []string

	for _, database := range list.Items {
		databases = append(databases, database.Name)
	}

	return databases, nil
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="author" xontent="Yiqing Lu">
	<title>pizza order form</title>

Pizza Guys Order Form

	<form id="myForm" method="Get">

Name
<input type="text" name="name" class="clear" size="33" placeholder="your name" required>

Address: #### Street Name ...
<input type="text" name="address" class="clear" size="52" placeholder="delivery address" required>

Phone Number: 123-123-1234
<input type="text" name="phone" class="clear" placeholder="123-123-1234" pattern="\d\d\d-\d\d\d-\d\d\d\d">

	    Pizza size

    	<input type="radio" name="size" value="large" required>Large
	    <input type="radio" name="size" value="medium">Medium
	    <input type="radio" name="size" value="small">Small

	    Pizza Topping

	    <input type="checkbox" name="topping" value="sausage" />Sausage
	    <input type="checkbox" name="topping" value="pepperoni" />Pepperoni
	    <input type="checkbox" name="topping" value="olives" />Olives
	    <input type="checkbox" name="topping" value="anchovies" />Anchovies
	    <input type="checkbox" name="topping" value="onions" />Onions

	    <input type="hidden" name="timestamp">

	    <input type="submit" value="Place Order" onclick="return doValidate()">
		<input type="reset" value="Clear">

	</form>

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.digitaltwins.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** The properties of a private endpoint connection. */
@Fluent
public final class ConnectionProperties {
    /*
     * The provisioning state.
     */
    @JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
    private ConnectionPropertiesProvisioningState provisioningState;

    /*
     * The private endpoint.
     */
    @JsonProperty(value = "privateEndpoint")
    private PrivateEndpoint privateEndpoint;

    /*
     * The list of group ids for the private endpoint connection.
     */
    @JsonProperty(value = "groupIds")
    private List<String> groupIds;

    /*
     * The connection state.
     */
    @JsonProperty(value = "privateLinkServiceConnectionState")
    private ConnectionPropertiesPrivateLinkServiceConnectionState privateLinkServiceConnectionState;

    /**
     * Get the provisioningState property: The provisioning state.
     *
     * @return the provisioningState value.
     */
    public ConnectionPropertiesProvisioningState provisioningState() {
        return this.provisioningState;
    }

    /**
     * Get the privateEndpoint property: The private endpoint.
     *
     * @return the privateEndpoint value.
     */
    public PrivateEndpoint privateEndpoint() {
        return this.privateEndpoint;
    }

    /**
     * Set the privateEndpoint property: The private endpoint.
     *
     * @param privateEndpoint the privateEndpoint value to set.
     * @return the ConnectionProperties object itself.
     */
    public ConnectionProperties withPrivateEndpoint(PrivateEndpoint privateEndpoint) {
        this.privateEndpoint = privateEndpoint;
        return this;
    }

    /**
     * Get the groupIds property: The list of group ids for the private endpoint connection.
     *
     * @return the groupIds value.
     */
    public List<String> groupIds() {
        return this.groupIds;
    }

    /**
     * Set the groupIds property: The list of group ids for the private endpoint connection.
     *
     * @param groupIds the groupIds value to set.
     * @return the ConnectionProperties object itself.
     */
    public ConnectionProperties withGroupIds(List<String> groupIds) {
        this.groupIds = groupIds;
        return this;
    }

    /**
     * Get the privateLinkServiceConnectionState property: The connection state.
     *
     * @return the privateLinkServiceConnectionState value.
     */
    public ConnectionPropertiesPrivateLinkServiceConnectionState privateLinkServiceConnectionState() {
        return this.privateLinkServiceConnectionState;
    }

    /**
     * Set the privateLinkServiceConnectionState property: The connection state.
     *
     * @param privateLinkServiceConnectionState the privateLinkServiceConnectionState value to set.
     * @return the ConnectionProperties object itself.
     */
    public ConnectionProperties withPrivateLinkServiceConnectionState(
        ConnectionPropertiesPrivateLinkServiceConnectionState privateLinkServiceConnectionState) {
        this.privateLinkServiceConnectionState = privateLinkServiceConnectionState;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (privateEndpoint() != null) {
            privateEndpoint().validate();
        }
        if (privateLinkServiceConnectionState() != null) {
            privateLinkServiceConnectionState().validate();
        }
    }
}


text:
An assertions framework for .NET with a BDD-like feel, inspired by Chai and Jasmine, designed to be user-extensible

![Build and Test](https://github.com/fluffynuts/NExpect/workflows/Build%20and%20Test/badge.svg)

![Nuget current version badge](https://img.shields.io/nuget/v/NExpect)

## Goals
- Expect(NExpect).To.Be.Readable();
  - Because code is for co-workers, not compilers. And your tests are part of your documentation.
- Expect(NExpect).To.Be.Expressive();
  - Because the intent of a test should be easy to understand. The reader can delve into the details when she cares to.
- Expect(NExpect).To.Be.Extensible();
  - Because I can't predict every use-case. I believe that your assertions framework should enable expressive, readable tests through extension.

## Tutorial / blog posts:
[https://fluffynuts.github.io/NExpect](https://fluffynuts.github.io/NExpect)
[dev.to](https://dev.to/fluffynuts/introducing-nexpect-555c)

## Usage
1. Download from [nuget.org](https://nuget.org): `install-package nexpect`
2. Import Expectations statically:
```csharp
using static NExpect.Expectations;
```
3. `Expect` inside your tests, with fluent syntax:
```csharp
// simple equality checks
Expect(1).To.Equal(1);
Expect(true).To.Not.Be.False(); // alt. grammar
Expect(null).To.Be.Null();
// - with negation, order doesn't matter
Expect("moo").Not.To.Equal("cow");
Expect("moo").To.Not.Equal("cow");
Expect(true).Not.To.Be.False();
Expect(false).To.Not.Be.True();

// exceptions
Expect(() => { }).Not.To.Throw();
Expect(() =>
  {
    throw new ArgumentException("moo", "moo cow");
  }).To.Throw<ArgumentException>()
  .With.Message.Containing("moo")
  .And.("cow");

// smarter string tests, with fluency
Expect(someString).To.Contain("moo").And("cow");
Expect("moo, said the cow")
    .To.Start.With("moo")
    .And.Contain("said")
    .Then("the")
    .And.End.With("cow");

// collection tests
Expect(someCollection).To.Contain.Exactly(2)
  .Matched.By(item => item.IsWhatWeWant());
Expect(someCollection).To.Contain.Only(1)
  .Deep.Equal.To(new { id = 42, name = "Douglas" });
Expect(someFlags).To.Contain.At.Least(3)
  .Equal.To(true);
Expect(new[] { 1, 2, 3 })
  .To.Be.Ordered.Ascending();
Expect(new[] { "c", "b", "a" })
  .To.Be.Ordered.Descending();

// type testing
Expect(someObject).To.Be
  .An.Instance.Of<Cow>();

// deep and intersection equality testing
var person = new {
  id = 1,
  name = "bob"
};
Expect(person)
  .To.Deep.Equal(new { id = 1, name = "bob" });
Expect(person)
  .To.Intersection.Equal(new { name = "bob" });
```

## Extending
Mostly, you can extend by adding extension methods for ICanAddMatcher<T> where T is the
type you want. You can also extend at any point in the grammar -- some of the "better"
points are ITo<T>, IBe<T>, IHave<T>, IA<T>, IAn<T>. You will need another namespace import:
```csharp
using NExpect.MatcherLogic
```
And your extension methods can be like:

```csharp
public static class MyMatchers
{
  public static void Five(this IBe<int> continuation)
  {
    continuation.AddMatcher(actual =>
    {
      var passed = actual == 5;
      var message = passed
                    ? $"Expected {actual} not to be 5"
                    : $"Expected {actual} to be 5";
      return new MatcherResult(passed, message);
    });
  }
}
```

```csharp
// somewhere else...
[Test]
public void FifteenDividedByThree_ShouldEqual_Five()
{
  var result = 15 / 3;
  Expect(result).To.Be.Five();
}
// Yes, yes, simple example is simple.
```

If you've ever written a Jasmine matcher, this should feel familiar.

If you have a bunch of existing expectations that you'd like to wrap
up into a nicely-named matcher, `.Compose` has you covered:

```csharp
// before
var cow = animalFactory.MakeCow();
var beetle = animalFactory.MakeBeetle();

// animal factory should make a Jersey cow
Expect(cow.Classification).To.Equal("Mammal");
Expect(cow.Legs).To.Equal(4);
Expect(cow.HasTail).To.Be.True();
Expect(cow.HasHorns).To.Be.True();
Expect(cow.HasSpots).To.Be.True();

// Animal factory should make a rhinoceros beetle
Expect(beetle.Classification).To.Equal("Insect");
Expect(beetle.Legs).To.Equal(6);
Expect(beetle.HasTail).To.Be.False();
Expect(beetle.HasHorns).To.Be.True();
Expect(beetle.HasSpots).To.Be.False();
```

```csharp
// after
var cow = animalFactory.MakeJerseyCow();
var beetle = animalFactory.MakeRhinocerosBeetle();

Expect(cow).To.Be.A.JerseyCow();
Expect(beetle).To.Be.A.RhinocerosBeetle();

// elsewhere:

public static class AnimalMatchers
{
  // the IMore<T> interface allows fluent chaining of expectations
  //  eg:
  //  Expect(cow).To.Be.A.JerseyCow()
  //     .And
  //     .Not.To.Be.A.FrieslandCow();
  public static IMore<Animal> JerseyCow(this IA<Animal> a)
  {
    return a.Compose(actual =>
    {
      Expect(cow.Classification).To.Equal("Mammal");
      Expect(cow.Legs).To.Equal(4);
      Expect(cow.HasTail).To.Be.True();
      Expect(cow.HasHorns).To.Be.True();
      Expect(cow.HasSpots).To.Be.True();
    });
  }
  public static IMore<Animal> RhinocerosBeetle(this IA<Animal> a)
  {
    return a.Compose(actual =>
    {
      Expect(beetle.Classification).To.Equal("Insect");
      Expect(beetle.Legs).To.Equal(6);
      Expect(beetle.HasTail).To.Be.False();
      Expect(beetle.HasHorns).To.Be.True();
      Expect(beetle.HasSpots).To.Be.False();
    });
  }
}
```

When one of the inner expectations fails, NExpect attempts to construct
a nice failure message. As with all expectations, you can always make
failures easier to understand with a custom message string or generator:

```csharp
using NExpect.Implementations;
using NExpect.MatcherLogic;
using NExpect;
using static NExpect.Expectations;

public static class AnimalMatchers
{
  public static IMore<Animal> JerseyCow(this IA<Animal> a)
  {
    return a.Compose(actual =>
    {
      // the Stringify extension method, available on all types,
      // comes from NExpect.Implementation.MessageHelpers and
      // produces a string representation of the object it's
      // operating on which is similar to JSON, so it's easier
      // to read what the object was
      var customMessage = $"Expected {actual.Stringify()} to be a cow";
      Expect(cow.Classification).To.Equal("Mammal", customMessage);
      Expect(cow.Legs).To.Equal(4, customMessage);
      Expect(cow.HasTail).To.Be.True(customMessage);
      Expect(cow.HasHorns).To.Be.True(customMessage);
      Expect(cow.HasSpots).To.Be.True(customMessage);
    });
  }
  public static IMore<Animal> RhinocerosBeetle(this IA<Animal> a)
  {
    return a.Compose(actual =>
    {
      // we can use a generator func to delay generation of the message
      //  which is especially helpful if message generation is expensive
      //  and we'd only like to spend that cpu time on a failure
      Func<string> customMessageGenerator = () => $"Expected {actual.Stringify()} to be a cow";
      Expect(beetle.Classification).To.Equal("Insect", customMessageGenerator);
      Expect(beetle.Legs).To.Equal(6, customMessageGenerator);
      Expect(beetle.HasTail).To.Be.False(customMessageGenerator);
      Expect(beetle.HasHorns).To.Be.True(customMessageGenerator);
      Expect(beetle.HasSpots).To.Be.False(customMessageGenerator);
    });
  }
}
```


text:
'use strict';

var should = require('should'),
  request = require('supertest'),
  path = require('path'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  Expense = mongoose.model('Expense'),
  express = require(path.resolve('./config/lib/express'));

/**
 * Globals
 */
var app,
  agent,
  credentials,
  user,
  expense;

/**
 * Expense routes tests
 */
describe('Expense CRUD tests', function () {

  before(function (done) {
    // Get application
    app = express.init(mongoose);
    agent = request.agent(app);

    done();
  });

  beforeEach(function (done) {
    // Create user credentials
    credentials = {
      username: 'username',
      password: 'M3@n.jsI$Aw3$0m3'
    };

    // Create a new user
    user = new User({
      firstName: 'Full',
      lastName: 'Name',
      displayName: 'Full Name',
      email: 'test@test.com',
      username: credentials.username,
      password: credentials.password,
      provider: 'local'
    });

    // Save a user to the test db and create new Expense
    user.save(function () {
      expense = {
        name: 'Expense name'
      };

      done();
    });
  });

  it('should be able to save a Expense if logged in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Expense
        agent.post('/api/expenses')
          .send(expense)
          .expect(200)
          .end(function (expenseSaveErr, expenseSaveRes) {
            // Handle Expense save error
            if (expenseSaveErr) {
              return done(expenseSaveErr);
            }

            // Get a list of Expenses
            agent.get('/api/expenses')
              .end(function (expensesGetErr, expensesGetRes) {
                // Handle Expenses save error
                if (expensesGetErr) {
                  return done(expensesGetErr);
                }

                // Get Expenses list
                var expenses = expensesGetRes.body;

                // Set assertions
                (expenses[0].user._id).should.equal(userId);
                (expenses[0].name).should.match('Expense name');

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should not be able to save an Expense if not logged in', function (done) {
    agent.post('/api/expenses')
      .send(expense)
      .expect(403)
      .end(function (expenseSaveErr, expenseSaveRes) {
        // Call the assertion callback
        done(expenseSaveErr);
      });
  });

  it('should not be able to save an Expense if no name is provided', function (done) {
    // Invalidate name field
    expense.name = '';

    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Expense
        agent.post('/api/expenses')
          .send(expense)
          .expect(400)
          .end(function (expenseSaveErr, expenseSaveRes) {
            // Set message assertion
            (expenseSaveRes.body.message).should.match('Please fill Expense name');

            // Handle Expense save error
            done(expenseSaveErr);
          });
      });
  });

  it('should be able to update an Expense if signed in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Expense
        agent.post('/api/expenses')
          .send(expense)
          .expect(200)
          .end(function (expenseSaveErr, expenseSaveRes) {
            // Handle Expense save error
            if (expenseSaveErr) {
              return done(expenseSaveErr);
            }

            // Update Expense name
            expense.name = 'WHY YOU GOTTA BE SO MEAN?';

            // Update an existing Expense
            agent.put('/api/expenses/' + expenseSaveRes.body._id)
              .send(expense)
              .expect(200)
              .end(function (expenseUpdateErr, expenseUpdateRes) {
                // Handle Expense update error
                if (expenseUpdateErr) {
                  return done(expenseUpdateErr);
                }

                // Set assertions
                (expenseUpdateRes.body._id).should.equal(expenseSaveRes.body._id);
                (expenseUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should be able to get a list of Expenses if not signed in', function (done) {
    // Create new Expense model instance
    var expenseObj = new Expense(expense);

    // Save the expense
    expenseObj.save(function () {
      // Request Expenses
      request(app).get('/api/expenses')
        .end(function (req, res) {
          // Set assertion
          res.body.should.be.instanceof(Array).and.have.lengthOf(1);

          // Call the assertion callback
          done();
        });

    });
  });

  it('should be able to get a single Expense if not signed in', function (done) {
    // Create new Expense model instance
    var expenseObj = new Expense(expense);

    // Save the Expense
    expenseObj.save(function () {
      request(app).get('/api/expenses/' + expenseObj._id)
        .end(function (req, res) {
          // Set assertion
          res.body.should.be.instanceof(Object).and.have.property('name', expense.name);

          // Call the assertion callback
          done();
        });
    });
  });

  it('should return proper error for single Expense with an invalid Id, if not signed in', function (done) {
    // test is not a valid mongoose Id
    request(app).get('/api/expenses/test')
      .end(function (req, res) {
        // Set assertion
        res.body.should.be.instanceof(Object).and.have.property('message', 'Expense is invalid');

        // Call the assertion callback
        done();
      });
  });

  it('should return proper error for single Expense which doesnt exist, if not signed in', function (done) {
    // This is a valid mongoose Id but a non-existent Expense
    request(app).get('/api/expenses/559e9cd815f80b4c256a8f41')
      .end(function (req, res) {
        // Set assertion
        res.body.should.be.instanceof(Object).and.have.property('message', 'No Expense with that identifier has been found');

        // Call the assertion callback
        done();
      });
  });

  it('should be able to delete an Expense if signed in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Expense
        agent.post('/api/expenses')
          .send(expense)
          .expect(200)
          .end(function (expenseSaveErr, expenseSaveRes) {
            // Handle Expense save error
            if (expenseSaveErr) {
              return done(expenseSaveErr);
            }

            // Delete an existing Expense
            agent.delete('/api/expenses/' + expenseSaveRes.body._id)
              .send(expense)
              .expect(200)
              .end(function (expenseDeleteErr, expenseDeleteRes) {
                // Handle expense error error
                if (expenseDeleteErr) {
                  return done(expenseDeleteErr);
                }

                // Set assertions
                (expenseDeleteRes.body._id).should.equal(expenseSaveRes.body._id);

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should not be able to delete an Expense if not signed in', function (done) {
    // Set Expense user
    expense.user = user;

    // Create new Expense model instance
    var expenseObj = new Expense(expense);

    // Save the Expense
    expenseObj.save(function () {
      // Try deleting Expense
      request(app).delete('/api/expenses/' + expenseObj._id)
        .expect(403)
        .end(function (expenseDeleteErr, expenseDeleteRes) {
          // Set message assertion
          (expenseDeleteRes.body.message).should.match('User is not authorized');

          // Handle Expense error error
          done(expenseDeleteErr);
        });

    });
  });

  it('should be able to get a single Expense that has an orphaned user reference', function (done) {
    // Create orphan user creds
    var _creds = {
      username: 'orphan',
      password: 'M3@n.jsI$Aw3$0m3'
    };

    // Create orphan user
    var _orphan = new User({
      firstName: 'Full',
      lastName: 'Name',
      displayName: 'Full Name',
      email: 'orphan@test.com',
      username: _creds.username,
      password: _creds.password,
      provider: 'local'
    });

    _orphan.save(function (err, orphan) {
      // Handle save error
      if (err) {
        return done(err);
      }

      agent.post('/api/auth/signin')
        .send(_creds)
        .expect(200)
        .end(function (signinErr, signinRes) {
          // Handle signin error
          if (signinErr) {
            return done(signinErr);
          }

          // Get the userId
          var orphanId = orphan._id;

          // Save a new Expense
          agent.post('/api/expenses')
            .send(expense)
            .expect(200)
            .end(function (expenseSaveErr, expenseSaveRes) {
              // Handle Expense save error
              if (expenseSaveErr) {
                return done(expenseSaveErr);
              }

              // Set assertions on new Expense
              (expenseSaveRes.body.name).should.equal(expense.name);
              should.exist(expenseSaveRes.body.user);
              should.equal(expenseSaveRes.body.user._id, orphanId);

              // force the Expense to have an orphaned user reference
              orphan.remove(function () {
                // now signin with valid user
                agent.post('/api/auth/signin')
                  .send(credentials)
                  .expect(200)
                  .end(function (err, res) {
                    // Handle signin error
                    if (err) {
                      return done(err);
                    }

                    // Get the Expense
                    agent.get('/api/expenses/' + expenseSaveRes.body._id)
                      .expect(200)
                      .end(function (expenseInfoErr, expenseInfoRes) {
                        // Handle Expense error
                        if (expenseInfoErr) {
                          return done(expenseInfoErr);
                        }

                        // Set assertions
                        (expenseInfoRes.body._id).should.equal(expenseSaveRes.body._id);
                        (expenseInfoRes.body.name).should.equal(expense.name);
                        should.equal(expenseInfoRes.body.user, undefined);

                        // Call the assertion callback
                        done();
                      });
                  });
              });
            });
        });
    });
  });

  afterEach(function (done) {
    User.remove().exec(function () {
      Expense.remove().exec(done);
    });
  });
});


text:
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdip...@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)

Attention: Requires Chrome or Safari. For IE of Firefox you need https://github.com/gimite/web-socket-js

1) install tornado (requires Tornado 3.0 or later)

   easy_install tornado

2) start this app:

   python gluon/contrib/websocket_messaging.py -k mykey -p 8888

3) from any web2py app you can post messages with

   from gluon.contrib.websocket_messaging import websocket_send
   websocket_send('http://127.0.0.1:8888', 'Hello World', 'mykey', 'mygroup')

4) from any template you can receive them with

   <script>
   $(document).ready(function(){
      if(!$.web2py.web2py_websocket('ws://127.0.0.1:8888/realtime/mygroup', function(e){alert(e.data)}))

         alert("html5 websocket not supported by your browser, try Google Chrome");
   });
   </script>

When the server posts a message, all clients connected to the page will popup an alert message
Or if you want to send json messages and store evaluated json in a var called data:

   <script>
   $(document).ready(function(){
      var data;
      $.web2py.web2py_websocket('ws://127.0.0.1:8888/realtime/mygroup', function(e){data=eval('('+e.data+')')});
   });
   </script>

- All communications between web2py and websocket_messaging will be digitally signed with hmac.
- All validation is handled on the web2py side and there is no need to modify websocket_messaging.py
- Multiple web2py instances can talk with one or more websocket_messaging servers.
- "ws://127.0.0.1:8888/realtime/" must be contain the IP of the websocket_messaging server.
- Via group='mygroup' name you can support multiple groups of clients (think of many chat-rooms)

Here is a complete sample web2py action:

    def index():
        form=LOAD('default', 'ajax_form', ajax=True)
        script=SCRIPT('''
            jQuery(document).ready(function(){
              var callback=function(e){alert(e.data)};
              if(!$.web2py.web2py_websocket('ws://127.0.0.1:8888/realtime/mygroup', callback))

                alert("html5 websocket not supported by your browser, try Google Chrome");
            });
        ''')
        return dict(form=form, script=script)

    def ajax_form():
        form=SQLFORM.factory(Field('message'))
        if form.accepts(request,session):
            from gluon.contrib.websocket_messaging import websocket_send
            websocket_send(
                'http://127.0.0.1:8888', form.vars.message, 'mykey', 'mygroup')
        return form

https is possible too using 'https://127.0.0.1:8888' instead of 'http://127.0.0.1:8888', but need to
be started with

   python gluon/contrib/websocket_messaging.py -k mykey -p 8888 -s keyfile.pem -c certfile.pem

for secure websocket do:

   web2py_websocket('wss://127.0.0.1:8888/realtime/mygroup',callback)

Acknowledgements:
Tornado code inspired by http://thomas.pelletier.im/2010/08/websocket-tornado-redis/

"""

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import hmac
import sys
import optparse
import urllib
import time

listeners, names, tokens = {}, {}, {}

def websocket_send(url, message, hmac_key=None, group='default'):
    sig = hmac_key and hmac.new(hmac_key, message).hexdigest() or ''
    params = urllib.urlencode(
        {'message': message, 'signature': sig, 'group': group})
    f = urllib.urlopen(url, params)
    data = f.read()
    f.close()
    return data

class PostHandler(tornado.web.RequestHandler):
    """
    only authorized parties can post messages
    """
    def post(self):
        if hmac_key and not 'signature' in self.request.arguments:
            self.send_error(401)
        if 'message' in self.request.arguments:
            message = self.request.arguments['message'][0]
            group = self.request.arguments.get('group', ['default'])[0]
            print '%s:MESSAGE to %s:%s' % (time.time(), group, message)
            if hmac_key:
                signature = self.request.arguments['signature'][0]
                if not hmac.new(hmac_key, message).hexdigest() == signature:
                    self.send_error(401)
            for client in listeners.get(group, []):
                client.write_message(message)

class TokenHandler(tornado.web.RequestHandler):
    """
    if running with -t post a token to allow a client to join using the token
    the message here is the token (any uuid)
    allows only authorized parties to joins, for example, a chat
    """
    def post(self):
        if hmac_key and not 'message' in self.request.arguments:
            self.send_error(401)
        if 'message' in self.request.arguments:
            message = self.request.arguments['message'][0]
            if hmac_key:
                signature = self.request.arguments['signature'][0]
                if not hmac.new(hmac_key, message).hexdigest() == signature:
                    self.send_error(401)
            tokens[message] = None

class DistributeHandler(tornado.websocket.WebSocketHandler):

    def check_origin(self, origin):
        return True

    def open(self, params):
        group, token, name = params.split('/') + [None, None]
        self.group = group or 'default'
        self.token = token or 'none'
        self.name = name or 'anonymous'
        # only authorized parties can join
        if DistributeHandler.tokens:
            if not self.token in tokens or not token[self.token] is None:
                self.close()
            else:
                tokens[self.token] = self
        if not self.group in listeners:
            listeners[self.group] = []
        # notify clients that a member has joined the groups
        for client in listeners.get(self.group, []):
            client.write_message('+' + self.name)
        listeners[self.group].append(self)
        names[self] = self.name
        print '%s:CONNECT to %s' % (time.time(), self.group)

    def on_message(self, message):
        pass

    def on_close(self):
        if self.group in listeners:
            listeners[self.group].remove(self)
        del names[self]
        # notify clients that a member has left the groups
        for client in listeners.get(self.group, []):
            client.write_message('-' + self.name)
        print '%s:DISCONNECT from %s' % (time.time(), self.group)

# if your webserver is different from tornado server uncomment this
# or override using something more restrictive:
# http://tornado.readthedocs.org/en/latest/websocket.html#tornado.websocket.WebSocketHandler.check_origin
# def check_origin(self, origin):
#    return True

if __name__ == "__main__":
    usage = __doc__
    version = ""
    parser = optparse.OptionParser(usage, None, optparse.Option, version)
    parser.add_option('-p',
                      '--port',
                      default='8888',
                      dest='port',
                      help='socket')
    parser.add_option('-l',
                      '--listen',
                      default='0.0.0.0',
                      dest='address',
                      help='listener address')
    parser.add_option('-k',
                      '--hmac_key',
                      default='',
                      dest='hmac_key',
                      help='hmac_key')
    parser.add_option('-t',
                      '--tokens',
                      action='store_true',
                      default=False,
                      dest='tokens',
                      help='require tockens to join')
    parser.add_option('-s',
                      '--sslkey',
                      default=False,
                      dest='keyfile',
                      help='require ssl keyfile full path')
    parser.add_option('-c',
                      '--sslcert',
                      default=False,
                      dest='certfile',
                      help='require ssl certfile full path')
    (options, args) = parser.parse_args()
    hmac_key = options.hmac_key
    DistributeHandler.tokens = options.tokens
    urls = [
        (r'/', PostHandler),
        (r'/token', TokenHandler),
        (r'/realtime/(.*)', DistributeHandler)]
    application = tornado.web.Application(urls, auto_reload=True)
    if options.keyfile and options.certfile:
        ssl_options = dict(certfile=options.certfile, keyfile=options.keyfile)
    else:
        ssl_options = None
    http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options)
    http_server.listen(int(options.port), address=options.address)
    tornado.ioloop.IOLoop.instance().start()


text:
package net.makito.himitsu;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;

public class ZXingExist {

    public static void Install(Context ctx) {
        Intent intentInstall = new Intent();
        String apkPath = "/data/data/" + ctx.getPackageName() + "/files";
        String apkName = "com.srowen.bs.android_25.apk";
        File file = new File(apkPath, apkName);
        try {
  InputStream is = ctx.getAssets().open("com.srowen.bs.android_25.apk");

            if (!file.exists()) {
                file.createNewFile();
                FileOutputStream os = ctx.openFileOutput(file.getName(),
                        Context.MODE_WORLD_WRITEABLE);
                byte[] bytes = new byte[512];
                int i = -1;
                while ((i = is.read(bytes)) > 0) {
                    os.write(bytes);
                }

                os.close();
                is.close();
                Log.e("", "----------- has been copy to ");
            } else {
                Log.e("", "-----------cunzai ");
            }
            String permission = "666";

            try {
                String command = "chmod " + permission + " " + apkPath + "/"
                        + apkName;
                Runtime runtime = Runtime.getRuntime();
                runtime.exec(command);
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            Log.e("", e.toString());
        }
        Log.e("", "fl--" + file.getName() + "-dd---" + file.getAbsolutePath()
                + "-pa-" + file.getPath());
        intentInstall.setAction(android.content.Intent.ACTION_VIEW);
        intentInstall.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        intentInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        ctx.startActivity(intentInstall);
    }

    public static boolean isAvilible(Context context, String packageName){
        final PackageManager packageManager = context.getPackageManager();//获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);//获取所有已安装程序的包信息
        List<String> pName = new ArrayList<String>();//用于存储所有已安装程序的包名
       //从pinfo中将包名字逐一取出,压入pName list中
            if(pinfo != null){
            for(int i = 0; i < pinfo.size(); i++){
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);//判断pName中是否有目标程序的包名,有TRUE,没有FALSE
  }
}


text:
package com.pfkj.oas.service;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import com.pfkj.oas.manager.SkManager;
import com.pfkj.oas.model.HeTongVo;
import com.pfkj.oas.model.SktzdVo;
import com.pfkj.oas.model.SrHeTongVo;

public class SkService {
	SkManager manager;

	public SkManager getManager() {
		return manager;
	}

	public void setManager(SkManager manager) {
		this.manager = manager;
	}

	public boolean saveHt(HeTongVo htVo) {
		// TODO 自动生成的方法存根
		return false;
	}

	public boolean saveSrht(SrHeTongVo htVo) {
		return manager.saveSrht(htVo);
	}

	public boolean saveSktzd(SktzdVo sktzd) {
		return manager.saveSktzd(sktzd);
	}

	public String searchSktzd(String str) throws JDOMException, IOException{

		StringBuffer result = new StringBuffer();
        /** *创建一个新的字符串*** */
        StringReader xmlReader = new StringReader(str);
        /** **创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入 */
        InputSource xmlSource = new InputSource(xmlReader);
        /** *创建一个SAXBuilder* */
        SAXBuilder builder = new SAXBuilder();
        /** *通过输入源SAX构造一个Document** */
        org.jdom.Document doc = builder.build(xmlSource);
        /** *获得根节点** */
        org.jdom.Element elt = doc.getRootElement();
        /** *获得节点** */
        String htbh = elt.getChild("HTBH").getText();
        String yzmc = elt.getChild("YZMC").getText();
        String sj = elt.getChild("SJ").getText().replace("-", "");
        String gclb = elt.getChild("GCLB").getText();
        List<SktzdVo> list = manager.searchSktzd(htbh,yzmc,sj,gclb);

        for (int i = 0;i<list.size();i++) {
        	SktzdVo sktzdVo = (SktzdVo)list.get(i);
        	result.append("
");
        	result.append(i+1);
        	result.append("	");
        	result.append(sktzdVo.getJlqs());
        	result.append("	");
        	result.append(sktzdVo.getJlrq());
        	result.append("	");
        	result.append(sktzdVo.getJlk());
        	result.append("	");
        	result.append(sktzdVo.getZbj());
        	result.append("	");
        	result.append(sktzdVo.getNmggzbzj());
        	result.append("	");
        	result.append(sktzdVo.getQtkk());
        	result.append("
");
		}
        return result.toString();
	}
}


text:
c = get_config()

# Add users here that are allowed admin access to JupyterHub.
c.Authenticator.admin_users = ["jhamrick"]

# Add users here that are allowed to login to JupyterHub.
c.Authenticator.whitelist = ["jhamrick"]


text:
Filesystem_DB
=============

Written by Oskari Rauta.
License: expat ( check copying.txt )

Filesystem DB Library for Arduino/Maple/etc..

This is a library for easy access/manipulation of 2 linked list style databases,
one for filesystem's folders and one for files.

I am/was (future reference) working with a project, that has a "server" system running
on a raspberry pi, and a "client" system running on Arduino (Due) - this client system
is connected "server" with rs485 and is equipped with a SD card. Server can update files
and folders on that SD card over the rs485. Now I needed a system that could check if
and file on SD card is outdated. So I decided that server should send a md5sum of file
when it sends it. This way we can have a database. I store this database on that sd card
also as a file not belonging to this database. Server can now retrieve folder and file
databases from client to see if required file or folder is missing or file on server has
been updated.

I made it to store entries in the database in alphabetical order, so list would be easier
to read and compare.

This doesn't use malloc and free. This uses new and delete - so it's maple safe.
Haven't tested it on maple, but should work, although the example propably needs a bit
tweaking.. It also needs a change from Serial to Serial1 if you use it on Arduino Uno/Mega/etc - other than Due..

Usage documentation is on Filesystem_DB.h and there is a example in examples folder.
Remember to read mentioned warnings in Filesystem_DB.h


text:
package com.amazonaws.services.cloudformation.model;

/**
 *

 * The output for a DescribeStackResources action.
 *

 */
public class DescribeStackResourcesResult {

    /**
     * A list of StackResource structures.
     */
    private java.util.List<StackResource> stackResources;

    /**
     * A list of StackResource structures.
     *
     * @return A list of StackResource structures.
     */
    public java.util.List<StackResource> getStackResources() {

        if (stackResources == null) {
            stackResources = new java.util.ArrayList<StackResource>();
        }
        return stackResources;
    }

    /**
     * A list of StackResource structures.
     *
     * @param stackResources A list of StackResource structures.
     */
    public void setStackResources(java.util.Collection<StackResource> stackResources) {
        if (stackResources == null) {
            this.stackResources = null;
            return;
        }

        java.util.List<StackResource> stackResourcesCopy = new java.util.ArrayList<StackResource>(stackResources.size());
        stackResourcesCopy.addAll(stackResources);
        this.stackResources = stackResourcesCopy;
    }

    /**
     * A list of StackResource structures.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param stackResources A list of StackResource structures.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public DescribeStackResourcesResult withStackResources(StackResource... stackResources) {
        if (getStackResources() == null) setStackResources(new java.util.ArrayList<StackResource>(stackResources.length));
        for (StackResource value : stackResources) {
            getStackResources().add(value);
        }
        return this;
    }

    /**
     * A list of StackResource structures.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param stackResources A list of StackResource structures.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public DescribeStackResourcesResult withStackResources(java.util.Collection<StackResource> stackResources) {
        if (stackResources == null) {
            this.stackResources = null;
        } else {
            java.util.List<StackResource> stackResourcesCopy = new java.util.ArrayList<StackResource>(stackResources.size());
            stackResourcesCopy.addAll(stackResources);
            this.stackResources = stackResourcesCopy;
        }

        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (stackResources != null) sb.append("StackResources: " + stackResources + ", ");
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getStackResources() == null) ? 0 : getStackResources().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof DescribeStackResourcesResult == false) return false;
        DescribeStackResourcesResult other = (DescribeStackResourcesResult)obj;

        if (other.getStackResources() == null ^ this.getStackResources() == null) return false;
        if (other.getStackResources() != null && other.getStackResources().equals(this.getStackResources()) == false) return false;
        return true;
    }

}


text:
package fi.nls.oskari.control.view;

import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.control.ontology.SearchKeywordsHandler;
import fi.nls.oskari.ontology.domain.Keyword;
import fi.nls.oskari.ontology.service.KeywordService;
import fi.nls.oskari.ontology.service.KeywordServiceMybatisImpl;
import fi.nls.oskari.util.DuplicateException;
import fi.nls.oskari.util.PropertyUtil;
import fi.nls.test.control.JSONActionRouteTest;
import fi.nls.test.util.ResourceHelper;
import fi.nls.test.util.TestHelper;
import org.junit.*;

import java.util.*;

import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;

/**
 * @author TMIKKOLAINEN
 */
public class SearchKeywordsHandlerTest extends JSONActionRouteTest {

    final private SearchKeywordsHandler handler = new SearchKeywordsHandler();

    private KeywordService keywordService = null;

    @BeforeClass
    public static void addLocales() throws Exception {
        Properties properties = new Properties();
        try {
            properties.load(SearchKeywordsHandlerTest.class.getResourceAsStream("test.properties"));
            PropertyUtil.addProperties(properties);
            String locales = PropertyUtil.getNecessary("oskari.locales");
            if (locales == null)
                fail("No darned locales");
        } catch (DuplicateException e) {
            fail("Should not throw exception" + e.getStackTrace());
        }

        assumeTrue(TestHelper.dbAvailable());
    }

    @Before
    public void setUp() throws Exception {
        keywordService = mock(KeywordServiceMybatisImpl.class);

        handler.setService(keywordService);
        handler.init();
    }

    @AfterClass
    public static void teardown() {
        PropertyUtil.clearProperties();
    }

    private static Keyword createKeyword(Long id, String value, Long... layers) {
        Keyword keyword = new Keyword();
        keyword.setId(id);
        keyword.setValue(value);
        List<Long> layerIds = new ArrayList<Long>();
        for(Long layer : layers) {
            layerIds.add(layer);
        }
        keyword.setLayerIds(layerIds);
        return keyword;
    }

    private static List<Map<String, Object>> getPermissionsList(Long... layerIDs) {
        List<Map<String, Object>> permissions = new ArrayList<Map<String, Object>>();
        for (Long layerID : layerIDs) {
            Map<String, Object> permission = new HashMap<String, Object>();
            permission.put("id", layerID);
            permissions.add(permission);
        }
        return permissions;
    }

    @Test
    public void testEmptyResponse() throws Exception {
        // Empty result should still give us a fake exact hit
        doReturn(null).when(keywordService).findExactKeyword(anyString(), anyString());
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("keyword", "nothing");
        parameters.put("lang", "fi");
        final ActionParameters actionParameters = createActionParams(parameters);
        verifyResponseNotWritten(actionParameters);
        handler.handleAction(actionParameters);
        verifyResponseWritten(actionParameters);
        verifyResponseContent(ResourceHelper.readJSONArrayResource("SearchKeywordsHandlerTest-empty-result.json", this));
    }

    @Test
    public void testNonPermittedLayerResponse() throws Exception {
        // test a response that doesn't have a layer because the user doesn't have permissions for it.
        // mock response from services
        doReturn(createKeyword(1l, "test", 1l, 2l)).when(keywordService).findExactKeyword(anyString(), anyString());
        // do unmocked calls simply return a new<Whatever>?
        // check that the response doesn't have layers
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("keyword", "test");
        parameters.put("lang", "fi");
        final ActionParameters actionParameters = createActionParams(parameters);
        verifyResponseNotWritten(actionParameters);
        handler.handleAction(actionParameters);
        verifyResponseWritten(actionParameters);
        verifyResponseContent(ResourceHelper.readJSONArrayResource("SearchKeywordsHandlerTest-one-layer.json", this));
    }

    @Test
    public void testFullResponse() throws Exception {
        // test a response that carries all possible response/relation types.
        // shows that we get all the relation types and that they are in the right order

        // exact match kw with no layers
        doReturn(createKeyword(1l, "test")).when(keywordService).findExactKeyword(anyString(), anyString());
        // synonym with no layers
        List<Keyword> synonyms = new ArrayList<Keyword>();
        synonyms.add(createKeyword(2l, "trial"));
        doReturn(synonyms).when(keywordService).findSynonyms(anyLong(), anyString());
        // near match with no layers
        List<Keyword> nearMatches = new ArrayList<Keyword>();
        nearMatches.add(createKeyword(3l, "testarossa"));
        doReturn(nearMatches).when(keywordService).findKeywordsMatching(anyString(), anyString());
        // parent with a layer
        List<Keyword> parents = new ArrayList<Keyword>();
        parents.add(createKeyword(4l, "parent", 1l));
        doReturn(parents).when(keywordService).findParents(anyLong(), anyString());
        // sibling with a not-permitted layer
        List<Keyword> siblings = new ArrayList<Keyword>();
        siblings.add(createKeyword(5l, "sibling", 2l));
        doReturn(siblings).when(keywordService).findSiblings(anyLong(), anyString());

        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("keyword", "test");
        parameters.put("lang", "fi");
        final ActionParameters actionParameters = createActionParams(parameters);
        verifyResponseNotWritten(actionParameters);
        handler.handleAction(actionParameters);
        verifyResponseWritten(actionParameters);
        verifyResponseContent(ResourceHelper.readJSONArrayResource("SearchKeywordsHandlerTest-all-relation-types.json", this));

    }

    @Test
    public void testNonPermittedLayerDoesNotBlockParentInclusion() throws Exception {
        doReturn(createKeyword(1l, "test", 1l)).when(keywordService).findExactKeyword(anyString(), anyString());
        List<Keyword> parents = new ArrayList<Keyword>();
        parents.add(createKeyword(4l, "parent", 2l));
        doReturn(parents).when(keywordService).findParents(anyLong(), anyString());

        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("keyword", "test");
        parameters.put("lang", "fi");
        final ActionParameters actionParameters = createActionParams(parameters);
        verifyResponseNotWritten(actionParameters);
        handler.handleAction(actionParameters);
        verifyResponseWritten(actionParameters);
        verifyResponseContent(ResourceHelper.readJSONArrayResource("SearchKeywordsHandlerTest-non-permitted-layer-on-exact-match.json", this));
    }

    @After
    public void delete() {
        PropertyUtil.clearProperties();
    }
}


text:
Gitlab Cookbook Changelog
=========================

v8.0.1
------

* Merge all pull requests in the queue
* Upgrade to gitlab 8-0-stable branch (update configuration, new gitlab-git-http-server, security.yml)
* In Fix 8.0.1 - Update gitlab.init.erb

v7.7.1
------

* Closes #90, incorrect instance variable in template.

v7.7.0
------

* Credit to @jeremyolliver for doing most of the work for an 7.x release.
  - gitlab branch targets 7-7-stable.
  - gitlab shell branch targets 2.4.1.
  - Ruby version is 2.1.2.
* mysql cookbook 6.0 related changes.
  - This is a potentially breaking change.  The gitlab::mysql recipe now sets up
    a mysql server since the mysql::server recipe no longer exists in the 6.0
    version of the mysql cookbook.
  - A future release of this cookbook may separate the duties of the mysql server, and
    the mysql database initialization for gitlab.
  - NOTE the database initialization for postgres remains unchanged, and backwards
    compatible with prior releases.

v6.9.0
------

* Fix Rubocop warnings
* Issue #76
  * Bump version to 6.9
  * depsolv problem with modernizr
*  Issue #74
  * Use database::mysql and database::postgresql for database cookbook
    library functionality as mysql::ruby postgres::ruby deprecrated.

v6.4.5 - v6.4.6
---------------

* Add regression tests for #66 hackery
* Issue #66, #71 regression, update-alternatives hack does not work when install_ruby_path
  is changed.

v6.4.4
------

* Issue #62, certificate resource does not exist if nil, and used as name attribute.

v6.4.3
------

* Issue #66, gitlab service needs a priority > 20, on debian platform.
* Issue #66, update-alternatives hack so gitlab-shell can find Ruby.
* Issue #69, Correct gitlab_url in gitlab-shell config.yml, add regression tests.
* Issue #67, soften cookbook dependencies on unknown platforms.
* Issue #62, Add new user attributes to gitlab.yml, and update documentation.

v6.4.2
------

* Add a profile script shim, so init script can correct Ruby.

v6.4.1
------

* Issue #60 - thanks to @nickryand
  - Modified the bundle install command to drop a file on successful
    completion
  - Added the absolute path to the bundler binary installed into the
    system ruby path.
  - Added a more accurate pattern matcher to gitlab service resource
    so Chef can find unicorn_rails processes instead of finding processes that
    have the 'gitlab' string in them.
  - Changed the background call to script/web and script/background_jobs
    in the startup script.  These are now foreground calls forcing the start
    script to block until they return (after the processes are up).  This
    prevents the Chef run from completing before the unicorn_rails processes
    are up.

* Other fixes/tweaks
  - Remove yum dependency hell.
  - Change init/database.yml order due to service subscription.
  - Add a :80 redirect to :443, avoids default site showing on :80
    when `gitlab['https']` set.

* Update test files
  - Pin omnibus version at 11.8.2, redisio remote file resource failure.
  - Remove explicit nil on databag_certificate_id, fails on default suite
  - Remove support Gemfile, and update travis.yml
  - Add bats tests for default/https suites

v6.4.0
------

  * Bump gitlab-shell to v1.8.0
  * Bump gitlab to 6.4.0
  * Remove stale nginx config file
  * Default recipe changes
    - Update gitlab-shell config to point at /usr/local/bin/redis-cli
    - Fix permissions on .ssh/authorized_keys
    - Add rack_attack file
    - Add precompile assets execute
    - Add logrotate dependency and configuration

v6.1.21
-------

  * Add node['database']['userhost'] attribute, fixes #57
  * Fix gitlab['listen_port']/gitlab['https'] condition, fixes #58
  * Add node['gitlab']['self_signed_cert'] and documentation, fixes #58
  * Revert yum-epel changes, COOK-4164 blocking, will re-open
    - Fix dependency hell w/ nginx cookbook
  * Add rubocop linting
  * Add chefspec mysql/postgres http/https branching specs
  * Remove unneeded python dependency

v6.1.10
-------

Bugs squashed:

  * Re-order database components to fix Ubuntu Test-Kitchen run. #44
  * Update port forwarding configuration in kitchen.yml. #46
  * Update Satellite paths to fix Gitlab forking. #50
  * ruby-build installs to node['gitlab']['home'], avoiding PATH hacks
    for Rake.  Use node['gitlab']['install_ruby_path'] to override. #16
  * ruby-build failing on 1.9.3-p448, bump version to 1.9.3-p484.
  * Pinned yum dependency on < 3.0.0

Features added:

  * Add knob for disabling Gravatar. #51
  * Add LDAP Authentication support. #49

Removed:

  * sudo cookbook dependency removed. #52

v6.1.0
------

Clean up some of the code to target [6-1-stable branch](https://github.com/gitlabhq/gitlabhq/blob/6-1-stable/doc/install/installation.md)

* Move gitlab.home to /srv/git - [FHS 2.3](http://www.pathname.com/fhs/pub/fhs-2.3.html)
* Use ruby_build to compile 1.9.3 by default per gitlabhq documentation.
* Clean up both cookbook and package dependencies.
* Remove ruby-shadow, included in Omnibus, not needed anyway as no
  password is set.
* Use gitconfig template, instead of execute.
* Add test-kitchen skeleton, and certificate data_bag integration.
  - Add gitlab.certificate_databag_id to deploy certificate from encrypted databag.
* Minor sudo fix in gitlab init script.
* Use nginx_site definition to disable default nginx site.
* Add nginx_server_names array for hostname match precedence over potential default sites matching `_`.

v0.5.0
------

* Database back-end changes via @sethvargo
  - Adds a mysql and postgresql database creation
  - **Breaking change**: developed against githlabhq/master (sqlite no longer supported)

* Gitolite deploy changes via @dscheu
  - Deploy gitlabhq/gitolite, not sitaramc/gitolite

* Add configurable backup paths to Gitlab configuration via @dscheu

v0.3.4
------

Fix issues with stable snapshot v3.x

* Avoid installing pg, gem which adds extra dependencies
* Add change to default gitolite.rc per upgrade instructions

v0.3.3
------

Issues #9 and #10

Issue 9: this version MAY fix issues with key generation when
cookbook is invocated via chef-solo.  There may exist other
chef-solo blockers within the cookbook.  Specifically, `File.exists?`
guards were added to SSH public key generation code blocks.

Issue 10: this version fixes one minor dependency bug with EPEL
dependencies via metadata and inclusion.

v0.3.2
------

* Default gitlab branch to stable

v0.3.1
------

* ISSUE 7: public key template fails to render
* ISSUE 8: unicorn_rails script fails on ruby package platforms

v0.3.0
------

* Missing bracket
* Change single-quote variable to symbol notation
* install python and symlink redis-cli so hooks work
* HTTPS options for nginx
* Ubuntu/Debian platform compatibility fixes
* [FC035](http://acrmp.github.com/foodcritic/#FC035): Template uses node attribute directly

v0.2.1
------

  Thanks to Fletcher Nichol for the feedback and fixes :)

  * Add `gitlab_branch` attribute.
  * Fix directory block syntax (do).

v0.2.0
------

  * Epic public release <crowd cheers>
  * Moar testing
  * Clean up init script
  * Fix unicorn config
  * Fix gitlab home permissions for nginx

v0.1.0
------

  #Epic refactor

  * Write long README
  * variable renaming to simplify readability
  * refactor dependencies and package lists
  * generate ssh keys in Ruby, import to gitolite
  * Integrate gitolite recipe into cookbook
  * Fix broken ssh problems
  * fixup git home permissions
  * use system ruby instead of chef-full bundler
  * Re-work dependencies; Prefer ruby_build rubies over Redhat shipped

v0.0.1 - v0.0.40
----------------

  #Prototyping

  Added cookbook dependencies for gitlab/gitolite
  Prototype attributes for gitlab cookbook
  Fixed gitolite support for gitlab in default.rb
  Fixed permissions & gl-setup in gitlab default.rb
  Edit default.rb in gitlab & gitolite cookbooks
  Edit gitolite cmd to add .pub key
  Fix code blocks in wrong order gitolite/gitlab ckbks
  Refactor gitolite/gitlab ckbks again. Works now.
  Add cookbooks redisio & sqlite. Install pkgs for gitlab
  Install Gems. Rename config files 4 gitlab cookbook
  Config Sqlite DB for gitlab
  Add ability to start gitlab & resque


text:
bomjs
=====

JavaScript program anaylzer


text:
<?php

namespace Berlioz\Core\Exception;

class RoutingException extends BerliozException
{
    // Default messages
    const messages = [0   => 'Unknown error',
                      100 => 'Continue',
                      101 => 'Switching Protocols',
                      200 => 'OK',
                      201 => 'Created',
                      202 => 'Accepted',
                      203 => 'Non-Authoritative Information',
                      204 => 'No Content',
                      205 => 'Reset Content',
                      206 => 'Partial Content',
                      300 => 'Multiple Choices',
                      301 => 'Moved Permanently',
                      302 => 'Moved Temporarily',
                      303 => 'See Other',
                      304 => 'Not Modified',
                      305 => 'Use Proxy',
                      400 => 'Bad Request',
                      401 => 'Unauthorized',
                      402 => 'Payment Required',
                      403 => 'Forbidden',
                      404 => 'Not Found',
                      405 => 'Method Not Allowed',
                      406 => 'Not Acceptable',
                      407 => 'Proxy Authentication Required',
                      408 => 'Request Time-out',
                      409 => 'Conflict',
                      410 => 'Gone',
                      411 => 'Length Required',
                      412 => 'Precondition Failed',
                      413 => 'Request Entity Too Large',
                      414 => 'Request-URI Too Large',
                      415 => 'Unsupported Media Type',
                      500 => 'Internal Server Error',
                      501 => 'Not Implemented',
                      502 => 'Bad Gateway',
                      503 => 'Service Unavailable',
                      504 => 'Gateway Time-out',
                      505 => 'HTTP Version not supported'];

    /**
     * RoutingException constructor.
     *
     * @param int             $code
     * @param string          $message
     * @param \Throwable|null $previous
     */
    public function __construct(int $code = 500, $message = '', \Throwable $previous = null)
    {
        // Default message
        if (empty($message)) {
            $message = static::messages[$code] ?: static::messages[0];
        }

        parent::__construct($message, $code, $previous);
    }
}


text:
import React from 'react';
import styled from 'styled-components';

import TitleIcon from '../../images/certificate/bike-festival.png';

function formatDate(date) {
    let formattedDate = date.replace(new RegExp('-', 'g'), '/');
    return formattedDate;
}

function removeNCKU(departmentName) {
    let processedDepartmentName = departmentName;
    if (departmentName.includes('成大')) {
        processedDepartmentName = departmentName.replace('成大', '');
    }
    return processedDepartmentName;
}

const Border = styled.div`
    background-color: #f8b62d;
    border: 8px solid #405d6f;
    padding: 1cm 3.5cm;
`;

const Column = styled.div`
    margin: 0 10px;
`;

const Content = styled.div`
    position: relative;
    left: 15px;
    margin: 50px auto;
    width: 10.5cm;
`;

const Date = styled.span`
    font-family: Helvetica;
`;

const Introduction = styled.div`
    width: 8.35cm;
`;

const Label = styled.div`
    width: 2.15cm;
`;

const LogoWrapper = styled.div`
    display: inline-flex;
    margin: 20px auto;

    img {
        height: 85px;
    }
`;

const Number = styled.span`
    font-family: Helvetica;
    font-size: 28px;
    font-weight: bold;
`;

const NumberWrapper = styled.div`
    margin: 10px 0;
`;

const Row = styled.div`
    margin: 20px auto;
`;
const ContentRow = Row.extend`
    line-height: 1.1rem;
    text-align: left;
    white-space: pre-wrap;
`;
const IntroductionWrapper = ContentRow.extend`
    display: inline-flex;
    margin: 0;
    width: 100%;
`;
const StyledRow = Row.extend`
    border-bottom: 1px solid black;
    font-size: 16px;
    margin: 0;
    padding: 3px 10px;
    text-align: center;
    width: 80px;
`;

const Statistic = styled.div`
    display: inline-flex;
    justify-content: center;
    margin-top: 30px;
    width: 100%;
`;

const Title = styled.div`
    font-size: 28px;
    margin: 20px 0;
`;

const Unit = styled.span`
    font-size: 24px;
`;

const Wrapper = styled.div`
    color: #504639;
    display: flex;
    font-size: 16px;
    font-weight: bold;
    height: 29.7cm;
    justify-content: center;
    overflow: auto;
    text-align: center;
    width: 21cm;
`;

const BikeFestival = ({
    currentLudoData,
    statisticData,
    userName,
}) => (
    <Wrapper>
        <Border>
            <LogoWrapper>
                <img src={TitleIcon} />
            </LogoWrapper>
            <Title>
                國立成功大學系所入門知識行動成果證明
            </Title>
            <Content>
                <ContentRow>
                    姓  名:{userName}
                </ContentRow>
                <ContentRow>
                    系  所:{currentLudoData.tags.length > 0 ? removeNCKU(currentLudoData.tags[0]) : '科系'}
                </ContentRow>
                <ContentRow>
                    執行時間:
                    <Date>
                        {formatDate(currentLudoData.start_day) + ' ~ ' + formatDate(currentLudoData.end_day)}
                    </Date>
                </ContentRow>
                <ContentRow>
                    模板名稱:{currentLudoData.title}
                </ContentRow>
                <IntroductionWrapper>
                    <Label>
                        模板內容:
                    </Label>
                    <Introduction>
                        {currentLudoData.introduction}
                    </Introduction>
                </IntroductionWrapper>
            </Content>
            <Statistic>
                <Column>
                    <StyledRow>
                        達成率
                    </StyledRow>
                    <NumberWrapper>
                        <Number>{Math.round(statisticData.completeRate * 10) / 10}</Number><Unit>%</Unit>
                    </NumberWrapper>
                </Column>
                <Column>
                    <StyledRow>
                        互動積分
                    </StyledRow>
                    <NumberWrapper>
                        <Number>{statisticData.interactScore}</Number>
                    </NumberWrapper>
                </Column>
                <Column>
                    <StyledRow>
                        行為間隔
                    </StyledRow>
                    <NumberWrapper>
                        <Number>{statisticData.actionInterval}</Number><Unit>天</Unit>
                    </NumberWrapper>
                </Column>
                <Column>
                    <StyledRow>
                        互動PR
                    </StyledRow>
                    <NumberWrapper>
                        <Number>{statisticData.interactPR}</Number>
                    </NumberWrapper>
                </Column>
            </Statistic>
        </Border>
    </Wrapper>
);

export default BikeFestival;


text:
layout: post
title: New Zealand 2007
date: 2007-01-31 12:00:00
comments: yes
image:
 feature: https://farm4.staticflickr.com/3931/15423899641_22c229f0c0_k_d.jpg
tags:
- travel
- family
---

Goin' to NZ to celebrate finishing school. As you do.

## Day One

Well after getting up 16 hours ago, it's now time to write what is sure to be the first of one reports into my trip to New Zealand.

We spent last night in a seedy airport motel, wich I highly reccommend not visiting. Anywhoo, we got up at 0500 (And what does the first 0 stand for? OH MY GOD, IT'S EARLY) And we took their complementary shuttle bus to the airport. This would have been delightful if the guy driving it had known his basic geography – that NZ isn't actually a part of Australia, meaning that we needed to go to the international terminal, not the domestic. Still, at least we have them in the same building, unlike Brisbane or Sydney.

The flight was the same as any other, only loooooooonger.

I still wished for a bigger seat and MORE LEGROOM! I finished most of the book Hotel Babylon. This is the basis of the BBC miniseries, and, unlike the miniseries, is actually good. What a shock! Jaimie was kind enough to take time out of his busy schedule of climbing over us to go to sleep. Passport control is a bitch, it really is. I am so glad that we got to go in the special Disabled/Diplomatic Passports/Flight Crew/Small, Annoying Children queue. So we get out into the free-to-roam section of Christchurch Airport. and it's tiny! really! Melbourne and Brisbane, the two major airports that I've been to are very, very much bigger.

Coolangatta [Gold Coast] is tiny little thing that doesn't accept international flights, and I'm pretty sure that it's as large as Christchurch International (Which is the main entry point for the South Island, as well as home to the US' Antarctic Support Facilities (I saw a antarctic-capable C-130, which had me all excited))

So on to the roads we go. It's all very similar to at home, although there are a lot of nagging little things that are different. The speed limit signs are circular, their money seems to be issued in the name of the Reserve Bank of NZ, everyone talks strange, not just accent, but the actual words and phrases they use.

Dad and I got dispatched on a mission to the shops, and took the hotel shuttle into the CBD. They dropped us off at this place called Pak'n'Save. Now from the outside, it looks like something similar to Safeway, mainly because it has its own brand of servo nearby. We walk inside and oh shit. Do you guys remeber the old Franklins supermarkets that went under a few years ago? It's like one of those but MASSSSSIVE. we got our stuff as quickly as possible, but had to make a last-ditch return to the fruit and veg section – a VERY bad idea.

Beaten, but victorious, we made a rearward-facing tactical maneuver. Oh that reminds me, they sell booze there and for some reason I couldn't understand this lady would walk up to different checkouts and swipe her namebadge. Turns out its because the kids working there were actual kids and couldn't sell alcohol all by themselves.

We catch this taxi home before going out for dinner at this place the guys at the front desk (Our Friend James At The Front Desk and the duty manager) recommended. Sasha the Russian Maxicab driver met us and we go to this place called Lone Star,a family restaurant co-located with this country and western bar and also this trendy bar out back. During kids dinner time, they had DVDs of the Thunderbirds going without the sound, and the waitstaff we occasionally found hiding out in the back bar watching as well.

They also had a fair bit of memorabilia, including stuff that was probably photocopied and also stuff that had blatently been stolen from the internet, as it had been blown up just enough that you could see the pixels.

The TV here is strange, there's hardly any american stuff, a bit of NZ stuff, but its mostly exported from the UK, with a lot of familiar ads. Know the Ford one with Jackie O and that guy from Australian Idol? Thats here.

## Day Two

Two days and two entries! I'm doing well!!! My hope to have a written record of this trip could actually occur!

Well there's still time for that to change.

Speaking of changes, I'm coming home on saturday the 27th now, so that I can enrol in TAFE by myself on Sunday. I only miss out on a day or two in the spas and hot springs, stuff that I really don't care about. And best of all, I get a four-hour(?) flight without Jamieson climbing over me. Hurrah!

So today we did very little. Extremely little even. Getting up late we went to the pool. The New Zealanders really know how to have a pool- Hot! DAMN HOT! REAL HOT! But on the down side, this means an absolute shload of chlorine, which, due to my habit of doing most of my swimming underwater, was really not cool.

At night, our friend Sasha The Maxicab Driver took us out to this wildlife reserve pretty similar to Healsville Sanctuary, they do this Maori experience fancy show that was pretty fun. The tour guide designated a random German guy as our tribal Chief so he got to have this Maori warrior scream at him, which I'm sure was great fun..

[![Native bird](https://farm6.staticflickr.com/5597/15423379601_391b23463d_z_d.jpg)](https://www.flickr.com/photos/ubersejanus/15423379601/in/album-72157647905761520/)

Nature!

After that we were 'accepted into their tribe' which seemed to involve sitting around an amphitheatre and listening to them sing songs, a couple being their traditional songs, but a few that the parentals knew the tune to and also the hokie pokie. Then they taught the women there how to use poi, and got Chief Hans (or watever his name was) to bring down his 'longhairs' to do the haka. That was fun, although most of the guys aside from me, dad and this Irish guy nearby hadn't cottoned on to the fact that Longhairs meant "Warriors" meant "Men in the audience" (we skipped the middle bit though) and had to get that spelled out to them.

Another thing is that one of the performers looked white from the audience but was 'black' when you got up close to him, and that the second-string girl performer looked really familiar, something that really has me on edge, like the other night where one of Chrissy's friends came in and I was suuuuure that I had seen her somewhere before (Turned out that it was from her mobile phone's background, but it was driving me fucking mad trying to figure it out)

The park also did a wildlife tour after that, of the native New Zealand wildlife there, which was interesting, although they turned us loose in the rest of the park which was introduced species, something I found very strange. Deer, Possums, Geese, Wallabies, Magpies, and these massive Eels all showcased just as much as their natives… oh well. These Newzealanders are crazy \*taps head\*.

On the way home we caught some KFC. That was a bad idea, because the the girl who was serving us wasn't very good. But that was OK, because they still have hotrods. But the girl didn't put them in did she? But that was also OK, because i had a Snacker! I love those things, but we don't have them any more do we?

Hooray for international travel!

## Day Three

Day three here in New Zealand, and I'm still going strong!

We went out to a place called Akaroa, which was long ago the only french settlement in the country.

About 47 different people told me the tale of how this settlement happened. In the time that such things still went on, the French ship foolish told a nearby English settlement that they were going to start a colony at this harbour. So the British jumped in a Man O' War — a very fast ship, beat them there, and hoisted the Union Jack high.

But back to me,

We got up at 8am!

I'm never up at 8am! it was terrible! But anyway, at 8am we met our new friends, Ernie the Tour Guide and Howard & Jill, the English tourists.

In the beginning, I wasn't convinced that we were on the right tour, because he was going all around Christchurch but eventually we headed off through the Cambridge Mountains (I think that was what they was called) and off to Akaroa.

[![An old truck](https://farm3.staticflickr.com/2945/15426599795_073a0ffe31_z_d.jpg)](https://www.flickr.com/photos/ubersejanus/15426599795/in/album-72157647905761520/)

This old railway truck was super exciting

On the way we stopped off at this old railway station which was what made Jaimie's day. Back into the bus and we evenually made our way there, through a coffee shop/bar, a cheese factory (and I had thought that gravy fines were disgusting… thats nothing). Where Ernie cooked up an excellent barbeque, before we headed off to the ship.

It was maybe a 50-foot tour boat, that took us all around the harbour, which about 6 million years ago was a volcano.

The skipper told us that the New Zealand Dolphin was highly endangered, only 7000 left in the wild, of which 1000 were in the local area. So we shouldn't get our hopes up on seeing too many.

I reckon we must have seen about half of them.

Seriously, so many of them were around the boat, we were just sitting there until another tour group came in and jumped in, you know, a swim with the dolphins trip. Ive got a picture of one girl jumping in with a pool noodle, which was pretty funny.

On the way back into Christchurch, we stopped off at this beachcomber's museum/house. He's got all this stuff thats washed up on the shore and put it up to view. He's got all sorts of good stuff in there, everything from petrified wood to cannon shells, to these massive lightglobes. Really interesting to see what washes up.

[![The Akaroa River](https://farm4.staticflickr.com/3930/15239849309_11196c5b6a_z_d.jpg)](https://www.flickr.com/photos/ubersejanus/15239849309/in/album-72157647905761520/)

The Akaroa River was hidden behind where we had lunch

## Day Four

Day four here, and I wasn't going to be arsed writing again today, but well, it shouldn't take too long.

Today I went on a tour of Mt Sunday, which is a little knoll in this glacial valley.

It was made famous by it's role in two of Peter Jackson's Lord of the Rings films, the location of the village of Edoras.

[![Andúril, Flame of the West](https://farm4.staticflickr.com/3932/15426751922_77cf4a7b4f_z_d.jpg)](https://www.flickr.com/photos/ubersejanus/15426751922/in/album-72157647905761520/)

I pose with Andúril, Flame of the West

It was one long-arse drive from Christchurch to this valley, with Rex the tourguide, the two Frenchwomen, the French expat from London, this Japanese woman, two Germans, two guys from Denmark and two sheltered ladies from the Channel Islands.

When we got there, we met up with another tourgroup which was led by a woman that didn't really know her stuff. She was constantly flicking through a guidebook and calling the Rohirrim 'Rohans'. But once you tuned her out, the scenery was fantastic and well worth the cramped journey.

Tonight, we went to this US chain restaurant called Denny's, which Mum used to work at when Dad was working out on the gasfields every few weeks. As far as I know, we don't have any of these in Australia anymore, and this is a really good thing, as they are terrible.

[![Rakai River bridge view](https://farm3.staticflickr.com/2948/15426710722_5e4e252173_z_d.jpg)](https://www.flickr.com/photos/ubersejanus/15426710722/in/album-72157647905761520/)

We stopped at this bridge, it had a nice view

Right now, I'm watching a bit of Fox News. It really is your voice for evil. Just before there was this Imam and some fat white guy getting interviewed about the Imam getting discriminated against and the guy was sayin flat out 'If you want me to care, then denounce what's his name, Osseta – Osama bin Laden' and the Imam just said calmly "OK, I have. Several times."

The white man then said something about how everyone was being inconvenienced by the aftermath of 9/11. For example, he couldn't take aftershave on the plane with him anymore.

Oh look, now they're mocking an ex-Air Force Colonel who says that he's taken some pictures that show UFOs. OK, I would too — but I wouldn't start out supportive of him, then start making it into a joke. That's not cricket.

## Day Five

We left the hotel we've been staying at all this time, the Holiday Inn-on-Avon bright and early and headed off to the Christchurch Railway Station to board the TraNZalpine (see what they did there?) train to Greymouth, chief city of the West Coast.

[![TraNZalpine train](https://farm4.staticflickr.com/3933/15426910832_e3a434bbf3_z_d.jpg)](https://www.flickr.com/photos/ubersejanus/15426910832/in/album-72157647905761520/)

Ze train, Anton! Ze train!

And it was spectacular. Amazing scenery the whole way over. If you ever come here, then you should definitely take this trip.

For something different, we stayed that night in a Backpacker's Hostel, which is more of a cheap, communal hotel than whatever I was that I was expecting.

[![Braided River from the train train](https://farm3.staticflickr.com/2946/15240571138_708e95ba0e_z_d.jpg)](https://www.flickr.com/photos/ubersejanus/15240571138/in/album-72157647905761520/)

Braided rivers are super cool

## Day Six
We went to a smaller, less polished, version of Sovereign Hill called Shantytown, which has a working steam train. Jaimie was very excited. Other than that, the only thing that had me excited there was the office was located in a building obstinately marked as the Bank of New Zealand, with a sign saying that they apologise for the inconvenience, but all of their staff hae taken off for the latest gold rush, and therefore this branch of the bank has been closed until further notice.

[![Steam trains train](https://farm4.staticflickr.com/3930/15404246846_647b758599_z_d.jpg)](https://www.flickr.com/photos/ubersejanus/15404246846/in/album-72157647905761520/)

Steam trains at Shantytown

Yesterday was mostly spent driving straight back to the East Coast, and the civilised-er part of the island.

Now we're in a motel at a place called Woodend, and are planning on doing very little, kinda like what you would normally do on a holiday.

## Days Seven through Ten

As expected, this week has amounted to little, fast.

Today is roughly a 30 degree day, and the locals are all going all 'its sooo hot' and we're having a good chuckle.

We went to Woolworths today, that was surprisingly good. Its pretty much exactly the same as it is back home, even smelling the same (As I'm sure you guys know, Safeways have a very particular smell). But their doughnuts tasted horrible. There was a lot of 'Australian' food there, but they have their own colour scheme and banner, looks a lot more like Foodworks brands that Woolies… oh well.

Today we went to a place called Kaikoura. This is the "Whale Capital of New Zealand", apparently.

So we go out on the tour boat and we saw one whale, albeit twice. But we did also this albatross with a massive wingspan.

[![A whale](https://farm4.staticflickr.com/3935/15404316576_81aab44bc7_z_d.jpg)](https://www.flickr.com/photos/ubersejanus/15404316576/in/album-72157647905761520/)

The whale

And by massive, I mean that if I was to stand on my own shoulders, those wings would still be bigger. We also saw a fair-sized pod of dolphins, with their jumping antics.

When we get off the boat we went to the local fish & chippery for dinner, which I said should be eaten in the car on the way back here to Woodend.

But I was outvoted, at least until the cheeky buggers surrounded us and then one of the stinking air-rats snaps up my bit of fish right out of my hand. After that the other came around to my way of thinking.

## Day Eleven

Day Eleven consisted of me catching the plane home. It was uneventful. Unless you consider seeing the crowd of backpackers sleeping along all the walls of the airport in the dark interesting. Really, it's just more of a weird thing that happened though…


text:
<?xml version="1.0" encoding="UTF-8" ?>
<locale>
    <name>be</name>
    <displayName>Belarusian</displayName>
    <datetime>
        <nativeCalendar>григорианский календарь</nativeCalendar>
        <shortDatePattern>dd.MM.yyyy</shortDatePattern>
        <longDatePattern>d MMMM yyyy</longDatePattern>
        <dateSeparator>.</dateSeparator>
        <shortTimePattern>H:mm</shortTimePattern>
        <longTimePattern>H:mm:ss</longTimePattern>
        <timeSeparator>:</timeSeparator>
        <dayNames>
            <fullName>
                <name>нядзеля</name>
                <name>панядзелак</name>
                <name>аўторак</name>
                <name>серада</name>
                <name>чацвер</name>
                <name>пятніца</name>
                <name>субота</name>
            </fullName>
            <shortName>
                <name>нд</name>
                <name>пн</name>
                <name>аў</name>
                <name>ср</name>
                <name>чц</name>
                <name>пт</name>
                <name>сб</name>
            </shortName>
        </dayNames>
        <monthNames>
            <fullName>
                <name>Студзень</name>
                <name>Люты</name>
                <name>Сакавік</name>
                <name>Красавік</name>
                <name>Май</name>
                <name>Чэрвень</name>
                <name>Ліпень</name>
                <name>Жнівень</name>
                <name>Верасень</name>
                <name>Кастрычнік</name>
                <name>Лістапад</name>
                <name>Снежань</name>
            </fullName>
            <shortName>
                <name>Сту</name>
                <name>Лют</name>
                <name>Сак</name>
                <name>Кра</name>
                <name>Май</name>
                <name>Чэр</name>
                <name>Ліп</name>
                <name>Жні</name>
                <name>Вер</name>
                <name>Кас</name>
                <name>Ліс</name>
                <name>Сне</name>
            </shortName>
        </monthNames>
    </datetime>
    <numberFormat>
        <numberDecimalDigits>2</numberDecimalDigits>
        <numberDecimalSeparator>,</numberDecimalSeparator>
        <numberGroupSeparator> </numberGroupSeparator>
        <currencySymbol>р.</currencySymbol>
        <currencyDecimalDigits>2</currencyDecimalDigits>
        <currencyDecimalSeparator>,</currencyDecimalSeparator>
        <currencyGroupSeparator> </currencyGroupSeparator>
        <currencyNegativePattern>8</currencyNegativePattern>
        <currencyPositivePattern>3</currencyPositivePattern>
    </numberFormat>
</locale>


text: This is a footer template


text:
namespace quic {

template <typename T, typename... Args>
std::unique_ptr<T> QuicMakeUnique(Args&&... args) {
  return QuicMakeUniqueImpl<T>(std::forward<Args>(args)...);
}

template <typename T>
std::unique_ptr<T> QuicWrapUnique(T* ptr) {
  return QuicWrapUniqueImpl<T>(ptr);
}

}  // namespace quic

#endif  // NET_THIRD_PARTY_QUIC_PLATFORM_API_QUIC_PTR_UTIL_H_


text:
package org.apache.sling.maven.slingstart.launcher;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Launcher implements LauncherMBean {

    private final int listenerPort;

    public Launcher(final int listenerPort) {
        this.listenerPort = listenerPort;
    }

    @Override
    public void startupFinished() {
        final List<String> hosts = new ArrayList<String>();
        hosts.add("localhost");
        hosts.add("127.0.0.1");

        boolean done = false;
        int index = 0;
        while ( !done && index < hosts.size() ) {
            final String hostName = hosts.get(index);
            final int twoMinutes = 2 * 60 * 1000;

            Socket clientSocket = null;
            DataOutputStream out = null;
            BufferedReader in = null;
            try {
                clientSocket = new Socket();
                clientSocket.connect(new InetSocketAddress(hostName, listenerPort), twoMinutes);
                // without that, read() call on the InputStream associated with this Socket is infinite
                clientSocket.setSoTimeout(twoMinutes);

                out = new DataOutputStream(clientSocket.getOutputStream());
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                out.writeBytes("started\n");
                in.readLine();
                done = true;
            } catch (final Throwable ignore) {
                // catch Throwable because InetSocketAddress and Socket#connect throws unchecked exceptions
                // we ignore this for now
            } finally {
                if ( in != null ) {
                    try {
                        in.close();
                    } catch ( final IOException ioe) {
                        // ignore
                    }
                }
                if ( out != null ) {
                    try {
                        out.close();
                    } catch ( final IOException ioe) {
                        // ignore
                    }
                }
                if ( clientSocket != null ) {
                    try {
                        clientSocket.close();
                    } catch (final IOException e) {
                        // ignore
                    }
                }
            }
            index++;
        }
    }

    @Override
    public void startupProgress(Float ratio) {
        // nothing to do
    }
}


text:
using Moq;
using NUnit.Framework;

namespace LegacyBounce.Framework.Tests {
    [TestFixture]
    public class BounceFactoryTests {
        [Test]
        public void CreateDefaultInstance() {
            // arrange
            var factory = new BounceFactory();

            // act
            var bounce = factory.GetBounce();

            // assert
            Assert.That(bounce, Is.Not.Null);
        }

        [Test]
        public void CreateDefaultInstance_LogFactoryInitialized() {
            // arrange
            var factory = new BounceFactory();

            // act
            var bounce = factory.GetBounce();

            // assert
            Assert.That(bounce.LogFactory, Is.Not.Null);
        }

        [Test]
        public void CreateInstanceWithOverridenLogOptions() {
            // arrange
            var logFactoryMock = new Mock<ITaskLogFactory>();
            var factory = new BounceFactory();

            // act
            var logOptions = new LogOptions();
            var bounce = factory.GetBounce(logOptions);

            // assert
            Assert.That(bounce.LogOptions, Is.SameAs(logOptions));
        }
    }
}


text:
<?php

namespace Drupal\views\Plugin\views\sort;

use Drupal\Core\Form\FormStateInterface;

/**
 * Basic sort handler for dates.
 *
 * This handler enables granularity, which is the ability to make dates
 * equivalent based upon nearness.
 *
 * @ViewsSort("date")
 */
class Date extends SortPluginBase {

  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['granularity'] = array('default' => 'second');

    return $options;
  }

  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    $form['granularity'] = array(
      '#type' => 'radios',
      '#title' => $this->t('Granularity'),
      '#options' => array(
        'second' => $this->t('Second'),
        'minute' => $this->t('Minute'),
        'hour'   => $this->t('Hour'),
        'day'    => $this->t('Day'),
        'month'  => $this->t('Month'),
        'year'   => $this->t('Year'),
      ),
      '#description' => $this->t('The granularity is the smallest unit to use when determining whether two dates are the same; for example, if the granularity is "Year" then all dates in 1999, regardless of when they fall in 1999, will be considered the same date.'),
      '#default_value' => $this->options['granularity'],
    );
  }

  /**
   * Called to add the sort to a query.
   */
  public function query() {
    $this->ensureMyTable();
    switch ($this->options['granularity']) {
      case 'second':
      default:
        $this->query->addOrderBy($this->tableAlias, $this->realField, $this->options['order']);
        return;
      case 'minute':
        $formula = $this->getDateFormat('YmdHi');
        break;
      case 'hour':
        $formula = $this->getDateFormat('YmdH');
        break;
      case 'day':
        $formula = $this->getDateFormat('Ymd');
        break;
      case 'month':
        $formula = $this->getDateFormat('Ym');
        break;
      case 'year':
        $formula = $this->getDateFormat('Y');
        break;
    }

    // Add the field.
    $this->query->addOrderBy(NULL, $formula, $this->options['order'], $this->tableAlias . '_' . $this->field . '_' . $this->options['granularity']);
  }

}


text:
require_relative 'spec_helper'

describe WSList do

  it "find service by verb/route" do
    service = WSList.find(:get, 'services/test.xml')
    service.should_not be_nil
    service.url.should == '/services/test.xml'
    service.verb.should == :get

    service = WSList.find(:delete, 'services/test.xml')
    service.url.should == '/services/test.xml'
    service.verb.should == :delete
  end

  it "finds service without or without the leading slash" do
    service = WSList.find(:get, '/services/test.xml')
    service.should_not be_nil
    service.url.should == '/services/test.xml'

    service = WSList.find(:delete, '/services/test.xml')
    service.url.should == '/services/test.xml'

    service = WSList.find(:get, 'slash/foo')
    service.should_not be_nil
    service.url.should == "/slash/foo"
  end

  it "finds the root service" do
    service = WSList.find(:get, '/')
    service.should_not be_nil
    service.extra["name"].should == "root"
  end

  it "raises an exception if a duplicate service is added" do
    lambda{ WSList.add(WeaselDiesel.new("/")) }.should raise_exception(WSList::DuplicateServiceDescription)
  end

end


text:
Sequel.migration do
  up do
    SequelRails.connection.run(%{
      ALTER TABLE "visualizations" ADD COLUMN country_codes text[]
    })
  end

  down do
    alter_table :visualizations do
      drop_column :country_codes
    end
  end
end