text:
Moco mainly focuses on server configuration. There are only two kinds of API right now: **Request** and **Response**.

That means if we get the expected request and then return our response. Now, you can see a Moco reference in details.

**WARNING** the json configuration below is just a snippet for one pair of request and response, instead of the whole configuration file.

## Request

### Content
**@Since 0.7**

If you want to response according to request content, Moco server can be configured as following:

* Java API

```java
server.request(by("foo")).response("bar");
```

* JSON

```json
{
  "request" :
    {
      "text" : "foo"
    },
  "response" :
    {
      "text" : "bar"
    }
}
```

If request content is too large, you can put it in a file:

* Java API

```java
server.request(by(file("foo.request"))).response("bar");
```

* JSON

```json
{
  "request" :
    {
      "file" : "foo.request"
    },
  "response" :
    {
      "text" : "bar"
    }
}
```

### XML
**@Since 0.7**

XML is a popular format for Web Services. When a request is in XML, only the XML structure is important in most cases and whitespace can be ignored. The `xml` operator can be used for this case.

* Java API

```java
server.request(xml(text("<request><parameters><id>1</id></parameters></request>"))).response("foo");
```

* JSON

```json
{
  "request":
    {
      "uri": "/xml",
      "text":
        {
          "xml": "<request><parameters><id>1</id></parameters></request>"
        }
    },
  "response":
    {
      "text": "foo"
    }
}
```

**NOTE**: Please escape the quote in text.

The large request can be put into a file:

```json
{
   "request":
     {
        "uri": "/xml",
        "file":
          {
            "xml": "your_file.xml"
          }
    },
  "response":
    {
      "text": "foo"
    }
}
```

### XPath
**@Since 0.7**

For the XML/HTML request, Moco allows us to match request with XPath.

* Java API

```java
server.request(eq(xpath("/request/parameters/id/text()"), "1")).response("bar");
```

* JSON

```json
{
  "request" :
    {
      "method" : "post",
      "xpaths" :
        {
          "/request/parameters/id/text()" : "1"
        }
    },
  "response" :
    {
      "text" : "bar"
    }
}
```

### JSON Request

#### JSON Text
**@Since 0.7**

Json is rising with RESTful style architecture. Just like XML, in the most case, only JSON structure is important, so `json` operator can be used.

* Java API

```java
server.request(json(text("{\"foo\":\"bar\"}"))).response("foo");
```

* JSON

```json
{
  "request":
    {
      "uri": "/json",
      "text":
        {
          "json": "{\"foo\":\"bar\"}"
        }
    },
  "response":
    {
      "text": "foo"
    }
}
```

**NOTE**: Please escape the quote in text.

#### JSON Text Shortcut
**@Since 0.9.2**

As you have seen, it is so boring to write json with escape character, especially in json configuration. So you can try the json shortcut. The upper case could be rewritten as following:

* JSON

```json
{
    "request": {
        "uri": "/json",
        "json": {
            "foo": "bar"
        }
    },
    "response": {
        "text": "foo"
    }
}
```

#### JSON File
**@Since 0.7**

The large request can be put into a file:

* Java API

```java
server.request(json(file("your_file.json"))).response("foo");
```

* JSON

```json
{
  "request":
    {
      "uri": "/json",
      "file":
        {
          "json": "your_file.json"
        }
    },
  "response":
    {
      "text": "foo"
    }
}
```

### JSONPath
**@Since 0.7**

For the JSON/HTML request, Moco allows us to match request with JSONPath.

* Java API

```java
server.request(eq(jsonPath("$.book[*].price"), "1")).response("response_for_json_path_request");
```

* JSON

```json
{
  "request":
    {
      "uri": "/jsonpath",
      "json_paths":
        {
          "$.book[*].price": "1"
	    }
    },
  "response":
    {
      "text": "response_for_json_path_request"
    }
}
```

### Operator

Moco also supports some operators which helps you write your expectation easily.

#### Match
**@Since 0.7**

You may want to match your request with regular expression, **match** could be your helper:

* Java API

```java
server.request(match(uri("/\\w*/foo"))).response("bar");
```

* JSON

```json
{
  "request":
    {
      "uri":
        {
          "match": "/\\w*/foo"
        }
    },
  "response":
    {
      "text": "bar"
    }
}
```

Moco is implemented by Java regular expression, you can refer [here](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html) for more details.

#### Starts With
**@Since 0.9.2**

**starsWith** operator can help you decide if the request information starts with a piece of text.

* Java API

```java
server.request(startsWith(uri("/foo"))).response("bar");
```

* JSON

```json
{
  "request":
    {
      "uri":
        {
          "startsWith": "/foo"
        }
    },
  "response":
    {
      "text": "bar"
    }
}
```

#### Ends With
**@Since 0.9.2**

**endsWith** operator can help you decide if the request information ends with a piece of text.

* Java API

```java
server.request(endsWith(uri("foo"))).response("bar");
```

* JSON

```json
{
  "request":
    {
      "uri":
        {
          "endsWith": "foo"
        }
    },
  "response":
    {
      "text": "bar"
    }
}
```

#### Contain
**@Since 0.9.2**

**contain** operator helps you know whether the request information contains a piece of text.

* Java API

```java
server.request(contain(uri("foo"))).response("bar");
```

* JSON

```json
{
  "request":
    {
      "uri":
        {
          "contain": "foo"
        }
    },
  "response":
    {
      "text": "bar"
    }
}
```

#### Exist
**@Since 0.9.2**

**exist** operator is used to decide whether the request information exists.

* Java API

```java
server.request(exist(header("foo"))).response("bar");
```

* JSON

```json
{
  "request":
    {
      "headers": {
        "foo": {
          "exist" : "true"
        }
    },
  "response":
    {
      "text": "bar"
    }
}
```

For JSON API, you can decide whether the information does not exist.

* JSON

```json
{
  "request":
    {
      "headers": {
        "foo": {
          "exist" : "not"
        }
    },
  "response":
    {
      "text": "bar"
    }
}
```

## Response

### Content
**@Since 0.7**

As you have seen in previous example, response with content is pretty easy.

* Java API

```java
server.request(by("foo")).response("bar");
```

* JSON

```json
{
  "request" :
    {
      "text" : "foo"
    },
  "response" :
    {
      "text" : "bar"
    }
}
```

The same as request, you can response with a file if content is too large to put in a string.

* Java API

```java
server.request(by("foo")).response(file("bar.response"));
```

* JSON

```json
{
  "request" :
    {
      "text" : "foo"
    },
  "response" :
    {
      "file" : "bar.response"
    }
}
```

### Latency
**@Since 0.7**

Sometimes, we need a latency to simulate slow server side operation.

* Java API

```java
server.request(by("foo")).response(latency(5000));
```

* JSON

```json
{
  "request" :
    {
      "text" : "foo"
    },
  "response" :
    {
      "latency" : 5000
    }
}
```

### Sequence
**@Since 0.7**

Sometimes, we want to simulate a real-world operation which change server side resource. For example:
* First time you request a resource and "foo" is returned
* We update this resource
* Again request the same URL, updated content, e.g. "bar" is expected.

We can do that by
```java
server.request(by(uri("/foo"))).response(seq("foo", "bar", "blah"));
```

The other response settings are able to be set as well.
```java
server.request(by(uri("/foo"))).response(seq(status(302), status(302), status(200)));
```

### JSON Response

JSON response is the API without Java API, so if response is json, we don't have to write json with escape character. Hint, json api will setup Content-Type header as well.

```json
{
    "request": {
        "uri": "/json"
    },
    "response": {
        "json": {
            "foo" : "bar"
        }
    }
}
```

## Template(Beta)
**Note**: Template is an experimental feature which could be changed a lot in the future. Feel free to tell how it helps or you need more features in template.

Sometimes, we need to customize our response based on something, e.g. response should have same header with request.

The goal can be reached by template:

### Content
**@Since 0.8**

All request content can be used in template with "req.content"

* Java
```java
server.request(by(uri("/template"))).response(template("${req.content}"));
```

* JSON
```json
{
    "request": {
        "uri": "/template"
    },
    "response": {
        "text": {
            "template": "${req.content}"
        }
    }
}
```

### Custom Variable
**@Since 0.9.1**

You can provide your own variables in your template.

* Java
```java
server.request(by(uri("/template"))).response(template("${'foo'}", "foo", "bar"));
```

* JSON
```json
{
    "request": {
        "uri": "/template"
    },
    "response": {
        "text": {
            "template": {
                "with" : "${'foo'}",
                "vars" : {
                    "foo" : "bar"
                }
            }
        }
    }
}
```

**@Since 0.10.0**

You can also use extractor to extract information from request.

* Java
```java
server.request(by(uri("/template"))).response(template("${'foo'}", "foo", jsonPath("$.book[*].price")));
```

* JSON
```json
{
    "request": {
        "uri": "/template"
    },
    "response": {
        "text": {
            "template": {
                "with" : "${'foo'}",
                "vars" : {
                    "foo" : {
                      "json_paths": "$.book[*].price"
                    }
                }
            }
        }
    }
}
```

Other extractors, e.g. xpath also work here.


text:
lock '3.2.1'

set :application, 'test_app'

namespace :deploy do
end

redpajama_set_name: RedPajamaGithub


text:
FROM debian:sid
MAINTAINER Jessie Frazelle <jess@linux.com>

