text:
layout: model
title: Extract relations between problem, treatment and test entities (ReDL)
author: John Snow Labs
name: redl_clinical_biobert
date: 2021-02-04
task: Relation Extraction
language: en
edition: Healthcare NLP 2.7.3
spark_version: 2.4
tags: [licensed, clinical, en, relation_extraction]
supported: true
annotator: RelationExtractionDLModel
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

Extract relations like `TrIP` : a certain treatment has improved a medical problem and 7 other such relations between problem, treatment and test entities.

## Predicted Entities

`PIP`, `TeCP`, `TeRP`, `TrAP`, `TrCP`, `TrIP`, `TrNAP`, `TrWP`

{:.btn-box}
[Live Demo](https://demo.johnsnowlabs.com/healthcare/RE_CLINICAL/){:.button.button-orange}
[Open in Colab](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Healthcare/10.Clinical_Relation_Extraction.ipynb){:.button.button-orange.button-orange-trans.co.button-icon}
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/clinical/models/redl_clinical_biobert_en_2.7.3_2.4_1612443963755.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
...
documenter = DocumentAssembler()\
.setInputCol("text")\
.setOutputCol("document")

sentencer = SentenceDetector()\
.setInputCols(["document"])\
.setOutputCol("sentences")

tokenizer = sparknlp.annotators.Tokenizer()\
.setInputCols(["sentences"])\
.setOutputCol("tokens")

pos_tagger = PerceptronModel()\
.pretrained("pos_clinical", "en", "clinical/models") \
.setInputCols(["sentences", "tokens"])\
.setOutputCol("pos_tags")

words_embedder = WordEmbeddingsModel() \
.pretrained("embeddings_clinical", "en", "clinical/models") \
.setInputCols(["sentences", "tokens"]) \
.setOutputCol("embeddings")

ner_tagger = MedicalNerModel.pretrained("ner_clinical", "en", "clinical/models")\
.setInputCols("sentences", "tokens", "embeddings")\
.setOutputCol("ner_tags")

ner_converter = NerConverter() \
.setInputCols(["sentences", "tokens", "ner_tags"]) \
.setOutputCol("ner_chunks")

dependency_parser = DependencyParserModel() \
.pretrained("dependency_conllu", "en") \
.setInputCols(["sentences", "pos_tags", "tokens"]) \
.setOutputCol("dependencies")

# Set a filter on pairs of named entities which will be treated as relation candidates
re_ner_chunk_filter = RENerChunksFilter() \
.setInputCols(["ner_chunks", "dependencies"])\
.setMaxSyntacticDistance(10)\
.setOutputCol("re_ner_chunks")\
.setRelationPairs(['SYMPTOM-EXTERNAL_BODY_PART_OR_REGION'])

# The dataset this model is trained to is sentence-wise.
# This model can also be trained on document-level relations - in which case, while predicting, use "document" instead of "sentence" as input.
re_model = RelationExtractionDLModel()\
.pretrained('redl_clinical_biobert', 'en', "clinical/models") \
.setPredictionThreshold(0.5)\
.setInputCols(["re_ner_chunks", "sentences"]) \
.setOutputCol("relations")

pipeline = Pipeline(stages=[documenter, sentencer, tokenizer, pos_tagger, words_embedder, ner_tagger, ner_converter, dependency_parser, re_ner_chunk_filter, re_model])

text ="""A 28-year-old female with a history of gestational diabetes mellitus diagnosed eight years prior to presentation and subsequent type two diabetes mellitus ( T2DM ), one prior episode of HTG-induced pancreatitis three years prior to presentation,  associated with an acute hepatitis , and obesity with a body mass index ( BMI ) of 33.5 kg/m2 , presented with a one-week history of polyuria , polydipsia , poor appetite , and vomiting .
"""
data = spark.createDataFrame([[text]]).toDF("text")
p_model = pipeline.fit(data)
result = p_model.transform(data)
```

```scala
...
val documenter = DocumentAssembler()
.setInputCol("text")
.setOutputCol("document")

val sentencer = SentenceDetector()
.setInputCols("document")
.setOutputCol("sentences")

val tokenizer = sparknlp.annotators.Tokenizer()
.setInputCols("sentences")
.setOutputCol("tokens")

val pos_tagger = PerceptronModel()
.pretrained("pos_clinical", "en", "clinical/models")
.setInputCols(Array("sentences", "tokens"))
.setOutputCol("pos_tags")

val words_embedder = WordEmbeddingsModel()
.pretrained("embeddings_clinical", "en", "clinical/models")
.setInputCols(Array("sentences", "tokens"))
.setOutputCol("embeddings")

val ner_tagger = MedicalNerModel.pretrained("ner_clinical", "en", "clinical/models")
.setInputCols(Array("sentences", "tokens", "embeddings"))
.setOutputCol("ner_tags")

val ner_converter = NerConverter()
.setInputCols(Array("sentences", "tokens", "ner_tags"))
.setOutputCol("ner_chunks")

val dependency_parser = DependencyParserModel()
.pretrained("dependency_conllu", "en")
.setInputCols(Array("sentences", "pos_tags", "tokens"))
.setOutputCol("dependencies")

// Set a filter on pairs of named entities which will be treated as relation candidates
val re_ner_chunk_filter = RENerChunksFilter()
.setInputCols(Array("ner_chunks", "dependencies"))
.setMaxSyntacticDistance(10)
.setOutputCol("re_ner_chunks")
.setRelationPairs(Array("SYMPTOM-EXTERNAL_BODY_PART_OR_REGION"))

// The dataset this model is trained to is sentence-wise.
// This model can also be trained on document-level relations - in which case, while predicting, use "document" instead of "sentence" as input.
val re_model = RelationExtractionDLModel()
.pretrained("redl_clinical_biobert", "en", "clinical/models")
.setPredictionThreshold(0.5)
.setInputCols(Array("re_ner_chunks", "sentences"))
.setOutputCol("relations")

val pipeline = new Pipeline().setStages(Array(documenter, sentencer, tokenizer, pos_tagger, words_embedder, ner_tagger, ner_converter, dependency_parser, re_ner_chunk_filter, re_model))

val data = Seq("A 28-year-old female with a history of gestational diabetes mellitus diagnosed eight years prior to presentation and subsequent type two diabetes mellitus ( T2DM ), one prior episode of HTG-induced pancreatitis three years prior to presentation,  associated with an acute hepatitis , and obesity with a body mass index ( BMI ) of 33.5 kg/m2 , presented with a one-week history of polyuria , polydipsia , poor appetite , and vomiting .").toDF("text")
val result = pipeline.fit(data).transform(data)
```

{:.nlu-block}
```python
import nlu
nlu.load("en.relation.clinical").predict("""A 28-year-old female with a history of gestational diabetes mellitus diagnosed eight years prior to presentation and subsequent type two diabetes mellitus ( T2DM ), one prior episode of HTG-induced pancreatitis three years prior to presentation,  associated with an acute hepatitis , and obesity with a body mass index ( BMI ) of 33.5 kg/m2 , presented with a one-week history of polyuria , polydipsia , poor appetite , and vomiting .
""")
```

</div>

## Results

```bash
|    | relation   | entity1   |   entity1_begin |   entity1_end | chunk1                                | entity2   |   entity2_begin |   entity2_end | chunk2                   |   confidence |
|---:|:-----------|:----------|----------------:|--------------:|:--------------------------------------|:----------|----------------:|--------------:|:-------------------------|-------------:|
|  0 | PIP        | PROBLEM   |              39 |            67 | gestational diabetes mellitus         | PROBLEM   |             157 |           160 | T2DM                     |     0.763447 |
|  1 | PIP        | PROBLEM   |              39 |            67 | gestational diabetes mellitus         | PROBLEM   |             289 |           295 | obesity                  |     0.682246 |
|  2 | PIP        | PROBLEM   |             117 |           153 | subsequent type two diabetes mellitus | PROBLEM   |             187 |           210 | HTG-induced pancreatitis |     0.610396 |
|  3 | PIP        | PROBLEM   |             117 |           153 | subsequent type two diabetes mellitus | PROBLEM   |             264 |           281 | an acute hepatitis       |     0.726894 |
```

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|redl_clinical_biobert|
|Compatibility:|Healthcare NLP 2.7.3+|
|License:|Licensed|
|Edition:|Official|
|Language:|en|

## Data Source

Trained on 2010 i2b2 relation challenge.

## Benchmarking

```bash
Relation           Recall Precision        F1   Support
PIP                 0.859     0.878     0.869      1435
TeCP                0.629     0.782     0.697       337
TeRP                0.903     0.929     0.916      2034
TrAP                0.872     0.866     0.869      1693
TrCP                0.641     0.677     0.659       340
TrIP                0.517     0.796     0.627       151
TrNAP               0.402     0.672     0.503       112
TrWP                0.257     0.824     0.392       109
Avg.                0.635     0.803     0.691
```

redpajama_set_name: RedPajamaGithub


text:
package rsp.engine

import collection.mutable.ArrayBuffer
import concurrent.duration._
import akka.actor._
import akka.event.Logging
import rsp.data._
import scala.util.Random
import rsp.data.RdfTools._
import rsp.data.RdfStream._
import scala.concurrent.Future
import scala.language.postfixOps

trait Feed{
  val stream:RdfStream

}

abstract class RspFeed(val stream:RdfStream,rate:Int) extends Feed with Actor{
  val log = Logging(context.system, this)
  private val subscribed=new ArrayBuffer[ActorRef]
  private implicit val ctx=context.dispatcher
  var launcher:Cancellable=null

  def produce:Future[Seq[Graph]]

  protected def dispatch(g:Graph)={
    //println("dispatching to "+subscribed.size)
    subscribed.foreach{
      s=>s ! g
  }}

  override def preStart()={
    log.info(s"RspFeed path: ${self.path}")
  }

  def receive={
    case Subscribe(a)=>
      subscribed+=a
    case Unsubscribe(a)=>
    case Init=>
      println("Init feeder "+rate)
      launcher=context.system.scheduler.schedule(0 seconds, rate milliseconds){
        produce.map{g=>
          println("to dispatch")
          g.foreach(dispatch)

        }

      }
    case End=>
      launcher.cancel
      subscribed.foreach{
        s=>s ! End
      }
  }
}

case class End()
case class Init()
case class Subscribe(actor:ActorRef)
case class Unsubscribe(actor:ActorRef)

class RandomRdfStream(override val name:Iri) extends RdfStream{
  import concurrent.ExecutionContext.Implicits.global
  def data={
    def s:Seq[Triple]={
      (1 to 10).map(i=>Triple("a","p",Random.nextDouble.toString)).toSeq
    }
    val triples=(1 to 1).flatMap{i=>s}

    val g=Graph(triples:_*)
    Future(Seq(g))
  }
}

class RandomRspFeed(n:String,rate:Int) extends RspFeed(new RandomRdfStream(n),rate){
  import concurrent.ExecutionContext.Implicits.global
  override def produce={
    def s:Seq[Triple]={
      (1 to 10).map(i=>Triple("a","p",Random.nextDouble.toString)).toSeq
    }
    val triples=(1 to 1).flatMap{i=>s}

    val g=Graph(triples:_*)
    Future(Seq(g))
  }
}


text:
.modal-footer > .closed{
    background-color: #30d50d;
    border: none;
    color: white;
}

.modal-footer > .closed:hover{
    background-color: #2e8e08;
    border: none;
    color: white;
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/fonts.css">

1

2
3

4

3

4

5

6

Slide2

Slide3

Previous

MENU

Next


text:
<?php
defined('BASEPATH') or exit('Not open Scripting');

/**
 * Description of Pmail
 *
 * @author ASUS
 */
class Pmail {

     var $CI;
     public function __construct() {
         require_once('PHPMailer/PHPMailerAutoload.php');
         $this->CI =& get_instance();
     }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
N. Z. Jl Bot. 21(3): 263 (1983)

#### Original name
Stictis laciniata P.R. Johnst.

### Remarks
null


text:
package org.jfree.chart.plot;

import java.awt.geom.Point2D;

import org.jfree.chart.renderer.category.CategoryItemRenderer;

/**
 * Represents state information for the crosshairs in a {@link CategoryPlot}.
 * An instance of this class is created at the start of the rendering process,
 * and updated as each data item is rendered.  At the end of the rendering
 * process, this class holds the row key, column key and value for the
 * crosshair location.
 *
 * @since 1.0.11
 */
public class CategoryCrosshairState extends CrosshairState {

    /**
     * The row key for the crosshair point.
     */
    private Comparable rowKey;

    /**
     * The column key for the crosshair point.
     */
    private Comparable columnKey;

    /**
     * Creates a new instance.
     */
    public CategoryCrosshairState() {
        this.rowKey = null;
        this.columnKey = null;
    }

    /**
     * Returns the row key.
     *
     * @return The row key.
     */
    public Comparable getRowKey() {
        return this.rowKey;
    }

    /**
     * Sets the row key.
     *
     * @param key  the row key.
     */
    public void setRowKey(Comparable key) {
        this.rowKey = key;
    }

    /**
     * Returns the column key.
     *
     * @return The column key.
     */
    public Comparable getColumnKey() {
        return this.columnKey;
    }

    /**
     * Sets the column key.
     *
     * @param key  the key.
     */
    public void setColumnKey(Comparable key) {
        this.columnKey = key;
    }

    /**
     * Evaluates a data point from a {@link CategoryItemRenderer} and if it is
     * the closest to the anchor point it becomes the new crosshair point.
     *
     * @param rowKey  the row key.
     * @param columnKey  the column key.
     * @param value  y coordinate (measured against the range axis).
     * @param datasetIndex  the dataset index for this point.
     * @param transX  x translated into Java2D space.
     * @param transY  y translated into Java2D space.
     * @param orientation  the plot orientation.
     */
    public void updateCrosshairPoint(Comparable rowKey, Comparable columnKey,
            double value, int datasetIndex, double transX, double transY,
            PlotOrientation orientation) {

        Point2D anchor = getAnchor();
        if (anchor != null) {
            double xx = anchor.getX();
            double yy = anchor.getY();
            if (orientation == PlotOrientation.HORIZONTAL) {
                double temp = yy;
                yy = xx;
                xx = temp;
            }
            double d = (transX - xx) * (transX - xx)
                    + (transY - yy) * (transY - yy);

            if (d < getCrosshairDistance()) {
                this.rowKey = rowKey;
                this.columnKey = columnKey;
                setCrosshairY(value);
                setDatasetIndex(datasetIndex);
                setCrosshairDistance(d);
            }
        }

    }

    /**
     * Updates only the crosshair row and column keys (this is for the case
     * where the range crosshair does NOT lock onto the nearest data value).
     *
     * @param rowKey  the row key.
     * @param columnKey  the column key.
     * @param datasetIndex  the dataset axis index.
     * @param transX  the translated x-value.
     * @param orientation  the plot orientation.
     */
    public void updateCrosshairX(Comparable rowKey, Comparable columnKey,
            int datasetIndex, double transX, PlotOrientation orientation) {

        Point2D anchor = getAnchor();
        if (anchor != null) {
            double anchorX = anchor.getX();
            if (orientation == PlotOrientation.HORIZONTAL) {
                anchorX = anchor.getY();
            }
            double d = Math.abs(transX - anchorX);
            if (d < getCrosshairDistance()) {
                this.rowKey = rowKey;
                this.columnKey = columnKey;
                setDatasetIndex(datasetIndex);
                setCrosshairDistance(d);
            }
        }

    }

}


text:
@interface JSQMessagesUIColorTests : XCTestCase
@end

@implementation JSQMessagesUIColorTests

- (void)setUp
{
    [super setUp];
}

- (void)tearDown
{
    [super tearDown];
}

- (void)testGreenColor
{
    CGFloat h, s, b, a;

    UIColor *green = [UIColor jsq_messageBubbleGreenColor];
    XCTAssertNotNil(green, @"Color should not be nil");

    [green getHue:&h saturation:&s brightness:&b alpha:&a];
    UIColor *copyGreen = [UIColor colorWithHue:h saturation:s brightness:b alpha:a];
    XCTAssertEqualObjects(green, copyGreen, @"Colors should be equal");
}

- (void)testBlueColor
{
    CGFloat h, s, b, a;

    UIColor *blue = [UIColor jsq_messageBubbleBlueColor];
    XCTAssertNotNil(blue, @"Color should not be nil");

    [blue getHue:&h saturation:&s brightness:&b alpha:&a];
    UIColor *copyBlue = [UIColor colorWithHue:h saturation:s brightness:b alpha:a];
    XCTAssertEqualObjects(blue, copyBlue, @"Colors should be equal");
}

- (void)testGrayColor
{
    CGFloat h, s, b, a;

    UIColor *gray = [UIColor jsq_messageBubbleLightGrayColor];
    XCTAssertNotNil(gray, @"Color should not be nil");

    [gray getHue:&h saturation:&s brightness:&b alpha:&a];
    UIColor *copyGray = [UIColor colorWithHue:h saturation:s brightness:b alpha:a];
    XCTAssertEqualObjects(gray, copyGray, @"Colors should be equal");
}

- (void)testDarkeningColors
{
    CGFloat r = 0.89f, g = 0.34f, b = 0.67f, a = 1.0f;

    CGFloat darkeningValue = 0.12f;

    UIColor *color = [UIColor colorWithRed:r green:g blue:b alpha:a];
    UIColor *darkColor = [color jsq_colorByDarkeningColorWithValue:darkeningValue];

    CGFloat dr, dg, db, da;
    [darkColor getRed:&dr green:&dg blue:&db alpha:&da];
    XCTAssertEqual(dr, r - darkeningValue, @"Red values should be equal");
    XCTAssertEqual(dg, g - darkeningValue, @"Green values should be equal");
    XCTAssertEqual(db, b - darkeningValue, @"Blue values should be equal");
    XCTAssertEqual(da, a, @"Alpha values should be equal");
}

- (void)testDarkeningColorsFloorToZero
{
    CGFloat r = 0.89f, g = 0.24f, b = 0.67f, a = 1.0f;

    CGFloat darkeningValue = 0.5f;

    UIColor *color = [UIColor colorWithRed:r green:g blue:b alpha:a];
    UIColor *darkColor = [color jsq_colorByDarkeningColorWithValue:darkeningValue];

    CGFloat dr, dg, db, da;
    [darkColor getRed:&dr green:&dg blue:&db alpha:&da];
    XCTAssertEqual(dr, r - darkeningValue, @"Red values should be equal");
    XCTAssertEqual(dg, 0.0f, @"Green values should be floored to zero");
    XCTAssertEqual(db, b - darkeningValue, @"Blue values should be equal");
    XCTAssertEqual(da, a, @"Alpha values should be equal");
}

@end


text:
@extends('lara-mvcms::layouts.application')

@section('content')
    @include('lara-mvcms::content-management.galleries._form')
@stop

@section('page-header')

        {{ trans('lara-mvcms::galleries.edit-title') }}

@overwrite

@section('breadcrumbs')

             {{ trans('lara-mvcms::dashboard.title') }}

             {{ trans('lara-mvcms::galleries.title') }}

 {{ trans('lara-mvcms::galleries.edit-title') }}

@overwrite


text:
package io.gravitee.repository.mongodb.management.internal.model;

import org.springframework.data.annotation.Id;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author Azize ELAMRANI (azize.elamrani at graviteesource.com)
 * @author GraviteeSource Team
 */
public class ApiQualityRulePkMongo implements Serializable {

    private String api;
    private String qualityRule;

    public ApiQualityRulePkMongo() {
    }

    public ApiQualityRulePkMongo(String api, String qualityRule) {
        this.api = api;
        this.qualityRule = qualityRule;
    }

    public String getApi() {
        return api;
    }

    public void setApi(String api) {
        this.api = api;
    }

    public String getQualityRule() {
        return qualityRule;
    }

    public void setQualityRule(String qualityRule) {
        this.qualityRule = qualityRule;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ApiQualityRulePkMongo that = (ApiQualityRulePkMongo) o;
        return Objects.equals(api, that.api) &&
                Objects.equals(qualityRule, that.qualityRule);
    }

    @Override
    public int hashCode() {
        return Objects.hash(api, qualityRule);
    }

    @Override
    public String toString() {
        return "ApiQualityRulePkMongo{" +
                "api='" + api + '\'' +
                ", qualityRule='" + qualityRule + '\'' +
                '}';
    }
}


text:
from unittest import skipUnless

from django.contrib.gis.gdal import HAS_GDAL
from django.forms import ValidationError
from django.test import SimpleTestCase, skipUnlessDBFeature
from django.utils import six
from django.utils.html import escape

if HAS_GDAL:
    from django.contrib.gis import forms
    from django.contrib.gis.geos import GEOSGeometry

@skipUnless(HAS_GDAL, "GeometryFieldTest needs GDAL support")
@skipUnlessDBFeature("gis_enabled")
class GeometryFieldTest(SimpleTestCase):

    def test_init(self):
        "Testing GeometryField initialization with defaults."
        fld = forms.GeometryField()
        for bad_default in ('blah', 3, 'FoO', None, 0):
            self.assertRaises(ValidationError, fld.clean, bad_default)

    def test_srid(self):
        "Testing GeometryField with a SRID set."
        # Input that doesn't specify the SRID is assumed to be in the SRID
        # of the input field.
        fld = forms.GeometryField(srid=4326)
        geom = fld.clean('POINT(5 23)')
        self.assertEqual(4326, geom.srid)
        # Making the field in a different SRID from that of the geometry, and
        # asserting it transforms.
        fld = forms.GeometryField(srid=32140)
        tol = 0.0000001
        xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140)
        # The cleaned geometry should be transformed to 32140.
        cleaned_geom = fld.clean('SRID=4326;POINT (-95.363151 29.763374)')
        self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol))

    def test_null(self):
        "Testing GeometryField's handling of null (None) geometries."
        # Form fields, by default, are required (`required=True`)
        fld = forms.GeometryField()
        with six.assertRaisesRegex(self, forms.ValidationError,
                "No geometry value provided."):
            fld.clean(None)

        # This will clean None as a geometry (See #10660).
        fld = forms.GeometryField(required=False)
        self.assertIsNone(fld.clean(None))

    def test_geom_type(self):
        "Testing GeometryField's handling of different geometry types."
        # By default, all geometry types are allowed.
        fld = forms.GeometryField()
        for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'):
            self.assertEqual(GEOSGeometry(wkt), fld.clean(wkt))

        pnt_fld = forms.GeometryField(geom_type='POINT')
        self.assertEqual(GEOSGeometry('POINT(5 23)'), pnt_fld.clean('POINT(5 23)'))
        # a WKT for any other geom_type will be properly transformed by `to_python`
        self.assertEqual(GEOSGeometry('LINESTRING(0 0, 1 1)'), pnt_fld.to_python('LINESTRING(0 0, 1 1)'))
        # but rejected by `clean`
        self.assertRaises(forms.ValidationError, pnt_fld.clean, 'LINESTRING(0 0, 1 1)')

    def test_to_python(self):
        """
        Testing to_python returns a correct GEOSGeometry object or
        a ValidationError
        """
        fld = forms.GeometryField()
        # to_python returns the same GEOSGeometry for a WKT
        for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'):
            self.assertEqual(GEOSGeometry(wkt), fld.to_python(wkt))
        # but raises a ValidationError for any other string
        for wkt in ('POINT(5)', 'MULTI   POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)'):
            self.assertRaises(forms.ValidationError, fld.to_python, wkt)

    def test_field_with_text_widget(self):
        class PointForm(forms.Form):
            pt = forms.PointField(srid=4326, widget=forms.TextInput)

        form = PointForm()
        cleaned_pt = form.fields['pt'].clean('POINT(5 23)')
        self.assertEqual(cleaned_pt, GEOSGeometry('POINT(5 23)'))
        self.assertEqual(4326, cleaned_pt.srid)

        point = GEOSGeometry('SRID=4326;POINT(5 23)')
        form = PointForm(data={'pt': 'POINT(5 23)'}, initial={'pt': point})
        self.assertFalse(form.has_changed())

@skipUnless(HAS_GDAL, "SpecializedFieldTest needs GDAL support")
@skipUnlessDBFeature("gis_enabled")
class SpecializedFieldTest(SimpleTestCase):
    def setUp(self):
        self.geometries = {
            'point': GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"),
            'multipoint': GEOSGeometry("SRID=4326;MULTIPOINT("
                                       "(13.18634033203125 14.504356384277344),"
                                       "(13.207969665527 14.490966796875),"
                                       "(13.177070617675 14.454917907714))"),
            'linestring': GEOSGeometry("SRID=4326;LINESTRING("
                                       "-8.26171875 -0.52734375,"
                                       "-7.734375 4.21875,"
                                       "6.85546875 3.779296875,"
                                       "5.44921875 -3.515625)"),
            'multilinestring': GEOSGeometry("SRID=4326;MULTILINESTRING("
                                            "(-16.435546875 -2.98828125,"
                                            "-17.2265625 2.98828125,"
                                            "-0.703125 3.515625,"
                                            "-1.494140625 -3.33984375),"
                                            "(-8.0859375 -5.9765625,"
                                            "8.525390625 -8.7890625,"
                                            "12.392578125 -0.87890625,"
                                            "10.01953125 7.646484375))"),
            'polygon': GEOSGeometry("SRID=4326;POLYGON("
                                    "(-1.669921875 6.240234375,"
                                    "-3.8671875 -0.615234375,"
                                    "5.9765625 -3.955078125,"
                                    "18.193359375 3.955078125,"
                                    "9.84375 9.4921875,"
                                    "-1.669921875 6.240234375))"),
            'multipolygon': GEOSGeometry("SRID=4326;MULTIPOLYGON("
                                         "((-17.578125 13.095703125,"
                                         "-17.2265625 10.8984375,"
                                         "-13.974609375 10.1953125,"
                                         "-13.359375 12.744140625,"
                                         "-15.732421875 13.7109375,"
                                         "-17.578125 13.095703125)),"
                                         "((-8.525390625 5.537109375,"
                                         "-8.876953125 2.548828125,"
                                         "-5.888671875 1.93359375,"
                                         "-5.09765625 4.21875,"
                                         "-6.064453125 6.240234375,"
                                         "-8.525390625 5.537109375)))"),
            'geometrycollection': GEOSGeometry("SRID=4326;GEOMETRYCOLLECTION("
                                               "POINT(5.625 -0.263671875),"
                                               "POINT(6.767578125 -3.603515625),"
                                               "POINT(8.525390625 0.087890625),"
                                               "POINT(8.0859375 -2.13134765625),"
                                               "LINESTRING("
                                               "6.273193359375 -1.175537109375,"
                                               "5.77880859375 -1.812744140625,"
                                               "7.27294921875 -2.230224609375,"
                                               "7.657470703125 -1.25244140625))"),
        }

    def assertMapWidget(self, form_instance):
        """
        Make sure the MapWidget js is passed in the form media and a MapWidget
        is actually created
        """
        self.assertTrue(form_instance.is_valid())
        rendered = form_instance.as_p()
        self.assertIn('new MapWidget(options);', rendered)
        self.assertIn('gis/js/OLMapWidget.js', str(form_instance.media))

    def assertTextarea(self, geom, rendered):
        """Makes sure the wkt and a textarea are in the content"""

        self.assertIn('<textarea ', rendered)
        self.assertIn('required', rendered)
        self.assertIn(geom.wkt, rendered)

    def test_pointfield(self):
        class PointForm(forms.Form):
            p = forms.PointField()

        geom = self.geometries['point']
        form = PointForm(data={'p': geom})
        self.assertTextarea(geom, form.as_p())
        self.assertMapWidget(form)
        self.assertFalse(PointForm().is_valid())
        invalid = PointForm(data={'p': 'some invalid geom'})
        self.assertFalse(invalid.is_valid())
        self.assertIn('Invalid geometry value', str(invalid.errors))

        for invalid in [geo for key, geo in self.geometries.items() if key != 'point']:
            self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid())

    def test_multipointfield(self):
        class PointForm(forms.Form):
            p = forms.MultiPointField()

        geom = self.geometries['multipoint']
        form = PointForm(data={'p': geom})
        self.assertTextarea(geom, form.as_p())
        self.assertMapWidget(form)
        self.assertFalse(PointForm().is_valid())

        for invalid in [geo for key, geo in self.geometries.items() if key != 'multipoint']:
            self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid())

    def test_linestringfield(self):
        class LineStringForm(forms.Form):
            l = forms.LineStringField()

        geom = self.geometries['linestring']
        form = LineStringForm(data={'l': geom})
        self.assertTextarea(geom, form.as_p())
        self.assertMapWidget(form)
        self.assertFalse(LineStringForm().is_valid())

        for invalid in [geo for key, geo in self.geometries.items() if key != 'linestring']:
            self.assertFalse(LineStringForm(data={'p': invalid.wkt}).is_valid())

    def test_multilinestringfield(self):
        class LineStringForm(forms.Form):
            l = forms.MultiLineStringField()

        geom = self.geometries['multilinestring']
        form = LineStringForm(data={'l': geom})
        self.assertTextarea(geom, form.as_p())
        self.assertMapWidget(form)
        self.assertFalse(LineStringForm().is_valid())

        for invalid in [geo for key, geo in self.geometries.items() if key != 'multilinestring']:
            self.assertFalse(LineStringForm(data={'p': invalid.wkt}).is_valid())

    def test_polygonfield(self):
        class PolygonForm(forms.Form):
            p = forms.PolygonField()

        geom = self.geometries['polygon']
        form = PolygonForm(data={'p': geom})
        self.assertTextarea(geom, form.as_p())
        self.assertMapWidget(form)
        self.assertFalse(PolygonForm().is_valid())

        for invalid in [geo for key, geo in self.geometries.items() if key != 'polygon']:
            self.assertFalse(PolygonForm(data={'p': invalid.wkt}).is_valid())

    def test_multipolygonfield(self):
        class PolygonForm(forms.Form):
            p = forms.MultiPolygonField()

        geom = self.geometries['multipolygon']
        form = PolygonForm(data={'p': geom})
        self.assertTextarea(geom, form.as_p())
        self.assertMapWidget(form)
        self.assertFalse(PolygonForm().is_valid())

        for invalid in [geo for key, geo in self.geometries.items() if key != 'multipolygon']:
            self.assertFalse(PolygonForm(data={'p': invalid.wkt}).is_valid())

    def test_geometrycollectionfield(self):
        class GeometryForm(forms.Form):
            g = forms.GeometryCollectionField()

        geom = self.geometries['geometrycollection']
        form = GeometryForm(data={'g': geom})
        self.assertTextarea(geom, form.as_p())
        self.assertMapWidget(form)
        self.assertFalse(GeometryForm().is_valid())

        for invalid in [geo for key, geo in self.geometries.items() if key != 'geometrycollection']:
            self.assertFalse(GeometryForm(data={'g': invalid.wkt}).is_valid())

@skipUnless(HAS_GDAL, "OSMWidgetTest needs GDAL support")
@skipUnlessDBFeature("gis_enabled")
class OSMWidgetTest(SimpleTestCase):
    def setUp(self):
        self.geometries = {
            'point': GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"),
        }

    def test_osm_widget(self):
        class PointForm(forms.Form):
            p = forms.PointField(widget=forms.OSMWidget)

        geom = self.geometries['point']
        form = PointForm(data={'p': geom})
        rendered = form.as_p()

        self.assertIn("OpenStreetMap (Mapnik)", rendered)
        self.assertIn("id: 'id_p',", rendered)

    def test_default_lat_lon(self):
        class PointForm(forms.Form):
            p = forms.PointField(
                widget=forms.OSMWidget(attrs={
                    'default_lon': 20, 'default_lat': 30
                }),
            )

        form = PointForm()
        rendered = form.as_p()

        self.assertIn("options['default_lon'] = 20;", rendered)
        self.assertIn("options['default_lat'] = 30;", rendered)
        if forms.OSMWidget.default_lon != 20:
            self.assertNotIn(
                "options['default_lon'] = %d;" % forms.OSMWidget.default_lon,
                rendered)
        if forms.OSMWidget.default_lat != 30:
            self.assertNotIn(
                "options['default_lat'] = %d;" % forms.OSMWidget.default_lat,
                rendered)

@skipUnless(HAS_GDAL, "CustomGeometryWidgetTest needs GDAL support")
@skipUnlessDBFeature("gis_enabled")
class CustomGeometryWidgetTest(SimpleTestCase):

    def test_custom_serialization_widget(self):
        class CustomGeometryWidget(forms.BaseGeometryWidget):
            template_name = 'gis/openlayers.html'
            deserialize_called = 0

            def serialize(self, value):
                return value.json if value else ''

            def deserialize(self, value):
                self.deserialize_called += 1
                return GEOSGeometry(value)

        class PointForm(forms.Form):
            p = forms.PointField(widget=CustomGeometryWidget)

        point = GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)")
        form = PointForm(data={'p': point})
        self.assertIn(escape(point.json), form.as_p())

        CustomGeometryWidget.called = 0
        widget = form.fields['p'].widget
        # Force deserialize use due to a string value
        self.assertIn(escape(point.json), widget.render('p', point.json))
        self.assertEqual(widget.deserialize_called, 1)

        form = PointForm(data={'p': point.json})
        self.assertTrue(form.is_valid())
        # Ensure that resulting geometry has srid set
        self.assertEqual(form.cleaned_data['p'].srid, 4326)


text:
using System.Collections.Generic;
using Nop.Core.Domain.Blogs;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Forums;
using Nop.Core.Domain.Messages;
using Nop.Core.Domain.News;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Shipping;
using Nop.Core.Domain.Stores;

namespace Nop.Services.Messages
{
    public partial interface IMessageTokenProvider
    {
        void AddStoreTokens(IList<Token> tokens, Store store, EmailAccount emailAccount);

        void AddOrderTokens(IList<Token> tokens, Order order, int languageId, int vendorId = 0);

        void AddShipmentTokens(IList<Token> tokens, Shipment shipment, int languageId);

        void AddOrderNoteTokens(IList<Token> tokens, OrderNote orderNote);

        void AddRecurringPaymentTokens(IList<Token> tokens, RecurringPayment recurringPayment);

        void AddReturnRequestTokens(IList<Token> tokens, ReturnRequest returnRequest, OrderItem orderItem);

        void AddGiftCardTokens(IList<Token> tokens, GiftCard giftCard);

        void AddCustomerTokens(IList<Token> tokens, Customer customer);

        void AddNewsLetterSubscriptionTokens(IList<Token> tokens, NewsLetterSubscription subscription);

        void AddProductReviewTokens(IList<Token> tokens, ProductReview productReview);

        void AddBlogCommentTokens(IList<Token> tokens, BlogComment blogComment);

        void AddNewsCommentTokens(IList<Token> tokens, NewsComment newsComment);

        void AddProductTokens(IList<Token> tokens, Product product, int languageId);

        void AddAttributeCombinationTokens(IList<Token> tokens, ProductAttributeCombination combination, int languageId);

        void AddForumTokens(IList<Token> tokens, Forum forum);

        void AddForumTopicTokens(IList<Token> tokens, ForumTopic forumTopic,
            int? friendlyForumTopicPageIndex = null, int? appendedPostIdentifierAnchor = null);

        void AddForumPostTokens(IList<Token> tokens, ForumPost forumPost);

        void AddPrivateMessageTokens(IList<Token> tokens, PrivateMessage privateMessage);

        void AddBackInStockTokens(IList<Token> tokens, BackInStockSubscription subscription);

        string[] GetListOfCampaignAllowedTokens();

        string[] GetListOfAllowedTokens();
    }
}


text:
type FixedGeneticOperatorsMixture <: GeneticOperatorsMixture
    operators::Vector{GeneticOperator} # available operations
    weights::WeightVec{Float64}        # fixed weights

    function FixedGeneticOperatorsMixture(
        operators::Vector{GeneticOperator},
        rates::Vector{Float64} = fill(1.0/length(operators), length(operators)) # defaults to uniform distribution of rates
    )
      length(operators) == length(rates) || throw(DimensionMismatch("Number of mutators does not match the number of their rates"))
      new(operators, weights(rates))
    end
end

# default implementation of apply!() for operators mixture
function apply!{T<:Real}(opmix::GeneticOperatorsMixture, v::Vector{T}, target_index::Int)
  op, tag = next(opmix)
  apply!(op, v, target_index)
end

function next(opmix::FixedGeneticOperatorsMixture)
  i = sample(1:length(opmix.operators), opmix.weights)
  return opmix.operators[i], i
end

# Frequency-adapting genetic operators mixture
type FAGeneticOperatorsMixture <: GeneticOperatorsMixture
    operators::Vector{GeneticOperator} # available operators
    fa::FrequencyAdapter               # adapter of operator frequencies

    function FAGeneticOperatorsMixture(operators::Vector{GeneticOperator}; c = 1E-2, eta = 1E-2, pmin = 0.01, pmax = 1.0)
      new(operators, FrequencyAdapter(length(operators); c = c, eta = eta, pmin = pmin, pmax = pmax))
    end
end

frequencies(opmix::FAGeneticOperatorsMixture) = frequencies(opmix.fa)

function next(opmix::FAGeneticOperatorsMixture)
  i = next(opmix.fa)
  return opmix.operators[i], i
end

function adjust!{F}(opmix::FAGeneticOperatorsMixture, op_index::Int, candi_index::Int, new_fitness::F, old_fitness::F, is_improved::Bool)
  # KLUDGE we don't know the fitness scheme, but if there is no improvement in fitness,
  # new_fitness==old_fitness, so it's ok to take the abs()
  update!(opmix.fa, op_index, is_improved ? abs(new_fitness-old_fitness) : 0.0)

  # also adjust the actual operator
  adjust!(opmix.operators[op_index], 0, candi_index, new_fitness, old_fitness, is_improved)
end

function trace_state(io::IO, fa::FAGeneticOperatorsMixture)
  println(io, "FrequencyAdapting mixture rates:")
  for i in eachindex(fa.operators)
    @printf(io, " %s=%.2f", typeof(fa.operators[i]), fa.fa.p[i])
  end
  println(io)
end


text:
[Here](http://tilow.github.com/SimplePanorama/) you can take a look at the script in action.
SimplePanorama is available under the [MIT License](https://github.com/TiloW/SimplePanorama/blob/master/LICENSE).

If you encounter any problems, feel free to send me a [mail](mailto:tilo@wiedera.de).
## Purpose

SimplePanorama is a javascript snippet, allowing you to create a cyclindric panorama for your website in no time.
SimplePanorama makes use of CSS 3D Transforms and gracefully falls back to other solutions if unavaibable.

## Requirements

SimplePanorama requires JQuery and Modernizr it has so far only been tested with version 1.8.3 but it will probably also work with older versions.

## Setup

You need to include [JQuery](http://jquery.com/download/),
[Modernizr](https://github.com/TiloW/SimplePanorama/blob/master/test/modernizr.js) (with touch-event and 3D-transform detection enabled),
[simple-panorama.css](https://github.com/TiloW/SimplePanorama/blob/master/public/simple-panorama.css) and [simple-panorama.js](https://github.com/TiloW/SimplePanorama/blob/master/public/simple-panorama.js).

## Usage

Take a look at the [demo section](https://github.com/TiloW/SimplePanorama/tree/master/test)!

### Creating a Panorama
You can create a new panorama after your DOM is loaded.
Here we create a panorama inside of the DOM element with id="myPanoContainer" and choose the image found at "../my_image.jpg".
```javascript
new SimplePanorama({
  'elem':      $('#myPanoContainer'),
  'imagePath': '../my_image.jpg'
});
```

### Basic Animation
You can animate the panorama by setting the "targetSpeed".
```javascript
pano = new SimplePanorama({
  'elem':      $('#myPanoContainer'),
  'imagePath': '../my_image.jpg'
});
pano.setTargetSpeed(0.1);
```

### Adding Hotspots
You can add hotspots to a panorama after it has finished loading.
Here we add a circle and a rectangle.
As you can see, one can embed any html-elements inside of the hotspots.
The circle methods takes html-content, x,y and radius. A rectangle function call must be provided with html-content, left, top, width and height.
```javascript
new SimplePanorama({
  'selector':  '#myPanoContainer',
  'imagePath': '../my_image.jpg',
  'callback':  function() {
    this.createCircleHotspot('<p>Hello World!<br />I\'m a <a href="http://de.wikipedia.org/wiki/Circle">circle</a>.</p>', 300, 250, 200);
    this.createRectHotspot('<p>Hello World!<br />I\'m a rectangle.</p>', 750, 150, 200, 200);
  }
});
```

### Activating Modules
There are certain modules which can be activaded per panorama instance.
Here we add support for moving the panorama by holding down the primary mousebutton.
```javascript
new SimplePanorama({
  'elem': $('#myPanoContainer'),
  'imagePath': '../my_image.jpg',
  'modules': ['move_mousedown']
});
```
For the time beeing theese modules are available:
- **move_mousedown**: Move the panorama around by dragging it
- **move_swipe**: Move the panorama around with a touchscreen
- **show_coordinates**: Displays the exact cursor position in the panorama

- **move_mousehover**: Move the panorama around by hovering over it
- **move_touch**: Move the panorama around with a touchscreen

### Options
As you can see, there are some options which can (or must) be provided to the constructor. Here's a complete list:
- **elem**: a JQuery select result, containing your DOM element
- **selector**: a JQuery selector to be used for fetching your DOM element (only used if **elem** is not supplied)
- **imgPath**: the path to your image file
- **callback**: a function to be called after loading the image and initializing the panorama (mostly used to setup hotspots)
- **modules**: an array of modules to be activated for this instance
- **repeative**: set to "false" if you dont want your panorama to be a full 360� shot
- **initialPos**: the intial rotation of the image (e.g. a value of 300 would result in the first 300 pixels to be hidden on the left)

### Styling Hotspots
The panorama consists only of HTML elements, you can style it using CSS.
Theese are the most important CSS classes:
- **sp-hotspot**: a hotspot, you want to set "background" and "border" here
- **sp-rect**: a rectangular hotspot
- **sp-circ**: a circular hotspot
- **sp-hotspot-content**: a wrapper inside of every hotspot, set "color" and "font" here, also you can change the padding if need be


text:
@import '../variables.css';

.outermost {
  box-shadow: 5px 5px 5px black;
  overflow-x: hidden;
  overflow-y: auto;
  height: 600px;
  border: 1px solid black;
  padding: 2px;
}

.expanded {
  transition: max-height 0.5s linear 0s;
  overflow-y: hidden;
  max-height: 1000px;
  border: 1px solid black;
}

.contracted {
  transition: max-height 0.5s linear 0s;
  max-height: 0;
  overflow-y: hidden;
  border: 1px solid black;
}

.singlebutton {
  margin: 5px;
}


text:
BIND_ADDR = '127.0.0.1'
BIND_PORT = '1337'

# How long should we wait for client connections to close
# before closing them during shutdown?
SHUTDOWN_TIMEOUT = 10

# How many peers should we gossip to?
GOSSIP_PEERS = 3

# How many generations should we gossip to?
# 2 generations: node1 -> gossips to n peers -> node2 -> gossips -> node3
# 3 generations: node1 -> gossips to n peers -> node2 -> gossips -> node3 -> gossips -> node4
GOSSIP_GENERATIONS = 2

PING_TIMEOUT = 1
PING_INTERVAL = 0.5

# When sending an ack, we have an opportunity to tack on some gossip.
# How many messages should we attach?
ACK_PAYLOAD_SIZE = 1


text:
package net.sf.jabref.logic.formatter.casechanger;

import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.cleanup.Formatter;

public class TitleCaseFormatter implements Formatter {

    @Override
    public String getName() {
        return Localization.lang("Title case");
    }

    @Override
    public String getKey() {
        return "title_case";
    }

    /**
     * Converts all words to upper case, but converts articles, prepositions, and conjunctions to lower case
     * Capitalizes first and last word
     * Does not change words starting with "{"
     */
    @Override
    public String format(String input) {
        Title title = new Title(input);

        title.getWords().stream().filter(Word::isSmallerWord).forEach(Word::toLowerCase);
        title.getWords().stream().filter(Word::isLargerWord).forEach(Word::toUpperFirst);

        title.getFirstWord().ifPresent(Word::toUpperFirst);
        title.getLastWord().ifPresent(Word::toUpperFirst);

        for (int i = 0; i < (title.getWords().size() - 2); i++) {
            if (title.getWords().get(i).endsWithColon()) {
                title.getWords().get(i + 1).toUpperFirst();
            }
        }

        return title.toString();
    }

    @Override
    public String getDescription() {
        return Localization.lang(
                "Capitalize all words, but converts articles, prepositions, and conjunctions to lower case.");
    }

    @Override
    public String getExampleInput() {
        return "{BPMN} conformance In open source Engines";
    }

}


text:
###### How to run:

Discovery server is implemented in Python. To run this server,
$ python discovery.py portNumber

where,
portNumber: is the port number that discovery will listen on, for requests.

Once you have the discovery up and running, you need to then start Conversion servers and Proxy servers with the IP/Hostname and Port Number of this Discovery server.

** ADD/REMOVE/LOOKUP protocols are described in the protocols/ folder. This discovery does exactly that, not more, not less!**

#### Proxy Server

Our proxy server is an extended version of HW2 Proxy server.
To compile and run:
```
$ javac ProxyServer.java
```

```
$ java ProxyServer i:<my ip/hostname>:<my portno> d:<discovery1 ip/hostname>:<discovery1 portno>[,...]

where,
i:<ip>:<port> - are address and portnumber of this proxyserver. address should be an external ip address

d:<ip>:<port>,[...] - address and portnumber of discovery servers. This can be used to register to multiple discovery servers.

ex:
to register to 1 discovery server:
$ java ProxyServer i:localhost:9999 d:localhost:7777

to register to 2 discovery servers:
$ java ProxyServer i:localhost:9999 d:localhost:7777,localhost:6666
```

**Note:**
* Proxy server also supports reading discovery servers and conversion table from file.
* Conversion server list is removed from the config file, instead Discovery server list is brought in.
* Tags:
```
  start tag: "=DISCOVERY_SERVER_LIST"
  server:	<ip or hostname>:<portno>
  end tag: "=END_LIST"
```
ex:
```
=DISCOVERY_SERVER_LIST
localhost:5555
=END_LIST
=CONVERSION_TABLE
ft->cm:ft->in,in->cm
cm->ft:cm->in,in->ft
m->in:m->cm,cm->in
in->m:in->cm,cm->m
=END_TABLE
```
* Each discovery server entry will contain IP address or hostname and port number with colon as a delimiter.
* Limitation: Only using maps to store discovery's ip,portno. So, if you have 2 discovery servers running on machine, only the last one is picked for discovery.
* At the start of the server, ADD requests are sent to all the discovery servers specified.
* When the server terminates gracefully (which will never happen!), it sends p REMOVE request to each server.
* Whenever a conversion is requested by the client, Proxy server breaks the conversion into multi-steps based on it's predefined table, and sends out LOOKUP request to Discovery server in its list. It sends out request to each Discovery server until it receives a valid "<hostname/IP> <portno>". If it receives a "None" response or "FAILURE" response, it continues to LOOKUP with remaining Discovery servers.

#### Conversion servers

#### Python Conversion Server 1 -

Our conversion server is an extended version of HW2 conversion server. It takes the IP address of the discovery server and the Conversion Server along with the Port number of both the servers. The Conversion server then registers its IP and port number to the discovery server. This conversion server converts from b to in or in to b and returns the client with the required output.
To compile and run:

Usage: python <programName.py> <IP:Conversion Server> <Port: Conversion server> <IP:Discovery Server> <Port: Discovery server>

where,

programName.py - It is the name of the conversion server written in python.

IP: Conversion Server - The IP of the conversion is given as an input parameter.

Port: Conversion Server - It is the port number of the Conversion server on which the conversion server will run.

IP: Discovery Server - It is the IP address of discovery server

Port: Discovery server - It is port number of discovery server.

Run:
```
python PythonConvServ2.py 10.0.0.3 5555 10.0.0.98 4444
```
Output:
```
registered
Response: SUCCESS

Started server on  4444
```
#### Python Conversion Server 2 -

Our conversion server is an extended version of HW2 conversion server. It takes the IP address of the discovery server and the Conversion Server along with the Port number of both the servers. The Conversion server then registers its IP and port number to the discovery server. This conversion server converts from cm to m or m to cm and returns the client with the required output.

To compile and run:

Usage:
```
python <programName.py> <IP:Conversion Server> <Port: Conversion server> <IP:Discovery Server> <Port: Discovery server>
```
where,

programName.py - It is the name of the conversion server written in python.

IP: Conversion Server - The IP of the conversion is given as an input parameter.

Port: Conversion Server - It is the port number of the Conversion server on which the conversion server will run.

IP: Discovery Server - It is the IP address of discovery server.

Port: Discovery server - It is port number of discovery server.

Run:
```
python PythonConvServ2.py 10.0.0.3 5555 10.0.0.98 4445
```
Output:
```
registered
Response: SUCCESS

Started server on  4445
```

#### C Conversion Server -

The conversion server is an extended version of HW2 conversion server.

It converts between banana (b) and pounds (lbs).

It is written in C.

Compile:

gcc -o convserver.o convserver.c

Example:
```
gcc ConvServer.c
```
Run:

./convserver.o DiscoveryIP DiscoveryPort SelfServerIP SelfServerPort

DiscoveryIP: It is the IP address of discovery server.

DiscoveryPort: It is the port number of discovery server.

SelfServerIp: It is the IP address of conversion server.

SelfServerPort: It is the port number of conversion server.

Example:
```
./a.out 52.23.242.100 5555 52.23.242.100 5554
```

Output:
```
Started server on port 5554
ADD b lbs 52.23.242.100 5554
```

####Java Conversion Server -

The conversion server is an extended version of HW2 conversion server.

It converts between inch (in) and centimeter (cm).

It is written in java.

Compile:

javac ConvServer.java

Example:
```
javac ConvServer.java
```

Run:

java ConvServer DiscoveryIP DiscoveryPort SelfServerIP SelfServerPort

DiscoveryIP: It is the IP address of discovery server.

DiscoveryPort: It is the port number of discovery server.

SelfServerIp: It is the IP address of conversion server.

SelfServerPort: It is the port number of conversion server.

Example:
```
java ConvServer 52.23.242.100 5555 52.23.242.100 5553
```
Output:
```
Started server on port 5553
```

Note:

When inputting the port number and IP address of conversion server and discovery server, the sequence of the four arguments are different.

In the conversion servers written in python, first input the IP address and port number of conversion server, and then input the IP address and port number discovery server.

While in the conversion servers written in Java and C, first input discovery server's IP address and port number, and then input the conversion server's IP address and port number.


text:
import os

# Parse the readme, and add new script info
# based on the flags used for tampermonkey.

# Default section.

intro = """
#tampermonkey
My ongoing TamperMonkey scripts for Chrome.

## modules

"""

def _markdown_param(line, name):
    return line.replace(
        '// @{}'.format(name), '\n**@{}**: '.format(name)).strip()

def _parse_script(doc):
    # Parse out the tampermonkey annotations and use them as markdown entries.
    vals = ''
    with open(doc) as jsdoc:
        param = ''
        for line in jsdoc.readlines():
            if line.startswith('// @name '):
                param = _markdown_param(line, 'name')
            elif line.startswith('// @description '):
                param = _markdown_param(line, 'description')
            elif line.startswith('// @match '):
                param = _markdown_param(line, 'match')
            else:
                continue
            vals += '\n{}\n'.format(param)
    return vals + '\n'

def parse():
    # Overwrite to prevent concatenating random text, etc...
    with open('README.md', 'wb') as markdownfile:
        markdownfile.write(intro)
        jsfiles = os.listdir('src/')
        for jsfile in jsfiles:
            markdownfile.write('#### {}\n'.format(jsfile))
            markdownfile.write(_parse_script(
                '{}/src/{}'.format(os.getcwd(), jsfile)))

if __name__ == '__main__':
    parse()


text:
'use strict'
import isProtoProp from '../lib/'
import test from 'ava'

test('should throw error when type or property is not a string', t => {
  const typeTest = () => isProtoProp(1, 'prop')

  const propTest = () => isProtoProp('type', 1)

  t.throws(typeTest, TypeError)
  t.throws(propTest, TypeError)
})

test('should return false if not a js type', t => {
  t.falsy(isProtoProp('dog', 'bark'))
  t.falsy(isProtoProp('gulp', 'task'))
})

test('should return false if property is not on prototype', t => {
  t.falsy(isProtoProp('Array', 'count'))
  t.falsy(isProtoProp('Error', 'ignore'))
})

test('shoud return true if property is on prototype', t => {
  t.truthy(isProtoProp('Array', 'length'))
  t.truthy(isProtoProp('Object', 'toString'))
  t.truthy(isProtoProp('String', 'padEnd'))
})

test('should be case insensitive for types', t => {
  t.truthy(isProtoProp('array', 'length'))
  t.truthy(isProtoProp('ARRAY', 'length'))
})


text:
package edu.jhu.hlt.utilt;

import java.util.Iterator;

/**
 * Generic interface that combines {@link Iterator} and {@link AutoCloseable}
 * (similar to C# IDisposable).
 */
public interface AutoCloseableIterator<E> extends AutoCloseable, Iterator<E> {

}


text:
package it.reply.orchestrator.resource;

import it.reply.orchestrator.resource.common.AbstractResource;
import java.util.Date;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class DeploymentScheduleEventResource extends AbstractResource {

  private DeploymentResource deployment;

  private String scope;

  private String name;

  @Nullable
  private String replicationStatus;

  /**
   *  Create a new DeploymentScheduleEventResource.
   * @param uuid the uuid
   * @param creationTime the creation time
   * @param updateTime the update time
   * @param deployment the deployment deployment
   * @param scope the file scope
   * @param name the file name
   * @param replicationStatus the replication status
   */
  @Builder
  public DeploymentScheduleEventResource(@NonNull String uuid, @Nullable Date creationTime,
      @Nullable Date updateTime, DeploymentResource deployment,
      String scope, String name, @Nullable String replicationStatus) {
    super(uuid, creationTime, updateTime, null);
    this.deployment = deployment;
    this.scope = scope;
    this.name = name;
    this.replicationStatus = replicationStatus;
  }

}


text:
class HeatLaneJudgeNotesController < ApplicationController
  before_action :authenticate_user!
  before_action :load_competition
  before_action :load_heat_lane_judge_note

  before_action :authorize_competition_data

  # PUT /competition/:id/heat_lane_judge_note/:id/merge
  def merge
    lane = @heat_lane_judge_note.lane
    if @heat_lane_judge_note.merge
      flash[:notice] = "Updated Time Result for Lane #{lane}"
    else
      flash[:alert] = "Unable to update Time Result for Lane #{lane}. Check that it exists"
    end
    redirect_back(fallback_location: competition_heat_review_path(@competition, @heat_lane_judge_note.heat))
  end

  private

  def authorize_competition_data
    authorize @competition, :create_preliminary_result?
  end

  def load_heat_lane_judge_note
    @heat_lane_judge_note = HeatLaneJudgeNote.find(params[:id])
  end

  def load_competition
    @competition = Competition.find(params[:competition_id])
  end
end


text:
/* jshint camelcase: false, unused: false */
/* global inject: false */
'use strict';

describe('pascalprecht.translate', function () {

  describe('$translateStaticFilesLoader', function () {

    var $translate, $httpBackend, $translateStaticFilesLoader, $translationCache;

    beforeEach(module('pascalprecht.translate', function ($httpProvider) {
      if (angular.isDefined($httpProvider.useLegacyPromiseExtensions)) {
        $httpProvider.useLegacyPromiseExtensions(false);
      }
    }));

    beforeEach(inject(function (_$translate_, _$httpBackend_, _$translateStaticFilesLoader_, _$translationCache_) {
      $httpBackend = _$httpBackend_;
      $translate = _$translate_;
      $translateStaticFilesLoader = _$translateStaticFilesLoader_;
      $translationCache = _$translationCache_;

      $httpBackend.when('GET', 'lang_de_DE.json').respond({HEADER : 'Ueberschrift'});
      $httpBackend.when('GET', 'lang_de_DE.123.json').respond({HEADER : 'Ueberschrift'});
      $httpBackend.when('GET', 'lang_en_US.json').respond({HEADER : 'Header'});
      $httpBackend.when('GET', 'lang_nt_VD.json').respond(404);
    }));

    afterEach(function () {
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });

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

    it('should be a function', function () {
      expect(typeof $translateStaticFilesLoader).toBe('function');
    });

    it('should throw an error when called without files and prefix or suffix', function () {
      expect(function () {
        $translateStaticFilesLoader();
      }).toThrowError('Couldn\'t load static files, no files and prefix or suffix specified!');
    });

    it('should throw an error when called without prefix or suffix in files object', function () {
      expect(function () {
        $translateStaticFilesLoader({
          files : [{}]
        });
      }).toThrowError('Couldn\'t load static file, no prefix or suffix specified!');
    });

    it('should fetch static files when invoking', function () {
      $httpBackend.expectGET('lang_de_DE.json');
      $translateStaticFilesLoader({
        key : 'de_DE',
        prefix : 'lang_',
        suffix : '.json'
      });
      $httpBackend.flush();
    });

    it('should fetch static files from file map when invoking', function () {
      $httpBackend.expectGET('lang_de_DE.123.json');
      $translateStaticFilesLoader({
        key : 'de_DE',
        prefix : 'lang_',
        suffix : '.json',
        fileMap : {
          'lang_de_DE.json' : 'lang_de_DE.123.json'
        }
      });
      $httpBackend.flush();
    });

    it('should return a promise', function () {
      var promise = $translateStaticFilesLoader({
        key : 'de_DE',
        prefix : 'lang_',
        suffix : '.json'
      });
      expect(promise.then).toBeDefined();
      expect(typeof promise.then).toBe('function');
      $httpBackend.flush();
    });

    it('should put a translation table into a cache', function () {
      $httpBackend.expectGET('lang_de_DE.json');
      $translateStaticFilesLoader({
        key : 'de_DE',
        prefix : 'lang_',
        suffix : '.json',
        $http : {
          cache : $translationCache
        }
      });
      $httpBackend.flush();
      expect($translationCache.info().size).toEqual(1);
    });
  });

  describe('$translateStaticFilesLoader with custom options (method=POST)', function () {

    var $translate, $httpBackend, $translateStaticFilesLoader;

    beforeEach(module('pascalprecht.translate', function ($httpProvider) {
      if (angular.isDefined($httpProvider.useLegacyPromiseExtensions)) {
        $httpProvider.useLegacyPromiseExtensions(false);
      }
    }));

    beforeEach(inject(function (_$translate_, _$httpBackend_, _$translateStaticFilesLoader_) {
      $httpBackend = _$httpBackend_;
      $translate = _$translate_;
      $translateStaticFilesLoader = _$translateStaticFilesLoader_;

      $httpBackend.when('POST', 'lang_de_DE.json').respond({HEADER : 'Ueberschrift'});
      $httpBackend.when('POST', 'lang_en_US.json').respond({HEADER : 'Header'});
      $httpBackend.when('POST', 'lang_nt_VD.json').respond(404);
    }));

    afterEach(function () {
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });

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

    it('should be a function', function () {
      expect(typeof $translateStaticFilesLoader).toBe('function');
    });

    it('should throw an error when called without files and prefix or suffix', function () {
      expect(function () {
        $translateStaticFilesLoader({
          $http : {
            method : 'POST'
          }
        });
      }).toThrowError('Couldn\'t load static files, no files and prefix or suffix specified!');
    });

    it('should throw an error when called without prefix or suffix in files object', function () {
      expect(function () {
        $translateStaticFilesLoader({
          $http : {
            method : 'POST'
          },
          files : [{}]
        });
      }).toThrowError('Couldn\'t load static file, no prefix or suffix specified!');
    });

    it('should fetch static files when invoking', function () {
      $httpBackend.expectPOST('lang_de_DE.json');
      $translateStaticFilesLoader({
        key : 'de_DE',
        prefix : 'lang_',
        suffix : '.json',
        $http : {
          method : 'POST'
        }
      });
      $httpBackend.flush();
    });
  });

});


text:
package gov.hhs.fha.nhinc.docsubmission._11.passthru.deferred.request;

import javax.xml.ws.WebServiceContext;

import gov.hhs.fha.nhinc.async.AsyncMessageIdExtractor;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetRequestType;
import gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType;
import gov.hhs.fha.nhinc.cxf.extraction.SAML2AssertionExtractor;
import gov.hhs.fha.nhinc.docsubmission.passthru.deferred.request.PassthruDocSubmissionDeferredRequestOrchImpl;
import gov.hhs.fha.nhinc.messaging.server.BaseService;
import gov.hhs.healthit.nhin.XDRAcknowledgementType;

/**
 *
 * @author Neil Webb
 */
public class PassthruDocSubmissionDeferredRequestImpl extends BaseService {

    public XDRAcknowledgementType provideAndRegisterDocumentSetBRequest(
            RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType provideAndRegisterRequestRequest,
            WebServiceContext context) {
        AssertionType assertion = getAssertion(context, null);

        return new PassthruDocSubmissionDeferredRequestOrchImpl().provideAndRegisterDocumentSetBRequest(
                provideAndRegisterRequestRequest.getProvideAndRegisterDocumentSetRequest(), assertion,
                provideAndRegisterRequestRequest.getNhinTargetSystem());
    }

    public XDRAcknowledgementType provideAndRegisterDocumentSetBRequest(
            RespondingGatewayProvideAndRegisterDocumentSetRequestType provideAndRegisterRequestRequest,
            WebServiceContext context) {
        AssertionType assertion = getAssertion(context, provideAndRegisterRequestRequest.getAssertion());

        return new PassthruDocSubmissionDeferredRequestOrchImpl().provideAndRegisterDocumentSetBRequest(
                provideAndRegisterRequestRequest.getProvideAndRegisterDocumentSetRequest(), assertion,
                provideAndRegisterRequestRequest.getNhinTargetSystem());

    }
}


text:
import * as t from '../.'

declare function fromJSON<T>(value: any, type: t.Type<T>): T;

export default fromJSON


text:
_**Please read** our_
[**contribution guide**](https://github.com/dwyl/contributing)
(_thank you_!)


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/sync/engine_impl/directory_commit_contribution.h"

#include <stdint.h>

#include <set>
#include <string>

#include "base/message_loop/message_loop.h"
#include "components/sync/base/attachment_id_proto.h"
#include "components/sync/sessions_impl/status_controller.h"
#include "components/sync/syncable/entry.h"
#include "components/sync/syncable/mutable_entry.h"
#include "components/sync/syncable/syncable_read_transaction.h"
#include "components/sync/syncable/syncable_write_transaction.h"
#include "components/sync/test/engine/test_directory_setter_upper.h"
#include "components/sync/test/engine/test_id_factory.h"
#include "components/sync/test/engine/test_syncable_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace syncer {

class DirectoryCommitContributionTest : public ::testing::Test {
 public:
  void SetUp() override {
    dir_maker_.SetUp();

    syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir());
    CreateTypeRoot(&trans, dir(), PREFERENCES);
    CreateTypeRoot(&trans, dir(), EXTENSIONS);
    CreateTypeRoot(&trans, dir(), ARTICLES);
    CreateTypeRoot(&trans, dir(), BOOKMARKS);
  }

  void TearDown() override { dir_maker_.TearDown(); }

 protected:
  int64_t CreateUnsyncedItemWithAttachments(
      syncable::WriteTransaction* trans,
      ModelType type,
      const std::string& tag,
      const sync_pb::AttachmentMetadata& attachment_metadata) {
    // For bookmarks specify the Bookmarks root folder as the parent;
    // for other types leave the parent ID empty
    syncable::Id parent_id;
    if (type == BOOKMARKS) {
      syncable::Entry parent_entry(trans, syncable::GET_TYPE_ROOT, type);
      parent_id = parent_entry.GetId();
    }

    syncable::MutableEntry entry(trans, syncable::CREATE, type, parent_id, tag);
    if (attachment_metadata.record_size() > 0) {
      entry.PutAttachmentMetadata(attachment_metadata);
    }
    entry.PutIsUnsynced(true);
    return entry.GetMetahandle();
  }

  int64_t CreateUnsyncedItem(syncable::WriteTransaction* trans,
                             ModelType type,
                             const std::string& tag) {
    return CreateUnsyncedItemWithAttachments(trans, type, tag,
                                             sync_pb::AttachmentMetadata());
  }

  int64_t CreateSyncedItem(syncable::WriteTransaction* trans,
                           ModelType type,
                           const std::string& tag) {
    syncable::Entry parent_entry(trans, syncable::GET_TYPE_ROOT, type);
    syncable::MutableEntry entry(trans, syncable::CREATE, type,
                                 parent_entry.GetId(), tag);

    entry.PutId(syncable::Id::CreateFromServerId(
        id_factory_.NewServerId().GetServerId()));
    entry.PutBaseVersion(10);
    entry.PutServerVersion(10);
    entry.PutIsUnappliedUpdate(false);
    entry.PutIsUnsynced(false);
    entry.PutIsDel(false);
    entry.PutServerIsDel(false);

    return entry.GetMetahandle();
  }

  void CreateSuccessfulCommitResponse(
      const sync_pb::SyncEntity& entity,
      sync_pb::CommitResponse::EntryResponse* response) {
    response->set_response_type(sync_pb::CommitResponse::SUCCESS);
    response->set_non_unique_name(entity.name());
    response->set_version(entity.version() + 1);
    response->set_parent_id_string(entity.parent_id_string());

    if (entity.id_string()[0] == '-')  // Look for the - in 'c-1234' style IDs.
      response->set_id_string(id_factory_.NewServerId().GetServerId());
    else
      response->set_id_string(entity.id_string());
  }

  syncable::Directory* dir() { return dir_maker_.directory(); }

  TestIdFactory id_factory_;

  // Used in construction of DirectoryTypeDebugInfoEmitters.
  base::ObserverList<TypeDebugInfoObserver> type_observers_;

 private:
  base::MessageLoop loop_;  // Neeed to initialize the directory.
  TestDirectorySetterUpper dir_maker_;
};

// Verify that the DirectoryCommitContribution contains only entries of its
// specified type.
TEST_F(DirectoryCommitContributionTest, GatherByTypes) {
  int64_t pref1;
  {
    syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir());
    pref1 = CreateUnsyncedItem(&trans, PREFERENCES, "pref1");
    CreateUnsyncedItem(&trans, PREFERENCES, "pref2");
    CreateUnsyncedItem(&trans, EXTENSIONS, "extension1");
  }

  DirectoryTypeDebugInfoEmitter emitter(PREFERENCES, &type_observers_);
  std::unique_ptr<DirectoryCommitContribution> cc(
      DirectoryCommitContribution::Build(dir(), PREFERENCES, 5, &emitter));
  ASSERT_EQ(2U, cc->GetNumEntries());

  const std::vector<int64_t>& metahandles = cc->metahandles_;
  EXPECT_TRUE(std::find(metahandles.begin(), metahandles.end(), pref1) !=
              metahandles.end());
  EXPECT_TRUE(std::find(metahandles.begin(), metahandles.end(), pref1) !=
              metahandles.end());

  cc->CleanUp();
}

// Verify that the DirectoryCommitContributionTest builder function
// truncates if necessary.
TEST_F(DirectoryCommitContributionTest, GatherAndTruncate) {
  int64_t pref1;
  int64_t pref2;
  {
    syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir());
    pref1 = CreateUnsyncedItem(&trans, PREFERENCES, "pref1");
    pref2 = CreateUnsyncedItem(&trans, PREFERENCES, "pref2");
    CreateUnsyncedItem(&trans, EXTENSIONS, "extension1");
  }

  DirectoryTypeDebugInfoEmitter emitter(PREFERENCES, &type_observers_);
  std::unique_ptr<DirectoryCommitContribution> cc(
      DirectoryCommitContribution::Build(dir(), PREFERENCES, 1, &emitter));
  ASSERT_EQ(1U, cc->GetNumEntries());

  int64_t only_metahandle = cc->metahandles_[0];
  EXPECT_TRUE(only_metahandle == pref1 || only_metahandle == pref2);

  cc->CleanUp();
}

// Sanity check for building commits from DirectoryCommitContributions.
// This test makes two CommitContribution objects of different types and uses
// them to initialize a commit message.  Then it checks that the contents of the
// commit message match those of the directory they came from.
TEST_F(DirectoryCommitContributionTest, PrepareCommit) {
  {
    syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir());
    CreateUnsyncedItem(&trans, PREFERENCES, "pref1");
    CreateUnsyncedItem(&trans, PREFERENCES, "pref2");
    CreateUnsyncedItem(&trans, EXTENSIONS, "extension1");
  }

  DirectoryTypeDebugInfoEmitter emitter1(PREFERENCES, &type_observers_);
  DirectoryTypeDebugInfoEmitter emitter2(EXTENSIONS, &type_observers_);
  std::unique_ptr<DirectoryCommitContribution> pref_cc(
      DirectoryCommitContribution::Build(dir(), PREFERENCES, 25, &emitter1));
  std::unique_ptr<DirectoryCommitContribution> ext_cc(
      DirectoryCommitContribution::Build(dir(), EXTENSIONS, 25, &emitter2));

  sync_pb::ClientToServerMessage message;
  pref_cc->AddToCommitMessage(&message);
  ext_cc->AddToCommitMessage(&message);

  const sync_pb::CommitMessage& commit_message = message.commit();

  std::set<syncable::Id> ids_for_commit;
  ASSERT_EQ(3, commit_message.entries_size());
  for (int i = 0; i < commit_message.entries_size(); ++i) {
    const sync_pb::SyncEntity& entity = commit_message.entries(i);
    // The entities in this test have client-style IDs since they've never been
    // committed before, so we must use CreateFromClientString to re-create them
    // from the commit message.
    ids_for_commit.insert(
        syncable::Id::CreateFromClientString(entity.id_string()));
  }

  ASSERT_EQ(3U, ids_for_commit.size());
  {
    syncable::ReadTransaction trans(FROM_HERE, dir());
    for (std::set<syncable::Id>::iterator it = ids_for_commit.begin();
         it != ids_for_commit.end(); ++it) {
      SCOPED_TRACE(it->value());
      syncable::Entry entry(&trans, syncable::GET_BY_ID, *it);
      ASSERT_TRUE(entry.good());
      EXPECT_TRUE(entry.GetSyncing());
      EXPECT_FALSE(entry.GetDirtySync());
    }
  }

  pref_cc->CleanUp();
  ext_cc->CleanUp();
}

// Check that deletion requests include a model type.
// This was not always the case, but was implemented to allow us to loosen some
// other restrictions in the protocol.
TEST_F(DirectoryCommitContributionTest, DeletedItemsWithSpecifics) {
  int64_t pref1;
  {
    syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir());
    pref1 = CreateSyncedItem(&trans, PREFERENCES, "pref1");
    syncable::MutableEntry e1(&trans, syncable::GET_BY_HANDLE, pref1);
    e1.PutIsDel(true);
    e1.PutIsUnsynced(true);
  }

  DirectoryTypeDebugInfoEmitter emitter(PREFERENCES, &type_observers_);
  std::unique_ptr<DirectoryCommitContribution> pref_cc(
      DirectoryCommitContribution::Build(dir(), PREFERENCES, 25, &emitter));
  ASSERT_TRUE(pref_cc);

  sync_pb::ClientToServerMessage message;
  pref_cc->AddToCommitMessage(&message);

  const sync_pb::CommitMessage& commit_message = message.commit();
  ASSERT_EQ(1, commit_message.entries_size());
  EXPECT_TRUE(commit_message.entries(0).specifics().has_preference());

  pref_cc->CleanUp();
}

// As ususal, bookmarks are special.  Bookmark deletion is special.
// Deleted bookmarks include a valid "is folder" bit and their full specifics
// (especially the meta info, which is what server really wants).
TEST_F(DirectoryCommitContributionTest, DeletedBookmarksWithSpecifics) {
  int64_t bm1;
  {
    syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir());
    bm1 = CreateSyncedItem(&trans, BOOKMARKS, "bm1");
    syncable::MutableEntry e1(&trans, syncable::GET_BY_HANDLE, bm1);

    e1.PutIsDir(true);
    e1.PutServerIsDir(true);

    sync_pb::EntitySpecifics specifics;
    sync_pb::BookmarkSpecifics* bm_specifics = specifics.mutable_bookmark();
    bm_specifics->set_url("http://www.chrome.com");
    bm_specifics->set_title("Chrome");
    sync_pb::MetaInfo* meta_info = bm_specifics->add_meta_info();
    meta_info->set_key("K");
    meta_info->set_value("V");
    e1.PutSpecifics(specifics);

    e1.PutIsDel(true);
    e1.PutIsUnsynced(true);
  }

  DirectoryTypeDebugInfoEmitter emitter(BOOKMARKS, &type_observers_);
  std::unique_ptr<DirectoryCommitContribution> bm_cc(
      DirectoryCommitContribution::Build(dir(), BOOKMARKS, 25, &emitter));
  ASSERT_TRUE(bm_cc);

  sync_pb::ClientToServerMessage message;
  bm_cc->AddToCommitMessage(&message);

  const sync_pb::CommitMessage& commit_message = message.commit();
  ASSERT_EQ(1, commit_message.entries_size());

  const sync_pb::SyncEntity& entity = commit_message.entries(0);
  EXPECT_TRUE(entity.has_folder());
  ASSERT_TRUE(entity.specifics().has_bookmark());
  ASSERT_EQ(1, entity.specifics().bookmark().meta_info_size());
  EXPECT_EQ("K", entity.specifics().bookmark().meta_info(0).key());
  EXPECT_EQ("V", entity.specifics().bookmark().meta_info(0).value());

  bm_cc->CleanUp();
}

// Test that bookmarks support hierarchy.
TEST_F(DirectoryCommitContributionTest, HierarchySupport_Bookmark) {
  // Create a normal-looking bookmark item.
  int64_t bm1;
  {
    syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir());
    bm1 = CreateSyncedItem(&trans, BOOKMARKS, "bm1");
    syncable::MutableEntry e(&trans, syncable::GET_BY_HANDLE, bm1);

    sync_pb::EntitySpecifics specifics;
    sync_pb::BookmarkSpecifics* bm_specifics = specifics.mutable_bookmark();
    bm_specifics->set_url("http://www.chrome.com");
    bm_specifics->set_title("Chrome");
    e.PutSpecifics(specifics);

    e.PutIsDel(false);
    e.PutIsUnsynced(true);

    EXPECT_TRUE(e.ShouldMaintainHierarchy());
  }

  DirectoryTypeDebugInfoEmitter emitter(BOOKMARKS, &type_observers_);
  std::unique_ptr<DirectoryCommitContribution> bm_cc(
      DirectoryCommitContribution::Build(dir(), BOOKMARKS, 25, &emitter));

  sync_pb::ClientToServerMessage message;
  bm_cc->AddToCommitMessage(&message);
  const sync_pb::CommitMessage& commit_message = message.commit();
  bm_cc->CleanUp();

  ASSERT_EQ(1, commit_message.entries_size());
  EXPECT_TRUE(commit_message.entries(0).has_parent_id_string());
  EXPECT_FALSE(commit_message.entries(0).parent_id_string().empty());
}

// Test that preferences do not support hierarchy.
TEST_F(DirectoryCommitContributionTest, HierarchySupport_Preferences) {
  // Create a normal-looking prefs item.
  int64_t pref1;
  {
    syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir());
    pref1 = CreateUnsyncedItem(&trans, PREFERENCES, "pref1");
    syncable::MutableEntry e(&trans, syncable::GET_BY_HANDLE, pref1);

    EXPECT_FALSE(e.ShouldMaintainHierarchy());
  }

  DirectoryTypeDebugInfoEmitter emitter(PREFERENCES, &type_observers_);
  std::unique_ptr<DirectoryCommitContribution> pref_cc(
      DirectoryCommitContribution::Build(dir(), PREFERENCES, 25, &emitter));

  sync_pb::ClientToServerMessage message;
  pref_cc->AddToCommitMessage(&message);
  const sync_pb::CommitMessage& commit_message = message.commit();
  pref_cc->CleanUp();

  ASSERT_EQ(1, commit_message.entries_size());
  EXPECT_FALSE(commit_message.entries(0).has_parent_id_string());
  EXPECT_TRUE(commit_message.entries(0).parent_id_string().empty());
}

void AddAttachment(sync_pb::AttachmentMetadata* metadata, bool is_on_server) {
  sync_pb::AttachmentMetadataRecord record;
  *record.mutable_id() = CreateAttachmentIdProto(0, 0);
  record.set_is_on_server(is_on_server);
  *metadata->add_record() = record;
}

// Creates some unsynced items, pretends to commit them, and hands back a
// specially crafted response to the syncer in order to test commit response
// processing.  The response simulates a succesful commit scenario.
TEST_F(DirectoryCommitContributionTest, ProcessCommitResponse) {
  int64_t pref1_handle;
  int64_t pref2_handle;
  int64_t ext1_handle;
  {
    syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir());
    pref1_handle = CreateUnsyncedItem(&trans, PREFERENCES, "pref1");
    pref2_handle = CreateUnsyncedItem(&trans, PREFERENCES, "pref2");
    ext1_handle = CreateUnsyncedItem(&trans, EXTENSIONS, "extension1");
  }

  DirectoryTypeDebugInfoEmitter emitter1(PREFERENCES, &type_observers_);
  DirectoryTypeDebugInfoEmitter emitter2(EXTENSIONS, &type_observers_);
  std::unique_ptr<DirectoryCommitContribution> pref_cc(
      DirectoryCommitContribution::Build(dir(), PREFERENCES, 25, &emitter1));
  std::unique_ptr<DirectoryCommitContribution> ext_cc(
      DirectoryCommitContribution::Build(dir(), EXTENSIONS, 25, &emitter2));

  sync_pb::ClientToServerMessage message;
  pref_cc->AddToCommitMessage(&message);
  ext_cc->AddToCommitMessage(&message);

  const sync_pb::CommitMessage& commit_message = message.commit();
  ASSERT_EQ(3, commit_message.entries_size());

  sync_pb::ClientToServerResponse response;
  for (int i = 0; i < commit_message.entries_size(); ++i) {
    sync_pb::SyncEntity entity = commit_message.entries(i);
    sync_pb::CommitResponse_EntryResponse* entry_response =
        response.mutable_commit()->add_entryresponse();
    CreateSuccessfulCommitResponse(entity, entry_response);
  }

  sessions::StatusController status;

  // Process these in reverse order.  Just because we can.
  ext_cc->ProcessCommitResponse(response, &status);
  pref_cc->ProcessCommitResponse(response, &status);

  {
    syncable::ReadTransaction trans(FROM_HERE, dir());
    syncable::Entry p1(&trans, syncable::GET_BY_HANDLE, pref1_handle);
    EXPECT_TRUE(p1.GetId().ServerKnows());
    EXPECT_FALSE(p1.GetSyncing());
    EXPECT_FALSE(p1.GetDirtySync());
    EXPECT_LT(0, p1.GetServerVersion());

    syncable::Entry p2(&trans, syncable::GET_BY_HANDLE, pref2_handle);
    EXPECT_TRUE(p2.GetId().ServerKnows());
    EXPECT_FALSE(p2.GetSyncing());
    EXPECT_FALSE(p2.GetDirtySync());
    EXPECT_LT(0, p2.GetServerVersion());

    syncable::Entry e1(&trans, syncable::GET_BY_HANDLE, ext1_handle);
    EXPECT_TRUE(e1.GetId().ServerKnows());
    EXPECT_FALSE(e1.GetSyncing());
    EXPECT_FALSE(e1.GetDirtySync());
    EXPECT_LT(0, e1.GetServerVersion());
  }

  pref_cc->CleanUp();
  ext_cc->CleanUp();
}

// Creates some unsynced items with attachments and verifies that only items
// where all attachments have been uploaded to the server are eligible to be
// committed.
TEST_F(DirectoryCommitContributionTest, ProcessCommitResponseWithAttachments) {
  int64_t art1_handle;
  int64_t art2_handle;
  int64_t art3_handle;
  {
    syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir());

    // art1 has two attachments, both have been uploaded to the server.  art1 is
    // eligible to be committed.
    sync_pb::AttachmentMetadata art1_attachments;
    AddAttachment(&art1_attachments, true /* is_on_server */);
    AddAttachment(&art1_attachments, true /* is_on_server */);
    art1_handle = CreateUnsyncedItemWithAttachments(&trans, ARTICLES, "art1",
                                                    art1_attachments);

    // art2 has two attachments, one of which has been uploaded to the
    // server. art2 is not eligible to be committed.
    sync_pb::AttachmentMetadata art2_attachments;
    AddAttachment(&art2_attachments, false /* is_on_server */);
    AddAttachment(&art2_attachments, true /* is_on_server */);
    art2_handle = CreateUnsyncedItemWithAttachments(&trans, ARTICLES, "art2",
                                                    art2_attachments);

    // art3 has two attachments, neither of which have been uploaded to the
    // server. art2 is not eligible to be committed.
    sync_pb::AttachmentMetadata art3_attachments;
    AddAttachment(&art3_attachments, false /* is_on_server */);
    AddAttachment(&art3_attachments, false /* is_on_server */);
    art3_handle = CreateUnsyncedItemWithAttachments(&trans, ARTICLES, "art3",
                                                    art3_attachments);
  }

  DirectoryTypeDebugInfoEmitter emitter(ARTICLES, &type_observers_);
  std::unique_ptr<DirectoryCommitContribution> art_cc(
      DirectoryCommitContribution::Build(dir(), ARTICLES, 25, &emitter));

  // Only art1 is ready.
  EXPECT_EQ(1U, art_cc->GetNumEntries());

  sync_pb::ClientToServerMessage message;
  art_cc->AddToCommitMessage(&message);

  const sync_pb::CommitMessage& commit_message = message.commit();
  ASSERT_EQ(1, commit_message.entries_size());

  sync_pb::ClientToServerResponse response;
  for (int i = 0; i < commit_message.entries_size(); ++i) {
    sync_pb::SyncEntity entity = commit_message.entries(i);
    sync_pb::CommitResponse_EntryResponse* entry_response =
        response.mutable_commit()->add_entryresponse();
    CreateSuccessfulCommitResponse(entity, entry_response);
  }

  sessions::StatusController status;
  art_cc->ProcessCommitResponse(response, &status);
  {
    syncable::ReadTransaction trans(FROM_HERE, dir());

    syncable::Entry a1(&trans, syncable::GET_BY_HANDLE, art1_handle);
    EXPECT_TRUE(a1.GetId().ServerKnows());
    EXPECT_FALSE(a1.GetSyncing());
    EXPECT_FALSE(a1.GetDirtySync());
    EXPECT_LT(0, a1.GetServerVersion());

    syncable::Entry a2(&trans, syncable::GET_BY_HANDLE, art2_handle);
    EXPECT_FALSE(a2.GetId().ServerKnows());
    EXPECT_FALSE(a2.GetSyncing());
    EXPECT_FALSE(a2.GetDirtySync());
    EXPECT_EQ(0, a2.GetServerVersion());

    syncable::Entry a3(&trans, syncable::GET_BY_HANDLE, art3_handle);
    EXPECT_FALSE(a3.GetId().ServerKnows());
    EXPECT_FALSE(a3.GetSyncing());
    EXPECT_FALSE(a3.GetDirtySync());
    EXPECT_EQ(0, a3.GetServerVersion());
  }

  art_cc->CleanUp();
}

}  // namespace syncer


text:
package org.drools.guvnor.client.widgets.tables;

import java.util.Date;

import org.drools.guvnor.client.common.GenericCallback;
import org.drools.guvnor.client.resources.RuleFormatImageResource;
import org.drools.guvnor.client.rpc.PageResponse;
import org.drools.guvnor.client.rpc.StatePageRequest;
import org.drools.guvnor.client.rpc.StatePageRow;
import org.drools.guvnor.client.ruleeditor.EditorLauncher;
import org.drools.guvnor.client.rulelist.OpenItemCommand;
import org.drools.guvnor.client.widgets.tables.TitledTextCell.TitledText;

import com.google.gwt.cell.client.DateCell;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;

/**
 * Widget with a table of "By State" query results.
 */
public class StatePagedTable extends AbstractAssetPagedTable<StatePageRow> {

    private static final int PAGE_SIZE = 10;

    /**
     * Constructor
     *
     * @param stateName
     * @param editEvent
     */
    public StatePagedTable(
                           final String stateName,
                           final OpenItemCommand editEvent) {
        super( PAGE_SIZE,
               editEvent );
        setDataProvider( new AsyncDataProvider<StatePageRow>() {
            protected void onRangeChanged(HasData<StatePageRow> display) {
                StatePageRequest request = new StatePageRequest();
                request.setStateName( stateName );
                request.setStartRowIndex( pager.getPageStart() );
                request.setPageSize( pageSize );
                repositoryService.loadRuleListForState( request,
                                                        new GenericCallback<PageResponse<StatePageRow>>() {
                                                            public void onSuccess(PageResponse<StatePageRow> response) {
                                                                updateRowCount( response.getTotalRowSize(),
                                                                                response.isTotalRowSizeExact() );
                                                                updateRowData( response.getStartRowIndex(),
                                                                               response.getPageRowList() );
                                                            }
                                                        } );
            }
        } );
    }

    @Override
    protected void addAncillaryColumns(ColumnPicker<StatePageRow> columnPicker,
                                       SortableHeaderGroup<StatePageRow> sortableHeaderGroup) {

        Column<StatePageRow, RuleFormatImageResource> formatColumn = new Column<StatePageRow, RuleFormatImageResource>( new RuleFormatImageResourceCell() ) {

            public RuleFormatImageResource getValue(StatePageRow row) {
                return EditorLauncher.getAssetFormatIcon( row.getFormat() );
            }
        };
        columnPicker.addColumn( formatColumn,
                                new SortableHeader<StatePageRow, RuleFormatImageResource>(
                                                                                sortableHeaderGroup,
                                                                                constants.Format(),
                                                                                formatColumn ),
                                true );

        TitledTextColumn<StatePageRow> titleColumn = new TitledTextColumn<StatePageRow>() {
            public TitledText getValue(StatePageRow row) {
                TitledText tt = new TitledText( row.getName(),
                                                row.getAbbreviatedDescription() );
                return tt;
            }
        };
        columnPicker.addColumn( titleColumn,
                                new SortableHeader<StatePageRow, TitledText>(
                                                                              sortableHeaderGroup,
                                                                              constants.Name(),
                                                                              titleColumn ),
                                true );

        TextColumn<StatePageRow> packageNameColumn = new TextColumn<StatePageRow>() {
            public String getValue(StatePageRow row) {
                return row.getPackageName();
            }
        };
        columnPicker.addColumn( packageNameColumn,
                                new SortableHeader<StatePageRow, String>(
                                                                          sortableHeaderGroup,
                                                                          constants.PackageName(),
                                                                          packageNameColumn ),
                                true );

        TextColumn<StatePageRow> statusNameColumn = new TextColumn<StatePageRow>() {
            public String getValue(StatePageRow row) {
                return row.getStateName();
            }
        };
        columnPicker.addColumn( statusNameColumn,
                                new SortableHeader<StatePageRow, String>(
                                                                          sortableHeaderGroup,
                                                                          constants.Status(),
                                                                          statusNameColumn ),
                                true );

        Column<StatePageRow, Date> lastModifiedColumn = new Column<StatePageRow, Date>( new
                                                                                DateCell(
                                                                                DateTimeFormat.getFormat(
                                                                                DateTimeFormat.PredefinedFormat.DATE_TIME_MEDIUM ) ) ) {
            public Date getValue(StatePageRow row) {
                return row.getLastModified();
            }
        };
        columnPicker.addColumn( lastModifiedColumn,
                                new SortableHeader<StatePageRow, Date>(
                                                                        sortableHeaderGroup,
                                                                        constants.LastModified(),
                                                                        lastModifiedColumn ),
                                true );
    }

}


text:
enfig
=====

Sets environment `ENV[]` values from a YAML file.

## Why?

When a project starts growing so does it settings. After a while you end up with multiple
YAML files, one for each component, and it becomes hard to manage.

This gem lets you group all of your project settings into one YAML file in your project.
It then adds the settings to the ENV, so that you can use the `ENV[key]` in your code.

## Installation

Install the gem by adding it to  your `Gemfile`

`gem 'enfig', '~> 1.0.0'`

Then just simply call the `::load!` method, anywhere in your application.

### Rails

For Rails applications add the following snippet at the bottom of the `config/boot.rb` file.

```ruby
# config/boot.rb
require 'enfig'
Enfig.load! File.expand_path('../project.yml', __FILE__)
```

Replace `project.yml` with the name of your configuration file.

## API

The `::load!` methods take the filename as the first parameter and an optional hash as a second
parameter.

`Enfig.load!(filename:String, [options:Hash])`

### Options

**root** *[String, Symbol]*
*Default: nil*
The key to consider as the root of the configuration values. This is useful when working with multiple environments.

**prefix** *[String]*
*Default: nil*
The prefix for the environment keys.

**separator** *[String]*
*Default: '_'*
The separator to use when flattening the key of nested hashes.

**overwrite** *[Boolean]*
*Default: false*
Indicates if the existing `ENV[]` values can be overwritten.

### Example

```YAML
    # config/project.yml

    # Thanks to YAML you can reuse pieces of your configuration

    database: &database
      adapter: postgresql
      host: localhost
      database: project_db
      username: db_user
      password: abcdefg123456

    development:
      database:
        <<: *database

    production:
      database:
        <<: *database
        host: server.example.com
        password: seriouspassword
```

```ruby
Enfig.load! 'project.yml', root: :production, prefix: 'app', separator: '/', overwrite: true
```

Will result in setting the following ENV values.

```ruby
ENV['APP/DATABASE/ADAPTER']  = 'postgresql'
ENV['APP/DATABASE/HOST']     = 'server.example.com'
ENV['APP/DATABASE/DATABASE'] = 'project_db'
ENV['APP/DATABASE/USERNAME'] = 'db_user'
ENV['APP/DATABASE/PASSWORD'] = 'seriouspassword'
```

*Note: How the configuration hash results in the keys being  prefixed with `APP` and joined with a '/' separator*