RUN apt-get update && apt-get install -y \
	ca-certificates \
	s3cmd \
	--no-install-recommends \
	&& rm -rf /var/lib/apt/lists/*

# Setup s3cmd config
RUN { \
		echo '[default]'; \
		echo 'access_key=$AWS_ACCESS_KEY'; \
		echo 'secret_key=$AWS_SECRET_KEY'; \
	} > ~/.s3cfg

ENV HOME /root
WORKDIR $HOME/s3cmd-workspace

ENTRYPOINT [ "s3cmd" ]


text:
from django.contrib import admin
from gtag.models import Tag, TaggedItem

class TaggedItemInline(admin.StackedInline):
    model = TaggedItem

class TagAdmin(admin.ModelAdmin):
    inlines = [TaggedItemInline]
    list_display = ["name", "slug"]
    ordering = ["name", "slug"]
    search_fields = ["name"]
    prepopulated_fields = {"slug": ["name"]}

admin.site.register(Tag, TagAdmin)


text:
class Pokey::Hook
  attr_accessor :destination, :http_method, :data, :interval

  def initialize
    @http_method = :post
    @data = {}
  end

  def make_http_request!
    Pokey::Request.make!(destination, http_method, data)
  end

  def valid?
    validate_http_method!
    validate_interval!
    validate_destination!
    true
  end

  private

  def validate_http_method!
    raise Pokey::InvalidHTTPMethodError unless [:get, :post].include?(@http_method)
  end

  def validate_destination!
    raise Pokey::InvalidDestinationError if destination.nil? || destination == ""
  end

  def validate_interval!
    raise Pokey::InvalidIntervalError if @interval.nil? || @interval.zero?
  end
end

class Pokey::InvalidHTTPMethodError < Exception; end;
class Pokey::InvalidDestinationError < Exception; end;
class Pokey::InvalidIntervalError < Exception; end;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ReactFluxDashboardProto.Web.Ignore
{
    public class EquipmentAlarmDto
    {
        public string AlarmId { get; set; }
        public DateTime Timestamp { get; set; }
    }
}


text:
module Main where

import ECC.Tester
import ECC.Types
import Data.Monoid

import qualified ECC.Code.BPSK as BPSK
import qualified ECC.Code.LDPC.Reference as Reference
import qualified ECC.Code.LDPC.ElimTanh as ElimTanh

import qualified ECC.Code.LDPC.Accelerate as Accelerate

codes :: Code
codes = BPSK.code <> Reference.code <> Accelerate.code

-- usage: ./Main 0 2 4 6 8 0  bpsk
-- or, to run the LDPC reference implementation, at a single EBNO = 2.2
--        ./Main 2.2 ldpc/reference/jpl.1K/20
main :: IO ()
main = eccMain codes eccPrinter


text:
package com.opengamma.financial.analytics.curve.exposure;

import java.util.Set;

import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.core.position.Trade;
import com.opengamma.financial.analytics.curve.CurveConstructionConfiguration;
import com.opengamma.financial.security.FinancialSecurity;

/**
 * Provides a set of names of {@link CurveConstructionConfiguration}s that are required to price
 * a security for a given {@link ExposureFunction}.
 */
public interface InstrumentExposuresProvider {

  /**
   * Gets a list of relevant curve construction configurations for a given {@link ExposureFunction} and
   * {@link FinancialSecurity}
   * @param instrumentExposureConfigurationName The instrument exposure configuration name
   * @param trade The trade to look up curve construction configurations against.
   * @return A set of {@link CurveConstructionConfiguration} names
   * @throws OpenGammaRuntimeException If no matching configuration(s) are found for the security
   */
  Set<String> getCurveConstructionConfigurationsForConfig(String instrumentExposureConfigurationName,
                                                          Trade trade);
}


text:
package com.blogspot.toomuchcoding.book.chapter4._6_StubbingVoidMethod.subsequent.hamcrest;

import com.blogspot.toomuchcoding.book.chapter4.common.exception.FailedToSavedPersonDataException;
import com.blogspot.toomuchcoding.book.chapter4.common.voidmethod.PersonProcessor;
import com.blogspot.toomuchcoding.book.chapter4.common.voidmethod.PersonSaver;
import com.blogspot.toomuchcoding.common.testng.MockitoTestNGListener;
import com.blogspot.toomuchcoding.person.Person;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Matchers.any;

@Listeners(MockitoTestNGListener.class)
public class PersonProcessorTestNgTest {

    @Mock PersonSaver personSaver;

    @InjectMocks PersonProcessor systemUnderTest;

    @Test
    public void should_first_fail_to_save_person_data_and_then_succeed() {
        // given
        willThrow(FailedToSavedPersonDataException.class).willNothing().given(personSaver).savePerson(any(Person.class));

        // when
        boolean updateSuccessful = systemUnderTest.process(new Person());
        boolean secondUpdateSuccessful = systemUnderTest.process(new Person());

        // then
        assertThat(updateSuccessful, equalTo(false));
        assertThat(secondUpdateSuccessful, equalTo(true));
    }
}


text:
title: "RecoMob : Opinion Mining for Product Enhancement"
layout: post
date: 2016-03-31
tag: [natural langauge processing, deep learning]
<!-- image: https://koppl.in/indigo/assets/images/jekyll-logo-light-solid.png -->
<!-- headerImage: true -->
projects: true
<!-- hidden: true # don't count this post in blog pagination -->
description: "Extract sentiment analysis and a recommendation engine for mobile reviews"
category: project
author: rahuliyer
externalLink: false
---

<!-- ![Screenshot](https://raw.githubusercontent.com/sergiokopplin/indigo/gh-pages/assets/screen-shot.png) -->

<!-- Example of project - Indigo Minimalist Jekyll Template - [Demo](http://sergiokopplin.github.io/indigo/). This is a simple and minimalist template for Jekyll for those who likes to eat noodles. -->
You can get code [Here](https://github.com/rahul-iyer/OpinionMiningForProductEnhancement)
Paper can be found [Here](http://ieeexplore.ieee.org/document/8117687/)
---

The project was aimed at helping the manufactures to improve their products by getting aspect based sentiment from reviews.
- Used Recursive Neural Tensor Network with Word Vectors.
- Used StanfordCoreNLP toolkit and its dependency parsing framework to extract the aspects and sentiment associated with them by formulating rules.
- Also analyzed how reviews of the product fare over the time.
- Used a k-NN for recommending products to the user based on specific aspects.


text:
from os import environ, access, pathsep, X_OK
from os.path import exists, isdir, split, join

is_exe = lambda fpth: exists(fpth) and access(fpth, X_OK)

def xwhich(program, also_look=[]):
    """ UNIX `which` analogue. Derived from:
        https://github.com/amoffat/pbs/blob/master/pbs.py#L95) """
    fpath, fname = split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        paths = environ["PATH"].split(pathsep)
        try:
            paths += list(also_look)
        except (TypeError, ValueError):
            pass
        for path in paths:
            exe_file = join(path, program)
            if is_exe(exe_file):
                return exe_file
    return None

def which(program):
    return xwhich(program)

if __name__ == '__main__':
    programs_to_try = (
        'python',
        'ls',
        'wget',
        'curl',
        'coffee',
        'lessc',
        'yo-dogg',
    )

    ali = [join(pth,
        'coffee-script', 'bin') for pth in environ['NODE_PATH'].split(':') if bool(
            len(pth)) and isdir(pth)]

    for p in programs_to_try:
        print "\t %20s --> %s" % (("which('%s')" % p), xwhich(p, also_look=ali))


text:
@implementation BJPublishActionButtonTransformer

+ (Class)transformedValueClass
{
    return [NSString class];
}

+ (BOOL)allowsReverseTransformation
{
    return NO;
}

- (id)transformedValue:(id)value
{
    if ([value respondsToSelector:@selector(intValue)]) {
        int status = [value intValue];
        switch (status) {
            case Started:
                return @"Stop";
            case Starting:
                return @"Starting...";
            case Stopped:
                return @"Start";
            case Stopping:
                return @"Stopping...";
            default:
                break;
        }
    }

    return @"Unknown";
}

@end


text:
const {expect} = require('expect');
const Helpers = require('./helpers');
const SheetsBatchGetValues = require('../sheets_batch_get_values');

describe('Spreadsheet batch get values snippet', () => {
  const helpers = new Helpers();

  after(() => {
    return helpers.cleanup();
  });

  it('should batch get spreadsheet values', async () => {
    const spreadsheetId = await helpers.createTestSpreadsheet();
    await helpers.populateValues(spreadsheetId);
    const result = await SheetsBatchGetValues.batchGetValues(spreadsheetId, [
      'A1:A3',
      'B1:C1',
    ]);
    const valueRanges = result.data.valueRanges;
    expect(valueRanges.length).toBe(2);
    const values = valueRanges[0].values;
    expect(values.length).toBe(3);
  });
});


text:
<?php
namespace ABRouterTest\Functional;

use ABRouterTest\BaseTestCase;

class RouterTest extends BaseTestCase
{
    /**
     * @test
     */
    public function Router()
    {
        $fileIndex = dirname(__FILE__) . './../Fixtures/FakeApp/index.php';
        $response = include $fileIndex;

        $this->assertRegExp('/FakeDummyController:dummyAction/', $response);
    }
}


text:
(function() {
  'use strict';

  describe('horizon.dashboard.project.workflow.launch-instance.workflow tests', function () {
    var launchInstanceWorkflow;

    beforeEach(module('horizon.app.core'));
    beforeEach(module('horizon.dashboard.project'));
    beforeEach(module(function($provide) {
      // Need to mock horizon.framework.workflow from 'horizon'
      var workflow = function(spec, decorators) {
        angular.forEach(decorators, function(decorator) {
          decorator(spec);
        });
        return spec;
      };
      $provide.value('horizon.app.core.openstack-service-api.serviceCatalog', {});
      $provide.value('horizon.framework.util.workflow.service', workflow);
    }));

    beforeEach(inject(function ($injector) {
      launchInstanceWorkflow = $injector.get('horizon.dashboard.project.workflow.launch-instance.workflow');
    }));

    it('should be defined', function () {
      expect(launchInstanceWorkflow).toBeDefined();
    });

    it('should have a title property', function () {
      expect(launchInstanceWorkflow.title).toBeDefined();
    });

    it('should have the six steps defined', function () {
      expect(launchInstanceWorkflow.steps).toBeDefined();
      expect(launchInstanceWorkflow.steps.length).toBe(6);

      var forms = [
        'launchInstanceSourceForm',
        'launchInstanceFlavorForm',
        'launchInstanceNetworkForm',
        'launchInstanceAccessAndSecurityForm',
        'launchInstanceKeypairForm',
        'launchInstanceConfigurationForm'
      ];

      forms.forEach(function(expectedForm, idx) {
        expect(launchInstanceWorkflow.steps[idx].formName).toBe(expectedForm);
      });
    });

    it('specifies that the network step requires the network service type', function() {
      expect(launchInstanceWorkflow.steps[2].requiredServiceTypes).toEqual(['network']);
    });
  });

})();


text:
  |-- download - folder for scripts to download raw data into raw folder
  |   +-- download.py - script to download and update raw data
  |   +-- *.py  - scrips called by download.py
  |
  |-- clean - folder for scripts to clean data into interim folder
  |   +-- clean.py - script to clean raw data
  |   +-- *.py - scripts called by clean.py
  |
  |-- preprocess - folder for scrips to process the data into processed folder for visualization and analysis
  |   +-- process.py - script to process the data
  |   +-- *.py - scripts called by process.py

# Steps to run:
1. python download.py
2. python clean.py
3. python preprocess.py

# Processed Data Structure (End goal for data scripting)
## Weekly
| location    | year   | week | dengue | malaria | MaxTempC | MeanTempC | MinTempC | DewPointC | ... etc.
| Singapore | 2012 | 1       | 1          | 0          | 32             | 30               | 28             | 20            | ... etc.
## Monthly
| location    | year   | month | dengue | malaria | MaxTempC | MeanTempC | MinTempC | DewPointC | ... etc.
| Singapore | 2012 | 1       | 1          | 0          | 32             | 30               | 28             | 20            | ... etc.
## Yearly
| location    | year   | dengue | malaria | MaxTempC | MeanTempC | MinTempC | DewPointC | ... etc.
| Singapore | 2012 | 100       | 10        | 32             | 30               | 28             | 20            | ... etc.

If data does not exist for that location (e.g. weekly Malaysia malaria), it will not be recorded as an observation in the table (e.g. weekly table).


text:
@extends('layouts.layout_foundation')
@section('content')

@if($hide == 'false')

Cadastrar Computadores

<form method="post" action="{{URL::to('/administracao/computadores/create');}}">

Polo:

					<select name="poloid" required>
						<option value="" disabled>--- SELECIONE UM POLO ---</option>
						@foreach($polos as $polo)
							<option value="{{ $polo->intpoloid }}">{{ $polo->strpolo }}</option>
						@endforeach
					</select>

Computador:

					<input type="text" name="cpu" placeholder="Nome do Computador" required />

			<input type="submit" value="Cadastrar" class="button small success" />
			<input type="reset" value="Limpar" class="button small alert" />

</form>
@else

Editar Computadores

<form method="post" action="{{URL::to('/administracao/computadores/update');}}">

Computador:

					<input type="text" name="cpu" value="{{ $item }}" required />

					<input type="hidden" name="cpuid" value="{{ $id }}" required />

			<input type="submit" value="Salvar" class="button small success" />
			<input type="button" value="Cancelar" onclick="window.history.back()" class="button small alert" />

</form>
@endif

				::: COMPUTADORES CADASTRADOS :::

				Polo / Computador
				Editar
				Excluir

		<?php $new = ''; $old = ''; ?>
		@foreach($query as $cpu)
		@if($cpu->strnomecpu!=null)

			<?php $new = $cpu->intpoloid; ?>
				@if(($new!=$old) || ($new==null))
					--- {{ $cpu->strpolo }} ---
				@else
					{{ "

" }}
				@endif

				{{ $cpu->strnomecpu }}
				idcpu.'&item='.$cpu->strnomecpu);}}">
				idcpu);}}" onclick="return confirm('Você tem certeza disto?')">

		@endif
		<?php $old = $new; ?>

		@endforeach

@stop


text:
using Akka.Actor;
using Akka.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace UnboundedNondeterminism
{
    ///
    /// A base class which extends <see cref="ReceivePersistentActor"/> to:
    /// • Use a <see cref="Eventsourced.PersistenceId"/> generated from the <see cref="MemberInfo.Name"/> and a <see cref="Guid"/>.
    /// • Handle a <see cref="PersistableBase.Stop"/> message to safely stop the actor.
    ///
    public abstract class PersistableBase : ReceivePersistentActor
    {
        /// Instructs an <see cref="ActorBase"/> to stop when possible.
        /// <remarks>http://getakka.net/docs/persistence/persistent-actors#safely-shutting-down-persistent-actors</remarks>
        public sealed class Stop { }

        /// Returned in response to <see cref="Stop"/> when the <see cref="ActorBase"/> has stopped.
        public sealed class Stopped { }

        /// A <see cref="Guid"/> for <see langword="this"/>.
        public readonly Guid PersistenceGuid;

        /// <inheritdoc />
        public override string PersistenceId => $"{GetType().Name}-{PersistenceGuid}";

        /// <inheritdoc />
        /// <param name="persistenceGuid"><see cref="PersistenceGuid"/>.</param>
        public PersistableBase(Guid persistenceGuid)
        {
            PersistenceGuid = persistenceGuid;

            Command<Stop>(s => Context.Stop(Self));
        }
    }
}


text:
require File.expand_path('../../test_helper', __FILE__)

class WikiContentVersionTest < ActiveSupport::TestCase
  fixtures :projects, :users, :wikis, :wiki_pages, :wiki_contents, :wiki_content_versions

  def setup
  end

  def test_destroy
    v = WikiContent::Version.find(2)

    assert_difference 'WikiContent::Version.count', -1 do
      v.destroy
    end
  end

  def test_destroy_last_version_should_revert_content
    v = WikiContent::Version.find(3)

    assert_no_difference 'WikiPage.count' do
      assert_no_difference 'WikiContent.count' do
        assert_difference 'WikiContent::Version.count', -1 do
          assert v.destroy
        end
      end
    end
    c = WikiContent.find(1)
    v = c.versions.last
    assert_equal 2, c.version
    assert_equal v.version, c.version
    assert_equal v.comments, c.comments
    assert_equal v.text, c.text
    assert_equal v.author, c.author
    assert_equal v.updated_on, c.updated_on
  end

  def test_destroy_all_versions_should_delete_page
    WikiContent::Version.find(1).destroy
    WikiContent::Version.find(2).destroy
    v = WikiContent::Version.find(3)

    assert_difference 'WikiPage.count', -1 do
      assert_difference 'WikiContent.count', -1 do
        assert_difference 'WikiContent::Version.count', -1 do
          assert v.destroy
        end
      end
    end
    assert_nil WikiPage.find_by_id(1)
  end
end


text:
-- MySQL dump 10.13  Distrib 5.5.38, for debian-linux-gnu (x86_64)
--
-- Host: localhost    Database: lolalerter
-- ------------------------------------------------------
-- Server version 5.5.38-0ubuntu0.12.04.1

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Temporary table structure for view `active_summoners`
--

DROP TABLE IF EXISTS `active_summoners`;
/*!50001 DROP VIEW IF EXISTS `active_summoners`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE TABLE `active_summoners` (
  `ID` tinyint NOT NULL,
  `User` tinyint NOT NULL,
  `SummonerName` tinyint NOT NULL,
  `SummonerID` tinyint NOT NULL,
  `Alerter` tinyint NOT NULL,
  `Timestamp` tinyint NOT NULL
) ENGINE=MyISAM */;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `active_users`
--

DROP TABLE IF EXISTS `active_users`;
/*!50001 DROP VIEW IF EXISTS `active_users`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE TABLE `active_users` (
  `ID` tinyint NOT NULL,
  `APIKey` tinyint NOT NULL,
  `TwitchUsername` tinyint NOT NULL,
  `TwitchDisplay` tinyint NOT NULL,
  `TwitchToken` tinyint NOT NULL,
  `Timestamp` tinyint NOT NULL,
  `CreateDate` tinyint NOT NULL,
  `RememberToken` tinyint NOT NULL,
  `TwitchAlertsKey` tinyint NOT NULL,
  `MinimumDonation` tinyint NOT NULL,
  `ShowResubs` tinyint NOT NULL,
  `LastNotice` tinyint NOT NULL
) ENGINE=MyISAM */;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `alerter_friends`
--

DROP TABLE IF EXISTS `alerter_friends`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `alerter_friends` (
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  `Alerter` int(10) NOT NULL,
  `SummonerID` int(10) NOT NULL,
  `Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`),
  KEY `ShadowFriendID` (`Alerter`),
  CONSTRAINT `AlerterFriendID` FOREIGN KEY (`Alerter`) REFERENCES `alerters` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `alerter_statistics`
--

DROP TABLE IF EXISTS `alerter_statistics`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `alerter_statistics` (
  `Alerter` int(11) NOT NULL,
  `OnlineUsers` int(11) NOT NULL DEFAULT '0',
  `TotalSubscribed` int(11) NOT NULL DEFAULT '0',
  `Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`Alerter`),
  UNIQUE KEY `Shadow` (`Alerter`),
  CONSTRAINT `AlerterStatistics` FOREIGN KEY (`Alerter`) REFERENCES `alerters` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `alerter_statistics`
--

LOCK TABLES `alerter_statistics` WRITE;
/*!40000 ALTER TABLE `alerter_statistics` DISABLE KEYS */;
INSERT INTO `alerter_statistics` VALUES (1,0,0,'2015-09-04 02:00:00');
/*!40000 ALTER TABLE `alerter_statistics` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `alerters`
--

DROP TABLE IF EXISTS `alerters`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `alerters` (
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  `Username` varchar(50) NOT NULL,
  `Region` int(11) NOT NULL,
  `SummonerID` int(11) NOT NULL,
  `SummonerName` varchar(50) NOT NULL,
  `Password` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `Message` varchar(200) NOT NULL,
  `Enabled` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`),
  KEY `TrackerRegion` (`Region`),
  CONSTRAINT `TrackerRegion` FOREIGN KEY (`Region`) REFERENCES `regions` (`ID`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `alerters`
--

LOCK TABLES `alerters` WRITE;
/*!40000 ALTER TABLE `alerters` DISABLE KEYS */;
INSERT INTO `alerters` VALUES (1,'lolalerter',1,51012155,'LoLAlerter','PlaintextPassword','lolalerter@gmail.com','NA Bot Online!',1);
/*!40000 ALTER TABLE `alerters` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `messages`
--

DROP TABLE IF EXISTS `messages`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `messages` (
  `User` int(11) NOT NULL,
  `InGame` varchar(100) DEFAULT '{} has just subscribed!',
  `InChat` varchar(100) DEFAULT '♥ Thanks for subscribing, {}!',
  `NewDonation` varchar(100) DEFAULT '{user} has donated ${amount}!',
  PRIMARY KEY (`User`),
  UNIQUE KEY `User` (`User`),
  CONSTRAINT `MessageUser` FOREIGN KEY (`User`) REFERENCES `users` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `messages`
--

LOCK TABLES `messages` WRITE;
/*!40000 ALTER TABLE `messages` DISABLE KEYS */;
INSERT INTO `messages` VALUES (1,'{sub} has just joined the club!','★ Thanks for subscribing, {sub}!','{user} has donated ${amount}!');
/*!40000 ALTER TABLE `messages` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `notices`
--

DROP TABLE IF EXISTS `notices`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notices` (
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  `Message` varchar(200) NOT NULL,
  `Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `notices`
--

LOCK TABLES `notices` WRITE;
/*!40000 ALTER TABLE `notices` DISABLE KEYS */;
INSERT INTO `notices` VALUES (1,'Welcome to open-source LoLAlerter!','2015-09-04 02:00:00');
/*!40000 ALTER TABLE `notices` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `regions`
--

DROP TABLE IF EXISTS `regions`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `regions` (
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  `RegionName` varchar(50) NOT NULL,
  `RegionCode` varchar(50) NOT NULL,
  `RegionChat` varchar(50) NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `RegionName` (`RegionName`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `regions`
--

LOCK TABLES `regions` WRITE;
/*!40000 ALTER TABLE `regions` DISABLE KEYS */;
INSERT INTO `regions` VALUES (1,'North America','NA','na2'),(2,'EU West','EUW','euw1'),(3,'Korea','KR','kr'),(4,'Oceania','OCE','oc1'),(5,'Latin America North','LAN','la1'),(6,'Latin America South','LAS','la2'),(7,'EU Nordic and East','EUNE','eun1'),(8,'Brazil','BR','br'),(9,'Russia','RU','ru'),(10,'Turkey','TR','tr');
/*!40000 ALTER TABLE `regions` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `settings`
--

DROP TABLE IF EXISTS `settings`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `settings` (
  `Key` varchar(50) NOT NULL,
  `Value` varchar(50) NOT NULL,
  PRIMARY KEY (`Key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `settings`
--

LOCK TABLES `settings` WRITE;
/*!40000 ALTER TABLE `settings` DISABLE KEYS */;
INSERT INTO `settings` VALUES ('AdminSummoner','31186414'),('LargestDonation','10'),('MaxFriends','300'),('PayPalEmail','XXXXXXXXXXXXX@gmail.com'),('RiotAPI','XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'),('SubscriptionMonthly','5'),('TwitchAuth','oauth:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'),('TwitchUsername','LoLAlerterBot');
/*!40000 ALTER TABLE `settings` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `subscribers`
--

DROP TABLE IF EXISTS `subscribers`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `subscribers` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `User` int(11) NOT NULL,
  `TwitchID` int(11) NOT NULL,
  `Username` varchar(50) NOT NULL,
  `DisplayName` varchar(50) NOT NULL,
  `AddDate` datetime NOT NULL,
  `UnsubDate` datetime DEFAULT NULL,
  `Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Active` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`ID`),
  UNIQUE KEY `user_subscribers` (`User`,`TwitchID`),
  KEY `SubscriberUser` (`User`),
  CONSTRAINT `SubscriberUser` FOREIGN KEY (`User`) REFERENCES `users` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `subscription_payments`
--

DROP TABLE IF EXISTS `subscription_payments`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `subscription_payments` (
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  `User` int(10) NOT NULL,
  `PayerEmail` varchar(50) NOT NULL,
  `FirstName` varchar(50) NOT NULL,
  `LastName` varchar(50) NOT NULL,
  `TXNID` varchar(50) NOT NULL,
  `GrossAmount` double NOT NULL,
  `FeeAmount` double NOT NULL,
  `PaymentDate` datetime NOT NULL,
  `ExpiryDate` datetime NOT NULL,
  `Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`),
  KEY `User` (`User`),
  CONSTRAINT `PaymentUser` FOREIGN KEY (`User`) REFERENCES `users` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `subscription_payments`
--

LOCK TABLES `subscription_payments` WRITE;
/*!40000 ALTER TABLE `subscription_payments` DISABLE KEYS */;
INSERT INTO `subscription_payments` VALUES (1,1,'XXXXXXXXXX@gmail.com','Redback','Thomson','XXXXXXXXXXXXXXXXX',5,0.48,'2015-09-04 02:30:00','2015-10-04 02:30:00','2015-09-04 02:30:00');
/*!40000 ALTER TABLE `subscription_payments` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `summoners`
--

DROP TABLE IF EXISTS `summoners`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `summoners` (
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  `User` int(10) NOT NULL,
  `SummonerName` varchar(16) NOT NULL,
  `SummonerID` int(10) NOT NULL,
  `Alerter` int(11) NOT NULL,
  `Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`),
  KEY `UserSummoner` (`User`),
  KEY `SummonerShadow` (`Alerter`),
  CONSTRAINT `SummonerAlerter` FOREIGN KEY (`Alerter`) REFERENCES `alerters` (`ID`) ON UPDATE CASCADE,
  CONSTRAINT `UserSummoner` FOREIGN KEY (`User`) REFERENCES `users` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `summoners`
--

LOCK TABLES `summoners` WRITE;
/*!40000 ALTER TABLE `summoners` DISABLE KEYS */;
INSERT INTO `summoners` VALUES (1,1,'Intercontinent',31186414,1,'2015-09-04 12:00:00');
/*!40000 ALTER TABLE `summoners` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `user_statistics`
--

DROP TABLE IF EXISTS `user_statistics`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_statistics` (
  `User` int(10) NOT NULL,
  `TotalSubscribed` int(10) NOT NULL DEFAULT '0',
  PRIMARY KEY (`User`),
  CONSTRAINT `StatisticsUser` FOREIGN KEY (`User`) REFERENCES `users` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `user_statistics`
--

LOCK TABLES `user_statistics` WRITE;
/*!40000 ALTER TABLE `user_statistics` DISABLE KEYS */;
INSERT INTO `user_statistics` VALUES (1,0);
/*!40000 ALTER TABLE `user_statistics` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `users`
--

DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  `APIKey` varchar(36) DEFAULT NULL,
  `TwitchUsername` varchar(25) NOT NULL,
  `TwitchDisplay` varchar(25) NOT NULL,
  `TwitchToken` varchar(31) DEFAULT NULL,
  `Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `CreateDate` datetime NOT NULL,
  `RememberToken` varchar(60) DEFAULT NULL,
  `TwitchAlertsKey` varchar(50) DEFAULT NULL,
  `MinimumDonation` double DEFAULT NULL,
  `ShowResubs` tinyint(1) NOT NULL DEFAULT '1',
  `LastNotice` int(11) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `TwitchUsername` (`TwitchUsername`),
  KEY `UserNotice` (`LastNotice`),
  CONSTRAINT `UserNotice` FOREIGN KEY (`LastNotice`) REFERENCES `notices` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `users`
--

LOCK TABLES `users` WRITE;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` VALUES (1,'ABCDEFGH-1234-IJKL-5678-MNOPQRSTUVWX','redbackthomson','RedbackThomson','XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX','2015-09-04 12:00:00','2015-09-04 12:00:00','',NULL,NULL,1,0);
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Final view structure for view `active_summoners`
--

/*!50001 DROP TABLE IF EXISTS `active_summoners`*/;
/*!50001 DROP VIEW IF EXISTS `active_summoners`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50001 VIEW `active_summoners` AS select `lolalerter`.`summoners`.`ID` AS `ID`,`lolalerter`.`summoners`.`User` AS `User`,`lolalerter`.`summoners`.`SummonerName` AS `SummonerName`,`lolalerter`.`summoners`.`SummonerID` AS `SummonerID`,`lolalerter`.`summoners`.`Alerter` AS `Alerter`,`lolalerter`.`summoners`.`Timestamp` AS `Timestamp` from `summoners` where `lolalerter`.`summoners`.`User` in (select `active_users`.`ID` from `active_users`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `active_users`
--

/*!50001 DROP TABLE IF EXISTS `active_users`*/;
/*!50001 DROP VIEW IF EXISTS `active_users`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50001 VIEW `active_users` AS select `lolalerter`.`users`.`ID` AS `ID`,`lolalerter`.`users`.`APIKey` AS `APIKey`,`lolalerter`.`users`.`TwitchUsername` AS `TwitchUsername`,`lolalerter`.`users`.`TwitchDisplay` AS `TwitchDisplay`,`lolalerter`.`users`.`TwitchToken` AS `TwitchToken`,`lolalerter`.`users`.`Timestamp` AS `Timestamp`,`lolalerter`.`users`.`CreateDate` AS `CreateDate`,`lolalerter`.`users`.`RememberToken` AS `RememberToken`,`lolalerter`.`users`.`TwitchAlertsKey` AS `TwitchAlertsKey`,`lolalerter`.`users`.`MinimumDonation` AS `MinimumDonation`,`lolalerter`.`users`.`ShowResubs` AS `ShowResubs`,`lolalerter`.`users`.`LastNotice` AS `LastNotice` from `users` where `lolalerter`.`users`.`ID` in (select `lolalerter`.`subscription_payments`.`User` from `subscription_payments` where (`lolalerter`.`subscription_payments`.`ExpiryDate` > (utc_timestamp() - interval 8 hour))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2015-09-04  3:00:00


text:
package sdb.examples;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.sdb.SDBFactory;
import org.apache.jena.sdb.Store;
import org.apache.jena.sdb.store.StoreFactory;

/** Example of use with the Jena API for models. */

public class ExModelSDB
{
    static public void main(String...argv)
    {
        Store store = StoreFactory.create("sdb.ttl") ;
        Model model = SDBFactory.connectDefaultModel(store) ;

        StmtIterator sIter = model.listStatements() ;
        for ( ; sIter.hasNext() ; )
        {
            Statement stmt = sIter.nextStatement() ;
            System.out.println(stmt) ;
        }
        sIter.close() ;
        store.close() ;
    }
}


text:
from collections import defaultdict
import math
import re

class ProbabilityCounter(object):
	def __init__(self):
		self.counts = defaultdict(int)
		self.total = 0

	def add(self, item):
		self.counts[item] += 1
		self.total += 1

	def __getitem__(self, item):
		return self.counts[item] * 1.0 / self.total if item in self.counts else 0.0

	def iteritems(self):
		return ((item, count * 1.0 / self.total) for (item, count) in self.counts.iteritems())

SMOOTHING = 0.000001
FREE_TEXT_PROB = 0.0001

def smooth_log_prob(p):
	return math.log((p+SMOOTHING) * (1 - SMOOTHING))

class Phrase(object):
	def __init__(self, intent, items):
		self.intent = intent
		self.items = items

	def items_with_intermediate_states(self):
		items = []
		prev_item_name = "$START_{0}".format(self.intent)
		for item, i in zip(self.items, xrange(len(self.items))):
			if isinstance(item, list):
				name = item[0]
				prev_item_name = name
				items.append(item)
			elif isinstance(item, str) or isinstance(item, unicode):
				next_item_name = self.items[i+1][0] if i+1 < len(self.items) else "$END_{0}".format(self.intent)
				intermediate_item_name = "[{0}:{1}..{2}]".format(self.intent, prev_item_name, next_item_name)
				items.append([intermediate_item_name, item])
		return items

	def token_state_tuples(self):
		tuples = []
		for item in self.items_with_intermediate_states():
			for token in tokenize(item[1]):
				tuples.append((token, item[0]))
		return tuples

	def __repr__(self):
		return "[{0}: {1}]".format(self.intent, self.items)

	def get(self, key, default):
		for item in self.items:
			if isinstance(item, list) and item[0] == key:
				return item[1]
		return default

def flatten(list_of_lists):
	return reduce(lambda a, b: a+b, list_of_lists, [])

def split_strings_by_regex(strings, regex):
	print regex, type(regex), strings
	return flatten(map(lambda s: re.split(regex, s), strings))

def tokenize(text, preserve_regexes=None):
	text = text.lower()
	tokens = re.split(r"\s+", text)
	return tokens

def count_runs(items):
	runs = []
	for item in items:
		if len(runs) > 0 and runs[-1][0] == item:
			runs[-1] = (item, runs[-1][1]+1)
		else:
			runs.append((item, 1))
	return runs

def phrase_from_candidate(candidate, tokens):
	log_prob, intent, states = candidate
	states = states[1:] # strip '$START'
	items = []
	for state, n_tokens in count_runs(states):
		if state[0] == '[':
			# it's an intermediate state, so don't preserve it in output:
			items.append(" ".join(tokens[:n_tokens]))
		else:
			items.append([state, " ".join(tokens[:n_tokens])])
		tokens = tokens[n_tokens:]
	return Phrase(intent, items)

def parse_phrase(text, examples, state_regexes=None):
	if state_regexes == None: state_regexes = {}
	transition_probs = defaultdict(ProbabilityCounter)
	emission_probs = defaultdict(ProbabilityCounter)
	intents = set()
	states_for_root_states = defaultdict(set)
	for ex in examples:
		intents.add(ex.intent)
		# count transitions:
		states = map(lambda (token, state): state, ex.token_state_tuples())
		for state, next_state in zip(['$START_{0}'.format(ex.intent)] + states, states + ['$END_{0}'.format(ex.intent)]):
			transition_probs[state.split('/')[0]].add(next_state.split('/')[0])
			states_for_root_states[state.split('/')[0]].add(state)
		# count emissions:
		for item in ex.items_with_intermediate_states():
			name = item[0]
			if name[0] != '~':
				for token in tokenize(item[1]):
					emission_probs[name].add(token)
	def get_emission_prob(state, token):
		if state[0] == '~':
			return FREE_TEXT_PROB
		elif state[0] == '*':
			# a regex state:
			# print "does {0} match {1}? {2}".format(token, state[1:], re.match(state_regexes[state[1:]], token))
			return 1 if re.match(state_regexes[state[1:]], token) else 0
		else:
			return emission_probs[next_state][token]
	best_candidate = None
	# 'candidates' are (log_prob, intent, [state]) tuples
	tokens = tokenize(text, preserve_regexes = state_regexes.values())
	for intent in intents:
		# print 'INTENT {0}'.format(intent)
		candidates = [(0.0, intent, ['$START_{0}'.format(intent)])]
		for token in tokens + [None]:
			# if intent == 'search': print candidates
			best_candidates_for_last_state = {}
			for (candidate_log_prob, candidate_intent, candidate_states) in candidates:
				state = candidate_states[-1].split('/')[0]
				for next_state_root, transition_prob in transition_probs[state].iteritems():
					new_candidate = None
					if token == None:
						if next_state_root == "$END_{0}".format(intent):
							# print state, next_state_root, transition_prob
							new_candidate = (candidate_log_prob + smooth_log_prob(transition_prob), candidate_intent, candidate_states)
							if next_state_root not in best_candidates_for_last_state or new_candidate[0] > best_candidates_for_last_state[next_state_root][0]:
								best_candidates_for_last_state[next_state_root] = new_candidate
					else:
						for next_state in states_for_root_states[next_state_root]:
							if next_state[0]=='[':
								state_intent = next_state.split(':')[0][1:]
								if state_intent != intent:
									continue
							emission_prob = get_emission_prob(next_state, token)
							new_candidate = (candidate_log_prob + smooth_log_prob(transition_prob) + smooth_log_prob(emission_prob), candidate_intent, candidate_states + [next_state])
							if next_state not in best_candidates_for_last_state or new_candidate[0] > best_candidates_for_last_state[next_state][0]:
								best_candidates_for_last_state[next_state] = new_candidate
			candidates = best_candidates_for_last_state.values()
		#print candidates
		for candidate in candidates:
			if best_candidate == None or candidate[0] > best_candidate[0]:
				best_candidate = candidate
	return phrase_from_candidate(best_candidate, tokens) if best_candidate else None


text:
class C_BasePlayer;

class C_DOTAPlayer : public C_DOTABaseEntity
{
	DECLARE_CLASS( C_DOTAPlayer, C_DOTABaseEntity );

public:
	C_DOTAPlayer( C_BasePlayer *pEnt );

	operator C_BasePlayer *()
	{
		return reinterpret_cast<C_BasePlayer *>( GetEntity() );
	}

	// is this player instance the local player?
	bool IsLocalPlayer();

public:
	CEntProp( int, m_iPlayerID );

	CEntProp( C_BaseEntity *, m_hAssignedHero );

public:
	static C_DOTAPlayer GetLocalPlayer();

	static C_DOTAPlayer GetPlayerByIndex( int index );
	static C_DOTAPlayer GetPlayerByPlayerID( int playerId );

};


text:
namespace rl
{
	namespace math
	{
		typedef ::Eigen::AngleAxis<Real> AngleAxis;
	}
}

#endif // RL_MATH_ROTATION_H


text:
order: 3.3
version: 4.20.0
title:
  zh-CN: 字段监听 Hooks
  en-US: Watch Hooks
---

## zh-CN

`useWatch` 允许你监听字段变化,同时仅当该字段变化时重新渲染。API 文档请[查阅此处](#Form.useWatch)。

## en-US

`useWatch` helps watch the field change and only re-render for the value change. [API Ref](#Form.useWatch).

```tsx
import React from 'react';
import { Form, Input, InputNumber, Typography } from 'antd';

const Demo = () => {
  const [form] = Form.useForm<{ name: string; age: number }>();
  const nameValue = Form.useWatch('name', form);

  return (
    <>
      <Form form={form} layout="vertical" autoComplete="off">
        <Form.Item name="name" label="Name (Watch to trigger rerender)">
          <Input />
        </Form.Item>
        <Form.Item name="age" label="Age (Not Watch)">
          <InputNumber />
        </Form.Item>
      </Form>

      <Typography>
        <pre>Name Value: {nameValue}</pre>
      </Typography>
    </>
  );
};

export default Demo;
```


text:
<TITLE>Review for Birdcage, The (1996)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Birdcage, The (1996)

reviewed by
Philip Lam

                              THE BIRDCAGE
                       A film review by Philip Lam
                        Copyright 1996 Philip Lam

Directed by: Mike Nichols
Written by: Elaine May
Cast : Robin Williams (Armand Goldman), Gene Hackman (Senator Kevin
Keeley), Nathan Lane (Albert Goldman/ Starina), Dianne Wiest (Louise
Keeley), Dan Futterman (Val Goldman), Calista Flockhart (Barbara
Keeley), Hank Azaria (Agador), Christine Baranski (K atherine)
Produced by : MGM/UA / Mgm/ua Distribution Co. (distributor) / United
Artists
Rating : *** out of *****

DON'T WATCH THIS BIRDIE

The problem with watching a movie where well-known actors appear in
drag is that invariably the movie just becomes a vehicle for said
actors trying to stretch the comic buck of the dressing-up thing for
as much as they can. Remember TO WONG FOO, THANKS FO R EVERYTHING,
JULIE NEWMAR? Acting, even by Hollywood standards, is at a serious
premium here at BIRDCAGE.

But then again, that's obviously not the reason why one would go to
watch this movie. It's a comedy, or at least that's what it's billed
as. Adapted from the french movie LA CAGE AUX FOLLES or "The Cage of
Madmen," this movie doesn't live up to the origin al. Isn't it funny
how so many good movies from France lose something when they get
Hollywoodised? (A little qualifier would be THE ASSASSIN, but that's
only because they copied the whole movie line for line, and Brigette
Fonda is kinda cute). Clearly the french title loses something with my
translation and the Hollywood version actually sounds nicer, but hey,
I could just be a poor translator.

The story revolves around the lives of two families, the
Goldmans and the Keeleys. Robin Williams and Nathan Lane play Armand
and Albert Goldman, owners of the eponymous Birdcage, a drag
nightclub, while Gene Hackman and Dianne Wiest are Senator and Mrs
Keeley, believers in the sort of conservatism that would have made
them burn the Puritans at the stake for Caligari-like decadence.

The two families collide when their children Val and Barbara decide to
get married. Barbara needs to convince her Senator Dad that the
marriage is the right thing despite the fact that she's only 18. He is
initially reluctant as he's too busy planning his re-election.
Circumstances change and he's led to believe that the only way to
salvage his political career is to be seen doing something with a
"feel-good" factor, and there's hardly anything more likely to tug the
heartstrings of the public than a good 'ol-fashioned wedding. Val
panics and enlists the help of his dads in an attempt to make them
look like a normal family for one day as the Keeleys come to visit.

What results is embarassingly obvious and really, the audience just
laughs because it feels obliged to. Nothing original happens in this
movie and Robin Williams shows once again that he's a cotton candy
actor: any good feelings about him disappear strai ght after walking
under the exit sign. What's worse in this movie is that he's abysmally
insipid throughout. He's an actor who's realized that him trying to
act really isn't all that commercially viable (be honest: anyone could
have done DEAD POETS' SOCIE TY; and THE FISHER KING, who understood
that??). Reversion back to Mork-mode was inevitable. Doing that
properly may have at least salvaged something of this mess. He's so
boring in this movie that he actually makes Nathan Lane look good.
Yeah sure, you'v e probably seen the shots of the movie and heard the
touting of Nathan Lane stealing the show. Well, it isn't so much a
case of him stealing the show as everyone else throwing it at him. His
drag impersonation is laboured and definitely gets on the nerves
quickly. That scene with Williams trying to teach Lane "How To Be a
Man" was definitely a 10 on the cheesy scale.

That's not all. Like father like son and here, Val (Dan Futterman)
feels some genetic need to emulate Williams' perfomance. He maintains
this unfazable look through all the tribulations his character is
supposed to be going through. Anyone else would have done a decent
portrayal of a young man whose life is about to come apart. This is
obviously below Val and one suspects that he's incapable of doing
anything but look cool. He certainly looks like he'll be more
comfortable in a "Top Gun" sort of movie tha n a funny-farm drag
misadventure.

Scraping the bottom of the barrel, we get a couple of plus points. You
get a little look at Miami's South Beach where the film is set and we
get to see Gene Hackman's finest hour in the last minute of the movie.
Be warned though: Don't watch this movie un less you're prepared to
not think about it ever after. It's the stuff nightmares are made of.

REVIEW's rating system:
* Wait for the video.
** A little creaky, but still better than staying at home with Gotcha!
*** Pretty good, bring a friend.
**** Amazing, potent stuff.
***** Perfection. See it twice.
Copyright REVIEW. This review was written for REVIEW
<,">http://www.silkweb.com.sg/dmedia/review/>, an online, fortnightly
Singaporean rag curiously known to insiders as Giddiness Clinic. Visit us
for a free consultation on that ringing noise in your penguin's ear.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:layout_marginTop="@dimen/device_warning_item_padding">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/device_warning_item_padding"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_fpga_fault_label"/>

            <TextView
                android:id="@+id/warning_fpga_fault"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_fpga_communication_outTime_label"/>

            <TextView
                android:id="@+id/warning_fpga_communication_outTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_fpga_communication_error_label"/>

            <TextView
                android:id="@+id/warning_fpga_communication_error"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/device_warning_item_padding"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_storage_data_fault_label"/>

            <TextView
                android:id="@+id/warning_storage_data_fault"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_system_over_voltage_label"/>

            <TextView
                android:id="@+id/warning_system_over_voltage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_system_under_voltage_label"/>

            <TextView
                android:id="@+id/warning_system_under_voltage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/device_warning_item_padding"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_three_phase_voltage_unbalance_label"/>

            <TextView
                android:id="@+id/warning_three_phase_voltage_unbalance"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_output_quick_break_label"/>

            <TextView
                android:id="@+id/warning_output_quick_break"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_output_over_current_label"/>

            <TextView
                android:id="@+id/warning_output_over_current"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/device_warning_item_padding"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_unit_ac_high_voltage_label"/>

            <TextView
                android:id="@+id/warning_unit_ac_high_voltage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_temprature_igbt_high_label"/>

            <TextView
                android:id="@+id/warning_temprature_igbt_high"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_system_power_down_label"/>

            <TextView
                android:id="@+id/warning_system_power_down"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/device_warning_item_padding"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_close_resistance_fault_label"/>

            <TextView
                android:id="@+id/warning_close_resistance_fault"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_close_contactor_fault_label"/>

            <TextView
                android:id="@+id/warning_close_contactor_fault"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_open_resistance_fault_label"/>

            <TextView
                android:id="@+id/warning_open_resistance_fault"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/device_warning_item_padding"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_open_contactor_fault_label"/>

            <TextView
                android:id="@+id/warning_open_contactor_fault"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:paddingLeft="@dimen/device_warning_item_padding"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="left"
                android:textSize="@dimen/device_warning_item_label_font_size"
                android:textColor="@android:color/black"
                android:text="@string/device_warning_time_label"/>

            <TextView
                android:id="@+id/warning_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_gravity="center_vertical"
                android:gravity="center"
                android:textSize="@dimen/device_warning_item_font_size"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>


text:
<?php

/**
 * Register the classes
 */
ClassLoader::addClasses(array
(
    // Classes
    'CrudListView' => 'system/modules/crud/classes/CrudListView.php',

    // Modules
    'ModuleCrudList' => 'system/modules/crud/modules/ModuleCrudList.php',
));

/**
 * Register the templates
 */
TemplateLoader::addFiles(array
(
    'mod_crud_list_default' => 'system/modules/crud/templates/Modules',
));


text:
package org.zstack.compute.vm;

import org.zstack.header.vm.hooks.*;

import java.util.function.Supplier;

public interface VmInstanceHookManager {
    void hookStartEvent(Supplier<VmInstanceStartHook> supplier);

    void hookStopEvent(Supplier<VmInstanceStopHook> supplier);

    void hookRebootEvent(Supplier<VmInstanceRebootHook> supplier);

    void hookDestroyEvent(Supplier<VmInstanceDestroyHook> supplier);

    void hookCreateEvent(Supplier<VmInstanceCreateHook> supplier);
}


text:
using System.IO;

namespace Gaucho.Forms.Core.FileSystem {
    public enum StorageLocation {
        AppResource,
        Documents,
        Cache
    }

    public enum FileMode {
        Read,
        Write,
        CreateNew
    }

    public interface IFileSystem {
        Stream OpenFile(string filename, StorageLocation storageLocation = StorageLocation.Documents, FileMode fileMode = FileMode.Read);
        void DeleteFile(string filename, StorageLocation storageLocation = StorageLocation.Documents);
        bool FileExists(string filename, StorageLocation storageLocation = StorageLocation.Documents);
    }
}


text:
MongoMapper.connection = Mongo::Connection.new('209.20.80.96', 27017) #, :logger => Rails.logger)
MongoMapper.database = "connectme-#{Rails.env}"

User.ensure_index(:fb_id)

if defined?(PhusionPassenger)
   PhusionPassenger.on_event(:starting_worker_process) do |forked|
     MongoMapper.connection.connect if forked
   end
end


text:
var SwatchFieldView = Backbone.View.extend({

  initialize: function() {
    this.$swatch = this.$(".swatch-field-swatch");
    this.$input = this.$("input");
    this.refreshPreview();
  },

  colorRegex: /^(?:[0-9a-f]{3})(?:[0-9a-f]{3})?$/i,

  parseColor: function(color) {
    color = color.replace("#","");
    if (!!this.colorRegex.exec(color)) {
      return color.toUpperCase();
    }
    else {
      return false;
    }
  },

  refreshPreview: function() {
    var parsedColor = this.parseColor($.trim(this.$input.val()));
    if (!!parsedColor) {
      this.$swatch.attr("style", "background:#" + parsedColor + " !important");
      this.$swatch.addClass("-active");
    }
    else {
      this.$swatch.attr("style", "");
      this.$swatch.removeClass("-active");
    }
  },

  validateSelf: function() {
    var inputValue = $.trim(this.$input.val());
    var parsedColor = this.parseColor(inputValue);
    if (!parsedColor && inputValue !== "") {
      this.$el.addClass("field_with_errors");
    }
  },

  clearError: function() {
    this.$el.removeClass("field_with_errors");
  },

  events: {
    "keyup": "refreshPreview",
    "blur input": "validateSelf",
    "focus input": "clearError",
    "change input": function(event) {
      this.refreshPreview(event);
      this.validateSelf(event);
    }
  }

});

FormOrchestrator.register(".swatch-field", "SwatchFieldView");


text:
package org.traccar.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.traccar.BaseFrameDecoder;

public class Tk103FrameDecoder extends BaseFrameDecoder {

    @Override
    protected Object decode(
            ChannelHandlerContext ctx, Channel channel, ByteBuf buf) throws Exception {

        if (buf.readableBytes() < 2) {
            return null;
        }

        int frameStartIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '(');
        if (frameStartIndex == -1) {
            buf.clear();
            return null;
        }

        int frameEndIndex, freeTextSymbolCounter;
        for (frameEndIndex = frameStartIndex, freeTextSymbolCounter = 0;; frameEndIndex++) {
            int freeTextIndex = frameEndIndex;
            frameEndIndex = buf.indexOf(frameEndIndex, buf.writerIndex(), (byte) ')');
            if (frameEndIndex == -1) {
                break;
            }
            for (;; freeTextIndex++, freeTextSymbolCounter++) {
                freeTextIndex = buf.indexOf(freeTextIndex, frameEndIndex, (byte) '$');
                if (freeTextIndex == -1 || freeTextIndex >= frameEndIndex) {
                    break;
                }
            }
            if (freeTextSymbolCounter % 2 == 0) {
                break;
            }
        }

        if (frameEndIndex == -1) {
            while (buf.readableBytes() > 1024) {
                int discardUntilIndex = buf.indexOf(buf.readerIndex() + 1, buf.writerIndex(), (byte) '(');
                if (discardUntilIndex == -1) {
                    buf.clear();
                } else {
                    buf.readerIndex(discardUntilIndex);
                }
            }
            return null;
        }

        buf.readerIndex(frameStartIndex);

        return buf.readRetainedSlice(frameEndIndex + 1 - frameStartIndex);
    }

}


text:
using System;

public class GenericList<T>
    where T : IComparable
{
    private T[] array;
    private int index;

    public GenericList(int size)
    {
        array = new T[size];
        this.index = 0;
    }
    public void Add(T element)
    {
        if (this.index == this.array.Length - 1)
        {
            Expand();
        }
        array[index] = element;
        this.index++;
    }
    public T this[int position]
    {
        get
        {
            return this.array[position];
        }
        set
        {
            this.array[position] = value;
        }
    }
    public void RemoveAt(int position)
    {
        if (position < 0 || position > index)
        {
            Console.WriteLine("Doesn't exist !");
        }
        else
        {
            T[] result = new T[this.array.Length - 1];
            this.index--;
            Array.Copy(this.array, 0, result, 0, position);
            Array.Copy(this.array, position + 1, result, 0, this.array.Length - 1 - position);
            this.array = result;
        }
    }
    public void InsertAt(T element, int position)
    {
        if (position == this.array.Length - 1)
        {
            Expand();
        }

        T[] result = new T[this.array.Length + 1];
        this.index++;
        Array.Copy(this.array, 0, result, 0, position);
        result[position] = element;
        Array.Copy(this.array, position, result, position + 1, this.array.Length - position);
        this.array = result;
    }
    public void Clear()
    {
        int sizeTemp = this.array.Length;
        array = new T[sizeTemp];
        index = 0;
    }
    public int Find(T element)
    {
        return Array.IndexOf(this.array, element);
    }
    public override string ToString()
    {
        string result = String.Empty;
        for (int i = 0; i < this.index; i++)
        {
            result += this.array[i] + " ";
        }
        return result;
    }

    public void Expand()
    {
        T[] result = new T[this.array.Length * 2];
        Array.Copy(this.array, result, this.array.Length);
        this.array = result;
    }
    public T Min()
    {
        T min = this.array[0];
        for (int i = 0; i < index; i++)
        {
            if (min.CompareTo(this.array[i]) > 0)
            {
                min = this.array[i];
            }
        }

        return min;
    }
    public T Max()
    {
        T max = this.array[0];
        for (int i = 0; i < index; i++)
        {
            if (max.CompareTo(this.array[i]) < 0)
            {
                max = this.array[i];
            }
        }

        return max;
    }
}

public class Test
{
    static void Main()
    {
        GenericList<int> array = new GenericList<int>(5);
        array.Add(1);
        array.InsertAt(2, 1);
        array.RemoveAt(1);
        array.Add(10);
        Console.WriteLine(array.ToString());
        Console.WriteLine(array.Min());
        Console.WriteLine(array.Max());
        Console.WriteLine();
        array.Add(10);
        array.Add(10);
        array.Add(10);
        array.Add(10);
        array.Add(10);
        Console.WriteLine(array.ToString());
    }
}


text:
[![Build status](https://ci.appveyor.com/api/projects/status/09u2w3jv56qv2suj?svg=true)](https://ci.appveyor.com/project/narkhedegs/pipe)
# Pipe

Pipe streams in .NET without deadlocks.

### Purpose

Pipe helps to "pipe" the streams in .NET without deadlocks.

### Requirements

- .NET 4.5 and above

# Installation

Pipe is available at [Nuget](https://www.nuget.org/packages/Pipe/) and can be installed as a package using VisualStudio NuGet package manager or via the NuGet command line:
> Install-Package Pipe

### Usage

```cs
using Narkhedegs;
```

```cs
var pipe = new Pipe();

// StreamReader could be output of any process. for ex. StandardOutput of System.Diagnostics.Process
var processStream = streamReader.BaseStream;

try
{
	int bytesRead;

	while(bytesRead = await processStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
    {
    	await pipe.InputStream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
    }
}
finally
{
	processStream.Close();
    pipe.InputStream.Close();
}
```

### Credits

All credits goes to [madelson](https://github.com/madelson). This project is just a small part of [MedallionShell](https://github.com/madelson/MedallionShell) published as a separate NuGet package.

### License

MIT © [narkhedegs](https://github.com/narkhedegs)


text:
package br.furb.packing;

import br.furb.common.Point;
import br.furb.common.Transform;
import br.furb.packing.NoFitPolygon.TouchingEdgeVertex;

public class Line {

	Point start;
	Point end;

	public Line(Point start, Point end) {
		this.start = start;
		this.end = end;
	}

	public Point getStart() {
		return start;
	}

	public Point getEnd() {
		return end;
	}

	public TouchingEdgeVertex compare(Line line) {
		if (start.equals(line.start)) {
			return TouchingEdgeVertex.START_START;
		}
		if (start.equals(line.end)) {
			return TouchingEdgeVertex.START_END;
		}
		if (end.equals(line.start)) {
			return TouchingEdgeVertex.END_START;
		}
		if (end.equals(line.end)) {
			return TouchingEdgeVertex.END_END;
		}
		throw new IllegalStateException("Nenhum ponto é igual.");
	}

	public boolean intersectsLine(Point p1, Point p2) {
		return linesIntersect(p1, p2, start, end);
	}

	/**
	 * Returns an indicator of where the specified point {@code (px,py)} lies with respect to this line segment. See the method comments of {@link #relativeCCW(double, double, double, double, double, double)} to interpret the return value.
	 *
	 * @param px
	 *            the X coordinate of the specified point to be compared with this Line2D
	 * @param py
	 *            the Y coordinate of the specified point to be compared with this Line2D
	 * @return an integer that indicates the position of the specified coordinates with respect to this Line2D
	 * @see #relativeCCW(double, double, double, double, double, double)
	 * @since 1.2
	 */
	public int relativeCCW(double px, double py) {
		return relativeCCW(start.x, start.y, end.x, end.y, px, py);
	}

	/**
	 * Tests if the line segment from {@code (x1,y1)} to {@code (x2,y2)} intersects the line segment from {@code (x3,y3)} to {@code (x4,y4)}.
	 *
	 * @param x1
	 *            the X coordinate of the start point of the first specified line segment
	 * @param y1
	 *            the Y coordinate of the start point of the first specified line segment
	 * @param x2
	 *            the X coordinate of the end point of the first specified line segment
	 * @param y2
	 *            the Y coordinate of the end point of the first specified line segment
	 * @param x3
	 *            the X coordinate of the start point of the second specified line segment
	 * @param y3
	 *            the Y coordinate of the start point of the second specified line segment
	 * @param x4
	 *            the X coordinate of the end point of the second specified line segment
	 * @param y4
	 *            the Y coordinate of the end point of the second specified line segment
	 * @return true if the first specified line segment and the second specified line segment intersect each other; false otherwise.
	 * @since 1.2
	 */
	public static boolean linesIntersect(Point p1, Point p2, Point p3, Point p4) {
		return ((relativeCCW(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y) * //
				relativeCCW(p1.x, p1.y, p2.x, p2.y, p4.x, p4.y) <= 0) && //
		(relativeCCW(p3.x, p3.y, p4.x, p4.y, p1.x, p1.y) * //
				relativeCCW(p3.x, p3.y, p4.x, p4.y, p2.x, p2.y) <= 0));
	}

	/**
	 * Returns an indicator of where the specified point {@code (px,py)} lies with respect to the line segment from {@code (x1,y1)} to {@code (x2,y2)}. The return value can be either 1, -1, or 0 and indicates in which direction the specified line must pivot around its first end point, {@code (x1,y1)}, in order to point at the specified point {@code (px,py)}.
	 *

	 * A return value of 1 indicates that the line segment must turn in the direction that takes the positive X axis towards the negative Y axis. In the default coordinate system used by Java 2D, this direction is counterclockwise.
	 *

	 * A return value of -1 indicates that the line segment must turn in the direction that takes the positive X axis towards the positive Y axis. In the default coordinate system, this direction is clockwise.
	 *

	 * A return value of 0 indicates that the point lies exactly on the line segment. Note that an indicator value of 0 is rare and not useful for determining colinearity because of floating point rounding issues.
	 *

	 * If the point is colinear with the line segment, but not between the end points, then the value will be -1 if the point lies "beyond {@code (x1,y1)}" or 1 if the point lies "beyond {@code (x2,y2)}".
	 *
	 * @param x1
	 *            the X coordinate of the start point of the specified line segment
	 * @param y1
	 *            the Y coordinate of the start point of the specified line segment
	 * @param x2
	 *            the X coordinate of the end point of the specified line segment
	 * @param y2
	 *            the Y coordinate of the end point of the specified line segment
	 * @param px
	 *            the X coordinate of the specified point to be compared with the specified line segment
	 * @param py
	 *            the Y coordinate of the specified point to be compared with the specified line segment
	 * @return an integer that indicates the position of the third specified coordinates with respect to the line segment formed by the first two specified coordinates.
	 * @since 1.2
	 */
	public static int relativeCCW(double x1, double y1, double x2, double y2, double px, double py) {
		x2 -= x1;
		y2 -= y1;
		px -= x1;
		py -= y1;
		if (Math.abs(x2) < Transform.THRESHOLD2) {
			x2 = 0;
		}
		if (Math.abs(y2) < Transform.THRESHOLD2) {
			y2 = 0;
		}
		if (Math.abs(px) < Transform.THRESHOLD2) {
			px = 0;
		}
		if (Math.abs(py) < Transform.THRESHOLD2) {
			py = 0;
		}
		double ccw = px * y2 - py * x2;
		// equivalente a ccw == 0.0
		if (Math.abs(ccw) < Transform.THRESHOLD) {
			// The point is colinear, classify based on which side of
			// the segment the point falls on. We can calculate a
			// relative value using the projection of px,py onto the
			// segment - a negative value indicates the point projects
			// outside of the segment in the direction of the particular
			// endpoint used as the origin for the projection.
			ccw = px * x2 + py * y2;
			if (ccw > 0.0) {
				// Reverse the projection to be relative to the original x2,y2
				// x2 and y2 are simply negated.
				// px and py need to have (x2 - x1) or (y2 - y1) subtracted
				// from them (based on the original values)
				// Since we really want to get a positive answer when the
				// point is "beyond (x2,y2)", then we want to calculate
				// the inverse anyway - thus we leave x2 & y2 negated.
				px -= x2;
				py -= y2;
				ccw = px * x2 + py * y2;
				if (ccw < 0.0) {
					ccw = 0.0;
				}
			}
		}
		return (ccw < 0.0) ? -1 : ((ccw > 0.0) ? 1 : 0);
	}

	/**
	 * Returns the distance from a point to this line segment. The distance measured is the distance between the specified point and the closest point between the current line's end points. If the specified point intersects the line segment in between the end points, this method returns 0.0.
	 *
	 * @param px
	 *            the X coordinate of the specified point being measured against this line segment
	 * @param py
	 *            the Y coordinate of the specified point being measured against this line segment
	 * @return a double value that is the distance from the specified point to the current line segment.
	 * @see #ptLineDist(double, double)
	 * @since 1.2
	 */
	public double ptSegDist(double px, double py) {
		return ptSegDist(start.x, start.y, end.x, end.y, px, py);
	}

	/**
	 * Returns the distance from a point to a line segment. The distance measured is the distance between the specified point and the closest point between the specified end points. If the specified point intersects the line segment in between the end points, this method returns 0.0.
	 *
	 * @param x1
	 *            the X coordinate of the start point of the specified line segment
	 * @param y1
	 *            the Y coordinate of the start point of the specified line segment
	 * @param x2
	 *            the X coordinate of the end point of the specified line segment
	 * @param y2
	 *            the Y coordinate of the end point of the specified line segment
	 * @param px
	 *            the X coordinate of the specified point being measured against the specified line segment
	 * @param py
	 *            the Y coordinate of the specified point being measured against the specified line segment
	 * @return a double value that is the distance from the specified point to the specified line segment.
	 * @see #ptLineDist(double, double, double, double, double, double)
	 * @since 1.2
	 */
	public static double ptSegDist(double x1, double y1, double x2, double y2, double px, double py) {
		return Math.sqrt(ptSegDistSq(x1, y1, x2, y2, px, py));
	}

	/**
	 * Returns the square of the distance from a point to a line segment. The distance measured is the distance between the specified point and the closest point between the specified end points. If the specified point intersects the line segment in between the end points, this method returns 0.0.
	 *
	 * @param x1
	 *            the X coordinate of the start point of the specified line segment
	 * @param y1
	 *            the Y coordinate of the start point of the specified line segment
	 * @param x2
	 *            the X coordinate of the end point of the specified line segment
	 * @param y2
	 *            the Y coordinate of the end point of the specified line segment
	 * @param px
	 *            the X coordinate of the specified point being measured against the specified line segment
	 * @param py
	 *            the Y coordinate of the specified point being measured against the specified line segment
	 * @return a double value that is the square of the distance from the specified point to the specified line segment.
	 * @see #ptLineDistSq(double, double, double, double, double, double)
	 * @since 1.2
	 */
	public static double ptSegDistSq(double x1, double y1, double x2, double y2, double px, double py) {
		// Adjust vectors relative to x1,y1
		// x2,y2 becomes relative vector from x1,y1 to end of segment
		x2 -= x1;
		y2 -= y1;
		// px,py becomes relative vector from x1,y1 to test point
		px -= x1;
		py -= y1;
		double dotprod = px * x2 + py * y2;
		double projlenSq;
		if (dotprod <= 0.0) {
			// px,py is on the side of x1,y1 away from x2,y2
			// distance to segment is length of px,py vector
			// "length of its (clipped) projection" is now 0.0
			projlenSq = 0.0;
		} else {
			// switch to backwards vectors relative to x2,y2
			// x2,y2 are already the negative of x1,y1=>x2,y2
			// to get px,py to be the negative of px,py=>x2,y2
			// the dot product of two negated vectors is the same
			// as the dot product of the two normal vectors
			px = x2 - px;
			py = y2 - py;
			dotprod = px * x2 + py * y2;
			if (dotprod <= 0.0) {
				// px,py is on the side of x2,y2 away from x1,y1
				// distance to segment is length of (backwards) px,py vector
				// "length of its (clipped) projection" is now 0.0
				projlenSq = 0.0;
			} else {
				// px,py is between x1,y1 and x2,y2
				// dotprod is the length of the px,py vector
				// projected on the x2,y2=>x1,y1 vector times the
				// length of the x2,y2=>x1,y1 vector
				projlenSq = dotprod * dotprod / (x2 * x2 + y2 * y2);
			}
		}
		// Distance to line is now the length of the relative point
		// vector minus the length of its projection onto the line
		// (which is zero if the projection falls outside the range
		// of the line segment).
		double lenSq = px * px + py * py - projlenSq;
		if (lenSq < 0) {
			lenSq = 0;
		}
		// customização
		if (Math.abs(lenSq) <= Transform.THRESHOLD) {
			lenSq = 0;
		}
		return lenSq;
	}

	@Override
	public String toString() {
		return "Line > start=" + start + " - end=" + end;
	}
}