text:
title: 'Slack tracking in V8'
author: 'Michael Stanton ([@alpencoder](https://twitter.com/alpencoder)), renowned master of *slack*'
description: 'A detailed look into the V8 slack tracking mechanism.'
avatars:
 - 'michael-stanton'
date: 2020-09-24 14:00:00
tags:
 - internals
---
Slack tracking is a way to give new objects an initial size that is **larger than what they may actually use**, so they can have new properties added quickly. And then, after some period of time, to **magically return that unused space to the system**. Neat, huh?

It's especially useful because JavaScript doesn't have static classes. The system can never see "at a glance" how many properties you have. The engine experiences them one by one. So when you read:

```js
function Peak(name, height) {
  this.name = name;
  this.height = height;
}

const m1 = new Peak('Matterhorn', 4478);
```

You might think the engine has all it needs to perform well — you've told it the object has two properties, after all. However, V8 really has no idea what will come next. This object `m1` could be passed to another function that adds 10 more properties to it. Slack tracking comes out of this need to be responsive to whatever comes next in an environment without static compilation to infer overall structure. It's like many other mechanisms in V8, whose basis is only things you can generally say about execution, like:

- Most objects die soon, few live long — the garbage collection "generational hypothesis".
- The program does indeed have an organizational structure — we build [shapes or "hidden classes"](https://mathiasbynens.be/notes/shapes-ics) (we call these **maps** in V8) into the objects we see the programmer uses because we believe they will be useful. *BTW, [Fast Properties in V8](/blog/fast-properties) is a great post with interesting details about maps and property access.*
- Programs have an initialization state, when everything is new and it's hard to tell what's important. Later, the important classes and functions can be identified through their steady use — our feedback regime and compiler pipeline grow out of this idea.

Finally, and most importantly, the runtime environment must be very fast, otherwise we're just philosophizing.

Now, V8 could simply store properties in a backing store attached to the main object. Unlike properties that live directly in the object, this backing store can grow indefinitely through copying and replacing the pointer. However the fastest access to a property comes by avoiding that indirection and looking at a fixed offset from the start of the object. Below, I show the layout of a plain ol' JavaScript object in the V8 heap with two in-object properties. The first three words are standard in every object (a pointer to the map, to the properties backing store, and to the elements backing store). You can see that the object can't "grow" because it's hard up against the next object in the heap:

![](/_img/slack-tracking/property-layout.svg)

:::note
**Note:** I left out the details of the property backing store because the only thing important about it for the moment is that it can be replaced at any time with a larger one. However, it too is an object on the V8 heap and has a map pointer like all objects that reside there.
:::

So anyway, because of the performance provided by in-object properties, V8 is willing to give you extra space in each object, and **slack tracking** is the way it's done. Eventually, you'll settle down, stop adding new properties, and get down to the business of mining bitcoin or whatever.

How much "time" does V8 give you? Cleverly, it considers the number of times you've constructed a particular object. In fact, there is a counter in the map, and it's initialized with one of the more mystical magic numbers in the system: **seven**.

Another question: how does V8 know how much extra space in the object body to provide? It actually gets a hint from the compilation process, which offers an estimated number of properties to start with. This calculation includes the number of properties from the prototype object, going up the chain of prototypes recursively. Finally, for good measure it adds **eight** more (another magic number!). You can see this in `JSFunction::CalculateExpectedNofProperties()`:

```cpp
int JSFunction::CalculateExpectedNofProperties(Isolate* isolate,
                                               Handle<JSFunction> function) {
  int expected_nof_properties = 0;
  for (PrototypeIterator iter(isolate, function, kStartAtReceiver);
       !iter.IsAtEnd(); iter.Advance()) {
    Handle<JSReceiver> current =
        PrototypeIterator::GetCurrent<JSReceiver>(iter);
    if (!current->IsJSFunction()) break;
    Handle<JSFunction> func = Handle<JSFunction>::cast(current);

    // The super constructor should be compiled for the number of expected
    // properties to be available.
    Handle<SharedFunctionInfo> shared(func->shared(), isolate);
    IsCompiledScope is_compiled_scope(shared->is_compiled_scope(isolate));
    if (is_compiled_scope.is_compiled() ||
        Compiler::Compile(func, Compiler::CLEAR_EXCEPTION,
                          &is_compiled_scope)) {
      DCHECK(shared->is_compiled());
      int count = shared->expected_nof_properties();
      // Check that the estimate is sensible.
      if (expected_nof_properties <= JSObject::kMaxInObjectProperties - count) {
        expected_nof_properties += count;
      } else {
        return JSObject::kMaxInObjectProperties;
      }
    } else {
      // In case there was a compilation error proceed iterating in case there
      // will be a builtin function in the prototype chain that requires
      // certain number of in-object properties.
      continue;
    }
  }
  // In-object slack tracking will reclaim redundant inobject space
  // later, so we can afford to adjust the estimate generously,
  // meaning we over-allocate by at least 8 slots in the beginning.
  if (expected_nof_properties > 0) {
    expected_nof_properties += 8;
    if (expected_nof_properties > JSObject::kMaxInObjectProperties) {
      expected_nof_properties = JSObject::kMaxInObjectProperties;
    }
  }
  return expected_nof_properties;
}
```

Let's have a look at our object `m1` from before:

```js
function Peak(name, height) {
  this.name = name;
  this.height = height;
}

const m1 = new Peak('Matterhorn', 4478);
```

By the calculation in `JSFunction::CalculateExpectedNofProperties` and our `Peak()` function, we should have 2 in-object properties, and thanks to slack tracking, another 8 extra. We can print `m1` with `%DebugPrint()` (_this handy function exposes the map structure. You can use it by running `d8` with the flag `--allow-natives-syntax`_):

```
> %DebugPrint(m1);
DebugPrint: 0x49fc866d: [JS_OBJECT_TYPE]
 - map: 0x58647385 <Map(HOLEY_ELEMENTS)> [FastProperties]
 - prototype: 0x49fc85e9 <Object map = 0x58647335>
 - elements: 0x28c821a1 <FixedArray[0]> [HOLEY_ELEMENTS]
 - properties: 0x28c821a1 <FixedArray[0]> {
    0x28c846f9: [String] in ReadOnlySpace: #name: 0x5e412439 <String[10]: #Matterhorn> (const data field 0)
    0x5e412415: [String] in OldSpace: #height: 4478 (const data field 1)
 }
  0x58647385: [Map]
 - type: JS_OBJECT_TYPE
 - instance size: 52
 - inobject properties: 10
 - elements kind: HOLEY_ELEMENTS
 - unused property fields: 8
 - enum length: invalid
 - stable_map
 - back pointer: 0x5864735d <Map(HOLEY_ELEMENTS)>
 - prototype_validity cell: 0x5e4126fd <Cell value= 0>
 - instance descriptors (own) #2: 0x49fc8701 <DescriptorArray[2]>
 - prototype: 0x49fc85e9 <Object map = 0x58647335>
 - constructor: 0x5e4125ed <JSFunction Peak (sfi = 0x5e4124dd)>
 - dependent code: 0x28c8212d <Other heap object (WEAK_FIXED_ARRAY_TYPE)>
 - construction counter: 6
```

Note the instance size of the object is 52. Object layout in V8 is like so:

| word | what                                                 |
| ---- | ---------------------------------------------------- |
| 0    | the map                                              |
| 1    | pointer to the properties array                      |
| 2    | pointer to the elements array                        |
| 3    | in-object field 1 (pointer to string `"Matterhorn"`) |
| 4    | in-object field 2 (integer value `4478`)             |
| 5    | unused in-object field 3                             |
| …    | …                                                    |
| 12   | unused in-object field 10                            |

Pointer size is 4 in this 32-bit binary, so we've got those 3 initial words that every ordinary JavaScript object has, and then 10 extra words in the object. It tells us above, helpfully, that there are 8 "unused property fields". So, we are experiencing slack tracking. Our objects are bloated, greedy consumers of precious bytes!

How do we slim down? We use the construction counter field in the map. We reach zero and then decide we are done with slack tracking. However, if you construct more objects, you won't see the counter above decreasing. Why?

Well, it's because the map displayed above is not "the" map for a `Peak` object. It's only a leaf map in a chain of maps descending from the **initial map** that the `Peak` object is given before executing the constructor code.

How to find the initial map? Happily, the function `Peak()` has a pointer to it. It's the construction counter in the initial map that we use to control slack tracking:

```
> %DebugPrint(Peak);
d8> %DebugPrint(Peak)
DebugPrint: 0x31c12561: [Function] in OldSpace
 - map: 0x2a2821f5 <Map(HOLEY_ELEMENTS)> [FastProperties]
 - prototype: 0x31c034b5 <JSFunction (sfi = 0x36108421)>
 - elements: 0x28c821a1 <FixedArray[0]> [HOLEY_ELEMENTS]
 - function prototype: 0x37449c89 <Object map = 0x2a287335>
 - initial_map: 0x46f07295 <Map(HOLEY_ELEMENTS)>   // Here's the initial map.
 - shared_info: 0x31c12495 <SharedFunctionInfo Peak>
 - name: 0x31c12405 <String[4]: #Peak>
…

d8> // %DebugPrintPtr allows you to print the initial map.
d8> %DebugPrintPtr(0x46f07295)
DebugPrint: 0x46f07295: [Map]
 - type: JS_OBJECT_TYPE
 - instance size: 52
 - inobject properties: 10
 - elements kind: HOLEY_ELEMENTS
 - unused property fields: 10
 - enum length: invalid
 - back pointer: 0x28c02329 <undefined>
 - prototype_validity cell: 0x47f0232d <Cell value= 1>
 - instance descriptors (own) #0: 0x28c02135 <DescriptorArray[0]>
 - transitions #1: 0x46f0735d <Map(HOLEY_ELEMENTS)>
     0x28c046f9: [String] in ReadOnlySpace: #name:
         (transition to (const data field, attrs: [WEC]) @ Any) ->
             0x46f0735d <Map(HOLEY_ELEMENTS)>
 - prototype: 0x5cc09c7d <Object map = 0x46f07335>
 - constructor: 0x21e92561 <JSFunction Peak (sfi = 0x21e92495)>
 - dependent code: 0x28c0212d <Other heap object (WEAK_FIXED_ARRAY_TYPE)>
 - construction counter: 5
```

See how the construction counter is decremented to 5? If you'd like to find the initial map from the two-property map we showed above, you can follow its back pointer with the help of `%DebugPrintPtr()` until you reach a map with `undefined` in the back pointer slot. That will be this map above.

Now, a map tree grows from the initial map, with a branch for each property added from that point. We call these branches _transitions_. In the above printout of the initial map, do you see the transition to the next map with the label "name"? The whole map tree thus far looks like this:

![(X, Y, Z) means (instance size, number of in-object properties, number of unused properties).](/_img/slack-tracking/root-map-1.svg)

These transitions based on property names are how the ["blind mole"](https://www.google.com/search?q=blind+mole&tbm=isch)" of JavaScript builds its maps behind you. This initial map is also stored in the function `Peak`, so when it's used as a constructor, that map can be used to set up the `this` object.

```js
const m1 = new Peak('Matterhorn', 4478);
const m2 = new Peak('Mont Blanc', 4810);
const m3 = new Peak('Zinalrothorn', 4221);
const m4 = new Peak('Wendelstein', 1838);
const m5 = new Peak('Zugspitze', 2962);
const m6 = new Peak('Watzmann', 2713);
const m7 = new Peak('Eiger', 3970);
```

The cool thing here is that after creating `m7`, running `%DebugPrint(m1)` again produces a marvellous new result:

```
DebugPrint: 0x5cd08751: [JS_OBJECT_TYPE]
 - map: 0x4b387385 <Map(HOLEY_ELEMENTS)> [FastProperties]
 - prototype: 0x5cd086cd <Object map = 0x4b387335>
 - elements: 0x586421a1 <FixedArray[0]> [HOLEY_ELEMENTS]
 - properties: 0x586421a1 <FixedArray[0]> {
    0x586446f9: [String] in ReadOnlySpace: #name:
        0x51112439 <String[10]: #Matterhorn> (const data field 0)
    0x51112415: [String] in OldSpace: #height:
        4478 (const data field 1)
 }
0x4b387385: [Map]
 - type: JS_OBJECT_TYPE
 - instance size: 20
 - inobject properties: 2
 - elements kind: HOLEY_ELEMENTS
 - unused property fields: 0
 - enum length: invalid
 - stable_map
 - back pointer: 0x4b38735d <Map(HOLEY_ELEMENTS)>
 - prototype_validity cell: 0x511128dd <Cell value= 0>
 - instance descriptors (own) #2: 0x5cd087e5 <DescriptorArray[2]>
 - prototype: 0x5cd086cd <Object map = 0x4b387335>
 - constructor: 0x511127cd <JSFunction Peak (sfi = 0x511125f5)>
 - dependent code: 0x5864212d <Other heap object (WEAK_FIXED_ARRAY_TYPE)>
 - construction counter: 0
```

Our instance size is now 20, which is 5 words:

| word | what                            |
| ---- | ------------------------------- |
| 0    | the map                         |
| 1    | pointer to the properties array |
| 2    | pointer to the elements array   |
| 3    | name                            |
| 4    | height                          |

You'll wonder how this happened. After all, if this object is laid out in memory, and used to have 10 properties, how can the system tolerate these 8 words laying around with no one to own them? It's true that we never filled them with anything interesting — maybe that can help us.

If you wonder why I'm worried about leaving these words laying around, there is some background you need to know about the garbage collector. Objects are laid out one after the other, and the V8 garbage collector keeps track of things in that memory by walking over it again and again. Starting at the first word in memory, it expects to find a pointer to a map. It reads the instance size from the map and then knows how far to step forward to the next valid object. For some classes it has to additionally compute a length, but that's all there is to it.

![](/_img/slack-tracking/gc-heap-1.svg)

In the diagram above, the red boxes are the **maps**, and the white boxes the words that fill out the instance size of the object. The garbage collector can "walk" the heap by hopping from map to map.

So what happens if the map suddenly changes it's instance size? Now when the GC (garbage collector) walks the heap it will find itself looking at a word that it didn't see before. In the case of our `Peak` class, we change from taking up 13 words to only 5 (I colored the "unused property" words yellow):

![](/_img/slack-tracking/gc-heap-2.svg)

![](/_img/slack-tracking/gc-heap-3.svg)

We can deal with this if we cleverly initialize those unused properties with a **"filler" map of instance size 4**. This way, the GC will lightly walk over them once they are exposed to the traversal.

![](/_img/slack-tracking/gc-heap-4.svg)

This is expressed in the code in `Factory::InitializeJSObjectBody()`:

```cpp
void Factory::InitializeJSObjectBody(Handle<JSObject> obj, Handle<Map> map,
                                     int start_offset) {

  // <lines removed>

  bool in_progress = map->IsInobjectSlackTrackingInProgress();
  Object filler;
  if (in_progress) {
    filler = *one_pointer_filler_map();
  } else {
    filler = *undefined_value();
  }
  obj->InitializeBody(*map, start_offset, *undefined_value(), filler);
  if (in_progress) {
    map->FindRootMap(isolate()).InobjectSlackTrackingStep(isolate());
  }

  // <lines removed>
}
```

And so this is slack tracking in action. For each class you create, you can expect it to take up more memory for a while, but on the 7th instantiation we "call it good" and expose the leftover space for the GC to see. These one-word objects have no owners — that is, nobody points to them — so when a collection occurs they are freed up and living objects may be compacted to save space.

The diagram below reflects that slack tracking is **finished** for this initial map. Note that the instance size is now 20 (5 words: the map, the properties and elements arrays, and 2 more slots). Slack tracking respects the whole chain from the initial map. That is, if a descendent of the initial map ends up using all 10 of those initial extra properties, then the initial map keeps them, marking them as unused:

![(X, Y, Z) means (instance size, number of in-object properties, number of unused properties).](/_img/slack-tracking/root-map-2.svg)

Now that slack tracking is finished, what happens if we add another property to one of these `Peak` objects?

```js
m1.country = 'Switzerland';
```

V8 has to go into the properties backing store. We end up with the following object layout:

| word | value                                 |
| ---- | ------------------------------------- |
| 0    | map                                   |
| 1    | pointer to a properties backing store |
| 2    | pointer to elements (empty array)     |
| 3    | pointer to string `"Matterhorn"`      |
| 4    | `4478`                                |

The properties backing store then looks like this:

| word | value                             |
| ---- | --------------------------------- |
| 0    | map                               |
| 1    | length (3)                        |
| 2    | pointer to string `"Switzerland"` |
| 3    | `undefined`                       |
| 4    | `undefined`                       |
| 5    | `undefined`                       |

We have those extra `undefined` values there in case you decide to add more properties. We kind of think you might, based on your behavior so far!

## Optional properties

It may happen that you add properties in some cases only. Suppose if height is 4000 meters or more, you want to keep track of two additional properties, `prominence` and `isClimbed`:

```js
function Peak(name, height, prominence, isClimbed) {
  this.name = name;
  this.height = height;
  if (height >= 4000) {
    this.prominence = prominence;
    this.isClimbed = isClimbed;
  }
}
```

You add a few of these different variants:

```js
const m1 = new Peak('Wendelstein', 1838);
const m2 = new Peak('Matterhorn', 4478, 1040, true);
const m3 = new Peak('Zugspitze', 2962);
const m4 = new Peak('Mont Blanc', 4810, 4695, true);
const m5 = new Peak('Watzmann', 2713);
const m6 = new Peak('Zinalrothorn', 4221, 490, true);
const m7 = new Peak('Eiger', 3970);
```

In this case, objects `m1`, `m3`, `m5`, and `m7` have one map, and objects `m2`, `m4`, and `m6` have a map further down the chain of descendents from the initial map because of the additional properties. When slack tracking is finished for this map family, there are **4** in-object properties instead of **2** like before, because slack tracking makes sure to keep sufficient room for the maximum number of in-object properties used by any descendents in the tree of maps below the initial map.

Below shows the map family after running the code above, and of course, slack tracking is complete:

![(X, Y, Z) means (instance size, number of in-object properties, number of unused properties).](/_img/slack-tracking/root-map-3.svg)

## How about optimized code?

Let's compile some optimized code before slack tracking is finished. We'll use a couple native syntax commands to force a optimized compile to happen before we finished slack tracking:

```js
function foo(a1, a2, a3, a4) {
  return new Peak(a1, a2, a3, a4);
}

%PrepareFunctionForOptimization(foo);
const m1 = foo('Wendelstein', 1838);
const m2 = foo('Matterhorn', 4478, 1040, true);
%OptimizeFunctionOnNextCall(foo);
foo('Zugspitze', 2962);
```

That should be enough to compile and run optimized code. We do something in TurboFan (the optimizing compiler) called [**Create Lowering**](https://source.chromium.org/chromium/chromium/src/+/master:v8/src/compiler/js-create-lowering.h;l=32;drc=ee9e7e404e5a3f75a3ca0489aaf80490f625ca27), where we inline the allocation of objects. That means the native code we produce emits instructions to ask the GC for the instance size of the object to allocate and then carefully initialize those fields. However, this code would be invalid if slack tracking were to stop at some later point. What can we do about that?

Easy-peasy! We just end slack tracking early for this map family. This makes sense because normally — we wouldn't compile an optimized function until thousands of objects have been created. So slack tracking *should* be finished. If it's not, too bad! The object must not be that important anyway if fewer than 7 of them have been created by this point. (Normally, remember, we are only optimizing after the program ran for a long time.)

### Compiling on a background thread

We can compile optimized code on the main thread, in which case we can get away with prematurely ending slack tracking with some calls to change the initial map because the world has been stopped. However, we do as much compilation as possible on a background thread. From this thread it would be dangerous to touch the initial map because it *might be changing on the main thread where JavaScript is running.* So our technique goes like this:

1. **Guess** that the instance size will be what it would be if you did stop slack tracking right now. Remember this size.
1. When the compilation is almost done, we return to the main thread where we can safely force completion of slack tracking if it wasn't already done.
1. Check: is the instance size what we predicted? If so, **we are good!** If not, throw away the code object and try again later.

If you'd like to see this in code, have a look at the class [`InitialMapInstanceSizePredictionDependency`](https://source.chromium.org/chromium/chromium/src/+/master:v8/src/compiler/compilation-dependencies.cc?q=InitialMapInstanceSizePredictionDependency&ss=chromium%2Fchromium%2Fsrc) and how it's used in `js-create-lowering.cc` to create inline allocations. You'll see that the `PrepareInstall()` method is called on the main thread, which forces completion of slack tracking. Then method `Install()` checks if our guess on the instance size held up.

Here is the optimized code with the inlined allocation. First you see communication with the GC, checking to see if we can just bump a pointer forward by the instance size and take that (this is called bump-pointer allocation). Then, we start filling in fields of the new object:

```asm
…
43  mov ecx,[ebx+0x5dfa4]
49  lea edi,[ecx+0x1c]
4c  cmp [ebx+0x5dfa8],edi       ;; hey GC, can we have 28 (0x1c) bytes please?
52  jna 0x36ec4a5a  <+0x11a>

58  lea edi,[ecx+0x1c]
5b  mov [ebx+0x5dfa4],edi       ;; okay GC, we took it. KThxbye.
61  add ecx,0x1                 ;; hells yes. ecx is my new object.
64  mov edi,0x46647295          ;; object: 0x46647295 <Map(HOLEY_ELEMENTS)>
69  mov [ecx-0x1],edi           ;; Store the INITIAL MAP.
6c  mov edi,0x56f821a1          ;; object: 0x56f821a1 <FixedArray[0]>
71  mov [ecx+0x3],edi           ;; Store the PROPERTIES backing store (empty)
74  mov [ecx+0x7],edi           ;; Store the ELEMENTS backing store (empty)
77  mov edi,0x56f82329          ;; object: 0x56f82329 <undefined>
7c  mov [ecx+0xb],edi           ;; in-object property 1 <-- undefined
7f  mov [ecx+0xf],edi           ;; in-object property 2 <-- undefined
82  mov [ecx+0x13],edi          ;; in-object property 3 <-- undefined
85  mov [ecx+0x17],edi          ;; in-object property 4 <-- undefined
88  mov edi,[ebp+0xc]           ;; retrieve argument {a1}
8b  test_w edi,0x1
90  jz 0x36ec4a6d  <+0x12d>
96  mov eax,0x4664735d          ;; object: 0x4664735d <Map(HOLEY_ELEMENTS)>
9b  mov [ecx-0x1],eax           ;; push the map forward
9e  mov [ecx+0xb],edi           ;; name = {a1}
a1  mov eax,[ebp+0x10]          ;; retrieve argument {a2}
a4  test al,0x1
a6  jnz 0x36ec4a77  <+0x137>
ac  mov edx,0x46647385          ;; object: 0x46647385 <Map(HOLEY_ELEMENTS)>
b1  mov [ecx-0x1],edx           ;; push the map forward
b4  mov [ecx+0xf],eax           ;; height = {a2}
b7  cmp eax,0x1f40              ;; is height >= 4000?
bc  jng 0x36ec4a32  <+0xf2>
                  -- B8 start --
                  -- B9 start --
c2  mov edx,[ebp+0x14]          ;; retrieve argument {a3}
c5  test_b dl,0x1
c8  jnz 0x36ec4a81  <+0x141>
ce  mov esi,0x466473ad          ;; object: 0x466473ad <Map(HOLEY_ELEMENTS)>
d3  mov [ecx-0x1],esi           ;; push the map forward
d6  mov [ecx+0x13],edx          ;; prominence = {a3}
d9  mov esi,[ebp+0x18]          ;; retrieve argument {a4}
dc  test_w esi,0x1
e1  jz 0x36ec4a8b  <+0x14b>
e7  mov edi,0x466473d5          ;; object: 0x466473d5 <Map(HOLEY_ELEMENTS)>
ec  mov [ecx-0x1],edi           ;; push the map forward to the leaf map
ef  mov [ecx+0x17],esi          ;; isClimbed = {a4}
                  -- B10 start (deconstruct frame) --
f2  mov eax,ecx                 ;; get ready to return this great Peak object!
…
```

BTW, to see all this you should have a debug build and pass a few flags. I put the code into a file and called:

```bash
./d8 --allow-natives-syntax --trace-opt --code-comments --print-opt-code mycode.js
```

I hope this has been a fun exploration. I'd like to say a very special thanks to Igor Sheludko and Maya Armyanova for (patiently!) reviewing this post.


text:
<TITLE>Review for Misérables, Les (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Misérables, Les (1998)

reviewed by
Harvey S. Karten

LES MISERABLES

 Reviewed by Harvey Karten, Ph.D.
 Columbia Pictures
 Director: Bille August
 Writer: Rafael Yglesias from Victor Hugos' novel
 Cast:Liam Neeson, Geoffrey Rush, Uma Thurman, Claire
Danes, Hans Matheson

   A short while ago a woman was put to death in Texas for
the brutal pickax murder of two people.  The execution
followed world-wide protests in favor of clemency, not simply
because she was a woman but because she had reformed so
much during her long years on death row.  She had become
a kind, generous, born-again Christian, a pale shadow of her
former ruthless self, a transformation which led some to insist
that Texas would not be executing the same person. Even
more significant was the contention by another large block of
people that she was a fake: that human nature does not
change.

   Can human nature change?  Jean Valjean, the hero of
Victor Hugo's epic "Les Miserables," said himself that "the
world has not changed," and indeed, if we look around us we
find the planet is still teeming with poverty, homelessness,
vindictiveness as well as with examples of kindness,
generosity, and good will.  This is what gives "Les Miserables"
its contemporary appeal.  But if Valjean meant that the
individual cannot change, he was dead wrong as he proves
himself during the twenty-year span of the story.  Valjean is
changed by love--the respect accorded him by a bishop from
whom he stole; the affection he felt for a young prostitute; and
most of all for the adoration given him by an eight-year-old
girl whom he cared for over the course of two decades.  But
not everyone changes: Javert, the principal villain of this tale-
of-many-characters, is himself brutalized by his environment
and takes on an anal-retentive obsession with duty.  He is the
quintessential go-by-the-book creep.  The twenty-year
struggle between the miserly Javert and the beneficent
Valjean is probably what gives the story a universal appeal
that has made it popular throughout the world, has led to a
long-running Broadway musical, and has been the subject of
four films, featuring greats like Fredric March, Charles
Laughton, Michael Rennie, Gino Cervi, Jean Gabin, Richard
Jordan, Jean-Paul Belmondo, and now Liam Neeson.

   The current offering helmed by Bille August differs from the
1995 Claude Lelouch in that Lelouch framed the story by
placing it into a 20th-century landscape, ending in a story of
France during World War II.  In that, Belmondo is a simple
man who becomes like Jean Valjean as he helps a Jewish
family fleeing from the Nazis.  Lelouch wanted to impress us
with the impact that a single good man can have on the lives
of the people around him.  August's version is more
straightforward and suffers, by comparison, for its didacticism.
Better suited for a high-school class of kids with no prior
knowledge of the narrative, this "Les Miserables" telescopes
the long social chronicle into a relatively brief 129 minutes
(Lelouch used 178) and spells out each detail so plainly that
the most classics-hating pupil would be able to follow--if not to
love--the adventure.  The photography is as direct as the
story is straight, in no way emulating the gauzy effects of a
Merchant-Ivory work.

   "Les Miserables" is a Dickensian tale which uses the
downtrodden people of Paris as a backdrop to its central,
moral narrative.  Bille August's version ignores the opening
scenes of the novel which shows Jean Valjean (Liam Neeson)
stealing a loaf of bread, gaining a five-year sentence, and
then having the penalty upped to nineteen after an escape
attempt.  We do witness his visit to the kind bishop who
allows him the use of his home and food and refuses to turn
him in when Valjean is picked up for stealing the old man's
silverware.  Much of the tale is a detective drama, featuring
the pursuit by the reformed Valjean by the obsessed police
inspector Javert (Geoffrey Rush), as Javert believes that a
depraved man will always be depraved and dangerous and
insists on apprehending Valjean.  Valjean becomes rich when
he invents a way to use jet for jewelry (also not shown in the
movie) and uses his wealth to better the lives of the workers
in his factory.  His life takes on much greater meaning when
he adopts the eight-year-old Cosette after the death of her
mother, Fantine (Uma Thurman), and while the Javert-Valjean
chase goes on, Valjean does not reveal to his charge that he
is not her real father.

   The beady-eyed Geoffrey Rush, who turned in a stunning
performance as a disturbed concert pianist in "Shine," rises to
the occasion as a man who is also disturbed, but is unable to
release his full energies because of the limitations of Rafael
Yglesias's pedantic screenplay.  Neeson is better able to
overcome the weakness of the script by his powerful
presence, though the tremendous love he feels for Cosette
does not really come across.

   This "Les Miserables" is a fine text for helping students in
French Literature 101 but falls short of engaging the senses
the way a momentous melodrama of this caliber should.
Rated PG-13.  Running time: 129 minutes.  (C) Harvey
Karten 1998

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

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

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

Broken URLs inthe reviews are the responsibility of the author.

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

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

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<title>cowboy.js</title>

Input File

			Simple test (default Options : >=4Ko & <=5Mo)
			<input type="file" id="simple-test" name="simple-test" />

			Test with options (PDF, >=100 ko & <=5Mo)
			<input type="file" id="test-options" name="test-options" />

			Test with options passed by element properties (JPG, >=100ko & <=3Mo)
			<input type="file" id="test-options-properties" name="test-options-properties"
				data-minSize="100000" data-maxSize="3000000" data-requiredType="image/jpeg" />


text:
package leap

import (
	"errors"
	"io"
	"testing"

	"gobot.io/x/gobot"
	"gobot.io/x/gobot/gobottest"
)

var _ gobot.Adaptor = (*Adaptor)(nil)

func initTestLeapMotionAdaptor() *Adaptor {
	a := NewAdaptor("")
	a.connect = func(port string) (io.ReadWriteCloser, error) { return nil, nil }
	return a
}

func TestLeapMotionAdaptor(t *testing.T) {
	a := NewAdaptor("127.0.0.1")
	gobottest.Assert(t, a.Port(), "127.0.0.1")
}
func TestLeapMotionAdaptorConnect(t *testing.T) {
	a := initTestLeapMotionAdaptor()
	gobottest.Assert(t, a.Connect(), nil)

	a.connect = func(port string) (io.ReadWriteCloser, error) {
		return nil, errors.New("connection error")
	}
	gobottest.Assert(t, a.Connect(), errors.New("connection error"))
}

func TestLeapMotionAdaptorFinalize(t *testing.T) {
	a := initTestLeapMotionAdaptor()
	gobottest.Assert(t, a.Finalize(), nil)
}


text:
import sys

from mpf.tests.MpfBcpTestCase import MpfBcpTestCase
from unittest.mock import create_autospec, patch, MagicMock

class TestServiceCli(MpfBcpTestCase):

    def get_config_file(self):
        return 'config.yaml'

    def get_machine_path(self):
        return 'tests/machine_files/service_mode/'

    def _table(self, data):
        result = ""
        for row in data:
            for col in row:
                result += str(col) + ";"
            result += "\n"
        obj = MagicMock()
        obj.table = result[:-1]
        return obj

    def setUp(self):
        modules = {
            'terminaltables': MagicMock(),
        }
        modules["terminaltables"].AsciiTable = self._table

        self.module_patcher = patch.dict('sys.modules', modules)
        self.module_patcher.start()
        super().setUp()
        self.mock_stdin = create_autospec(sys.stdin)
        self.mock_stdout = create_autospec(sys.stdout)
        # we are connected as anonymous client
        self._bcp_client.name = None

    def tearDown(self) -> None:
        super().tearDown()
        self.module_patcher.stop()

    def _last_write(self, n=None):
        """:return: last `n` output lines"""
        if n is None:
            return self.mock_stdout.write.call_args[0][0]
        return "".join(map(lambda c: c[0][0], self.mock_stdout.write.call_args_list[-n:]))

    def test_cli(self):
        self.maxDiff = None
        with patch("mpf.commands.service.AsciiTable"):
            from mpf.commands.service import ServiceCli
            cli = ServiceCli(self._bcp_external_client, self.loop, self.mock_stdin, self.mock_stdout)

        cli.onecmd("light_color l_light5 red")
        self.assertEqual("Success\n", self._last_write())

        cli.onecmd("light_color l_light1 invalid_color")
        self.assertEqual("Error: Invalid RGB string: invalid_color\n", self._last_write())

        cli.onecmd("light_color l_light1 white")
        self.assertEqual("Success\n", self._last_write())

        cli.onecmd("list_lights")
        expected = """Board;Number;Name;Color;
Virtual;['led-1-b', 'led-1-g', 'led-1-r'];l_light1;(255, 255, 255);
Virtual;['led-5-b', 'led-5-g', 'led-5-r'];l_light5;(255, 0, 0);
"""
        self.assertEqual(expected, self._last_write())

        cli.onecmd("light_off l_light5")
        self.assertEqual("Success\n", self._last_write())

        self.assertLightColor("l_light5", "black")

        cli.onecmd("light_color l_light5")
        self.assertEqual("Success\n", self._last_write())

        self.assertLightColor("l_light5", "white")

        cli.onecmd("light_off l_light5")
        self.assertEqual("Success\n", self._last_write())

        self.assertLightColor("l_light5", "black")

        self.hit_switch_and_run("s_door_open", 0)

        cli.onecmd("list_switches")
        expected = """Board;Number;Name;State;
Virtual;1;s_door_open;closed;
Virtual;17;s_service_enter;open;
Virtual;18;s_service_esc;open;
Virtual;19;s_service_up;open;
Virtual;20;s_service_down;open;
"""
        self.assertEqual(expected, self._last_write())

        cli.onecmd("list_coils")
        expected = """Board;Number;Name;
Virtual;1;c_test;
Virtual;2;c_test2;
Virtual;3;c_test5;
Virtual;10;c_test6;
Virtual;100;c_test4;
Virtual;1000;c_test3;
"""
        self.assertEqual(expected, self._last_write())

        cli.onecmd("list_shows")
        expected = """Name;Token;
bl_color;['blinkenlight', 'blinkenlights', 'color', 'led', 'leds', 'light', 'lights'];
flash;['led', 'leds', 'light', 'lights'];
flash_color;['color', 'led', 'leds', 'light', 'lights'];
led_color;['color', 'led', 'leds', 'light', 'lights'];
off;['led', 'leds', 'light', 'lights'];
on;['led', 'leds', 'light', 'lights'];
"""
        self.assertEqual(expected, self._last_write())

        self.assertLightColor("l_light5", "black")

        cli.onecmd("show_play on led:l_light5")
        self.assertLightColor("l_light5", "white")

        cli.onecmd("show_stop on")
        self.assertLightColor("l_light5", "black")

        cli.onecmd("show_play led_color led:l_light5 color:red")
        self.assertLightColor("l_light5", "red")

        self.assertEqual("disabled", self.machine.coils["c_test"].hw_driver.state)

        cli.onecmd("coil_pulse c_test")
        self.assertEqual("Success\n", self._last_write())
        self.assertEqual("pulsed_10", self.machine.coils["c_test"].hw_driver.state)

        cli.onecmd("coil_enable c_test")
        self.assertEqual("Error: Cannot enable driver with hold_power 0.0\n", self._last_write())

        cli.onecmd("coil_enable c_test6")
        self.assertEqual("Success\n", self._last_write())
        self.assertEqual("enabled", self.machine.coils["c_test6"].hw_driver.state)

        cli.onecmd("coil_disable c_test6")
        self.assertEqual("Success\n", self._last_write())
        self.assertEqual("disabled", self.machine.coils["c_test6"].hw_driver.state)

        self.assertLightColor("l_light1", "white")
        self.assertLightColor("l_light5", "red")

        cli.onecmd("quit")
        self.advance_time_and_run()

        self.assertLightColor("l_light1", "black")
        self.assertLightColor("l_light5", "black")


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SmcMap (SMC v. 6_5_0 API Specification)</title>
<meta name="date" content="2015-02-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

SMC
6_5_0

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.sf.smc.model

Class SmcMap

java.lang.Object

net.sf.smc.model.SmcElement

net.sf.smc.model.SmcMap

public final class SmcMap
extends SmcElement

SMC has states grouped into maps. This class contains
 states in a list and
 stores the default state separately (if there is one).

See Also:

SmcFSM,
SmcState

Nested Class Summary

Nested classes/interfaces inherited from class net.sf.smc.model.SmcElement

SmcElement.TransType

Field Summary

Fields inherited from class net.sf.smc.model.SmcElement

_lineNumber, _name, NIL_STATE

Constructor Summary

Constructors

Constructor and Description

SmcMap(java.lang.String name,
      int lineNumber,
      SmcFSM fsm)

Creates a state machine map with the given name, line
 number and finite state machine.

Method Summary

Methods

Modifier and Type
Method and Description

void
accept(SmcVisitor visitor)

Calls the visitor's visit method for this finite state
 machine element.

void
addState(SmcState state)

Adds a state to the list.

boolean
findState(SmcState state)

Returns true if the state is in the list and
 false otherwise.

java.util.List<SmcState>
getAllStates()

Returns all states in this map including the default
 state.

SmcState
getDefaultState()

Returns the default state.

SmcFSM
getFSM()

Returns the owning finite state machine.

static int
getNextStateId()

Returns the next unique state identifier.

java.util.List<SmcState>
getStates()

Returns the map's states.

java.util.List<SmcTransition>
getTransitions()

Returns all the transitions from all the states in this
 map.

java.util.List<SmcTransition>
getUndefinedDefaultTransitions()

Returns the list of transitions that do not appear in the
 default state.

boolean
hasDefaultState()

Returns true if this map has an explicitly
 defined default state and false otherwise.

boolean
hasEntryActions()

Returns true if at least one of the map's states
 has an entry action and false otherwise.

boolean
hasExitActions()

Returns true if at least one of the map's states
 has an exit action and false otherwise.

boolean
isKnownState(java.lang.String stateName)

Returns true if this map contains the nsamed
 state; false otherwise.

java.lang.String
toString()

Returns the map's text representation.

Methods inherited from class net.sf.smc.model.SmcElement

getLineNumber, getName, merge

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

SmcMap

public SmcMap(java.lang.String name,
      int lineNumber,
      SmcFSM fsm)

Creates a state machine map with the given name, line
 number and finite state machine.

Parameters:

name - FSM map name.

lineNumber - .sm file where element begins.

fsm - the map resides in this FSM.

Method Detail

accept

public void accept(SmcVisitor visitor)

Calls the visitor's visit method for this finite state
 machine element.

Specified by:

accept in class SmcElement

Parameters:

visitor - The visitor instance.

See Also:

SmcVisitor

getFSM

public SmcFSM getFSM()

Returns the owning finite state machine.

Returns:

the owning finite state machine.

getStates

public java.util.List<SmcState> getStates()

Returns the map's states.

Returns:

the map's states.

findState

public boolean findState(SmcState state)

Returns true if the state is in the list and
 false otherwise.

Parameters:

state - an FSM state.

Returns:

true if the state is in the list and
 false otherwise.

isKnownState

public boolean isKnownState(java.lang.String stateName)

Returns true if this map contains the nsamed
 state; false otherwise.

Parameters:

stateName - an FSM state name.

Returns:

true if this map contains the nsamed
 state; false otherwise.

hasDefaultState

public boolean hasDefaultState()

Returns true if this map has an explicitly
 defined default state and false otherwise.

Returns:

true if this map has an explicitly
 defined default state and false otherwise.

getDefaultState

public SmcState getDefaultState()

Returns the default state. May return null.

Returns:

the default state.

getAllStates

public java.util.List<SmcState> getAllStates()

Returns all states in this map including the default
 state.

Returns:

all states in this map including the default
 state.

getTransitions

public java.util.List<SmcTransition> getTransitions()

Returns all the transitions from all the states in this
 map.

Returns:

all the transitions from all the states in this
 map.

getUndefinedDefaultTransitions

public java.util.List<SmcTransition> getUndefinedDefaultTransitions()

Returns the list of transitions that do not appear in the
 default state.

Returns:

the list of transitions that do not appear in the
 default state.

hasEntryActions

public boolean hasEntryActions()

Returns true if at least one of the map's states
 has an entry action and false otherwise.

Returns:

true if at least one of the map's states
 has an entry action and false otherwise.

hasExitActions

public boolean hasExitActions()

Returns true if at least one of the map's states
 has an exit action and false otherwise.

Returns:

true if at least one of the map's states
 has an exit action and false otherwise.

getNextStateId

public static int getNextStateId()

Returns the next unique state identifier.

Returns:

the next unique state identifier.

addState

public void addState(SmcState state)

Adds a state to the list.

Parameters:

state - an FSM state.

toString

public java.lang.String toString()

Returns the map's text representation.

Overrides:

toString in class java.lang.Object

Returns:

the map's text representation.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

SMC
6_5_0

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2015. Charles W. Rapp. All Rights Reserved. Use is subject to license terms.


text:
<?php

namespace PHPSpec2\Extension;

use PHPSpec2\ServiceContainer;

class Configuration
{
    private $container;

    public function __construct(ServiceContainer $container, YamlParser $parser = null)
    {
        $this->container = $container;
        $this->parser    = $parser ?: new YamlParser;
    }

    public function read($file)
    {
        if ($config = $this->parser->parse($file)) {
            foreach ($config as $key => $val) {
                $this->container->set($key, $val);
            }
        }
    }
}


text:
/**
 * These functions were taken/modified from zen-audio-player/zen-audio-player.github.io
 * https://github.com/zen-audio-player/zen-audio-player.github.io/blob/04eb63d5f520fa6aa6ca9805c669e25c75e6b341/js/everything.js
 */

module.exports.getParameterByName =function (url, name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(url);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};

module.exports.parseYoutubeVideoID = function(url) {
    var videoID = null;

    var shortUrlDomain = "youtu.be";
    var longUrlDomain = "youtube.com";

    if (url && url.length > 0) {
        // youtube.com format
        if (url.indexOf(longUrlDomain) !== -1) {
            videoID = module.exports.getParameterByName(url, "v");
            // If the URL had 2 v parameters, try parsing the second (usually when ?v=someurl&v=xyz)
            if (videoID === "") {
                videoID = module.exports.getParameterByName(window.location.href.substring(window.location.href.indexOf(url)), "v");
            }
        }
        // youtu.be format
        else if (url.indexOf(shortUrlDomain) !== -1) {
            var endPosition = url.indexOf("?") === -1 ? url.length : url.indexOf("?");
            var offset = url.indexOf(shortUrlDomain) + shortUrlDomain.length + 1; // Skip over the slash also
            videoID = url.substring(offset, endPosition);
        }
        // Assume YouTube video ID string
        else {
            videoID = url;
        }

        var slashPos = videoID.indexOf("/");
        // We found a slash in the video ID (ex: real id is ABC123, but saw ABC123/zen)
        // So, only keep what's before the slash
        if (slashPos !== -1) {
            videoID = videoID.substring(0, slashPos);
        }

        currentVideoID = videoID;

        return videoID;
    }
    return null;
};


text:
import pytest

from wtforms.validators import email
from wtforms.validators import ValidationError

@pytest.mark.parametrize(
    "email_address",
    ["foo@bar.dk", "123@bar.dk", "foo@456.dk", "foo@bar456.info", "foo@bücher.中国"],
)
def test_valid_email_passes(email_address, dummy_form, dummy_field):
    """
    Valid email address should pass without raising
    """
    validator = email()
    dummy_field.data = email_address
    validator(dummy_form, dummy_field)

@pytest.mark.parametrize(
    "email_address",
    [
        None,
        "",
        "  ",
        "foo",
        "bar.dk",
        "foo@",
        "@bar.dk",
        "foo@bar",
        "foo@bar.ab12",
        "foo@.bar.ab",
        "foo.@bar.co",
        "foo@foo@bar.co",
        "fo o@bar.co",
    ],
)
def test_invalid_email_raises(email_address, dummy_form, dummy_field):
    """
    Bad email address should raise ValidationError
    """
    validator = email()
    dummy_field.data = email_address
    with pytest.raises(ValidationError) as e:
        validator(dummy_form, dummy_field)

    assert str(e.value) == "Invalid email address."

@pytest.mark.parametrize("email_address", ["foo@"])
def test_invalid_email_raises_granular_message(email_address, dummy_form, dummy_field):
    """
    When granular_message=True uses message from email_validator library.
    """
    validator = email(granular_message=True)
    dummy_field.data = email_address
    with pytest.raises(ValidationError) as e:
        validator(dummy_form, dummy_field)

    assert str(e.value) == "There must be something after the @-sign."


text:
JSML
====

Appendable sequences of JSON documents

There's an issue with JSON that I can't tolerate: If you want to add a new
object to a JSON document, you have to rewrite the whole document. That makes it
inappropriate for logging an similar tasks. This is where JSML pitches in.

Example
-------

Here's an example document that defines metadata for serveral articles:

``` javascript
{
  "title": "Hello World",
  "date":  "2012-08-09",
  "tags":  [ "hello world", "misc" ]
}
---
{
  "title": "The second article",
  "date":  "2012-08-10",
  "tags":  [ "misc" ]
}
```

Note that each object is a normal JSON representation of a JavaScript object.
In pure JSON, the same document would look like this:

``` javascript
[
  {
    "title": "Hello World",
    "date": "2012-08-09",
    "tags": [ "hello world", "misc" ]
  },
  {
    "title": "The second article",
    "date":  "2012-08-10",
    "tags":  [ "misc" ]
  }
]
```

So the only difference from a usual JSON document is, that objects in top level
arrays are separated by `---` on a distinct line.

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

```
npm install jsml
```

or

```
ender build jsml
```

Usage
-----

You can use JSML just like [JSON](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON):

``` javascript
var JSML = require('jsml');

var jsmlDocument = '{ "title": "Hello World",\n'
                 + '"date":  "2012-08-09",\n'
                 + '"tags":  [ "hello world", "misc" ] }\n'
                 + '---\n'
                 + '{ "title": "The second article",\n'
                 + '"date":  "2012-08-10",\n'
                 + '"tags":  [ "misc" ] }\n';

// Parse a string

var doc = JSML.parse(jsmlDocument);

console.log(doc);

// Stringify an Object or an Array of Objects

var jsmlString = JSML.stringify(doc, null, '  ');

console.log(jsmlString);
```

This will print:

``` javascript
[ { title: 'Hello World',
    date: '2012-08-09',
    tags: [ 'hello world', 'misc' ] },
  { title: 'The second article',
    date: '2012-08-10',
    tags: [ 'misc' ] } ]
```

for the parsed string and the following for the _stringified_ array:

``` javascript
{
  "title": "Hello World",
  "date": "2012-08-09",
  "tags": [
    "hello world",
    "misc"
  ]
}
---
{
  "title": "The second article",
  "date": "2012-08-10",
  "tags": [
    "misc"
  ]
}
```

Bugs and Issues
---------------

If you encounter any bugs or issues, feel free to
[open an issue](https://github.com/pvorb/jsml/issues) at github.

License
-------

Copyright © 2012 Paul Vorbach

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
var Handler = require('./handler');

/**
 * Upgrade the server by creating handlers for incoming server requests.
 *
 * Example:
 *
 *    upgrade(http.createServer(), {template: 'foo.html'})
 *
 */

module.exports = function (server, options) {
  var emit = server.emit
    , respond = require('./respond')(options);

  server.emit = function (ev, req, res) {
    if(ev === 'request') {
      var h = new Handler(req, res, respond, server)
        , args = arguments;

      h.run(function () {
        emit.apply(server, args);
      });
    } else {
      emit.apply(server, arguments);
    }
  }

  return server;
}


text:
#region << 版 本 注 释 >>

#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;

namespace Dos.ORM
{
    public interface IConstructorInvoker
    {
        object Invoke(params object[] parameters);
    }

    public class ConstructorInvoker : IConstructorInvoker
    {
        private Func<object[], object> m_invoker;

        public ConstructorInfo ConstructorInfo { get; private set; }

        public ConstructorInvoker(ConstructorInfo constructorInfo)
        {
            this.ConstructorInfo = constructorInfo;
            this.m_invoker = InitializeInvoker(constructorInfo);
        }

        private Func<object[], object> InitializeInvoker(ConstructorInfo constructorInfo)
        {
            // Target: (object)new T((T0)parameters[0], (T1)parameters[1], ...)

            // parameters to execute
            var parametersParameter = System.Linq.Expressions.Expression.Parameter(typeof(object[]), "parameters");

            // build parameter list
            var parameterExpressions = new List<System.Linq.Expressions.Expression>();
            var paramInfos = constructorInfo.GetParameters();
            for (int i = 0; i < paramInfos.Length; i++)
            {
                // (Ti)parameters[i]
                var valueObj = System.Linq.Expressions.Expression.ArrayIndex(parametersParameter, System.Linq.Expressions.Expression.Constant(i));
                var valueCast = System.Linq.Expressions.Expression.Convert(valueObj, paramInfos[i].ParameterType);

                parameterExpressions.Add(valueCast);
            }

            // new T((T0)parameters[0], (T1)parameters[1], ...)
            var instanceCreate = System.Linq.Expressions.Expression.New(constructorInfo, parameterExpressions);

            // (object)new T((T0)parameters[0], (T1)parameters[1], ...)
            var instanceCreateCast = System.Linq.Expressions.Expression.Convert(instanceCreate, typeof(object));

            var lambda = System.Linq.Expressions.Expression.Lambda<Func<object[], object>>(instanceCreateCast, parametersParameter);

            return lambda.Compile();
        }

        public object Invoke(params object[] parameters)
        {
            return this.m_invoker(parameters);
        }

        #region IConstructorInvoker Members

        object IConstructorInvoker.Invoke(params object[] parameters)
        {
            return this.Invoke(parameters);
        }

        #endregion
    }
    public class ConstructorInvokerFactory : IFastReflectionFactory<ConstructorInfo, IConstructorInvoker>
    {
        public IConstructorInvoker Create(ConstructorInfo key)
        {
            return new ConstructorInvoker(key);
        }

        #region IFastReflectionFactory<ConstructorInfo,IConstructorInvoker> Members

        IConstructorInvoker IFastReflectionFactory<ConstructorInfo, IConstructorInvoker>.Create(ConstructorInfo key)
        {
            return this.Create(key);
        }

        #endregion
    }
    public class ConstructorInvokerCache : FastReflectionCache<ConstructorInfo, IConstructorInvoker>
    {
        protected override IConstructorInvoker Create(ConstructorInfo key)
        {
            return FastReflectionFactories.ConstructorInvokerFactory.Create(key);
        }
    }
}


text:
package org.apache.solr.search;

import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.SolrInfoMBean;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.search.join.BlockJoinChildQParserPlugin;
import org.apache.solr.search.join.BlockJoinParentQParserPlugin;
import org.apache.solr.util.plugin.NamedListInitializedPlugin;

import java.net.URL;

public abstract class QParserPlugin implements NamedListInitializedPlugin, SolrInfoMBean {
  /** internal use - name of the default parser */
  public static String DEFAULT_QTYPE = LuceneQParserPlugin.NAME;

  /** internal use - name to class mappings of builtin parsers */
  public static final Object[] standardPlugins = {
    LuceneQParserPlugin.NAME, LuceneQParserPlugin.class,
    OldLuceneQParserPlugin.NAME, OldLuceneQParserPlugin.class,
    FunctionQParserPlugin.NAME, FunctionQParserPlugin.class,
    PrefixQParserPlugin.NAME, PrefixQParserPlugin.class,
    BoostQParserPlugin.NAME, BoostQParserPlugin.class,
    DisMaxQParserPlugin.NAME, DisMaxQParserPlugin.class,
    ExtendedDismaxQParserPlugin.NAME, ExtendedDismaxQParserPlugin.class,
    FieldQParserPlugin.NAME, FieldQParserPlugin.class,
    RawQParserPlugin.NAME, RawQParserPlugin.class,
    TermQParserPlugin.NAME, TermQParserPlugin.class,
    NestedQParserPlugin.NAME, NestedQParserPlugin.class,
    FunctionRangeQParserPlugin.NAME, FunctionRangeQParserPlugin.class,
    SpatialFilterQParserPlugin.NAME, SpatialFilterQParserPlugin.class,
    SpatialBoxQParserPlugin.NAME, SpatialBoxQParserPlugin.class,
    JoinQParserPlugin.NAME, JoinQParserPlugin.class,
    SurroundQParserPlugin.NAME, SurroundQParserPlugin.class,
    SwitchQParserPlugin.NAME, SwitchQParserPlugin.class,
    MaxScoreQParserPlugin.NAME, MaxScoreQParserPlugin.class,
    BlockJoinParentQParserPlugin.NAME, BlockJoinParentQParserPlugin.class,
    BlockJoinChildQParserPlugin.NAME, BlockJoinChildQParserPlugin.class,
    CollapsingQParserPlugin.NAME, CollapsingQParserPlugin.class,
    SimpleQParserPlugin.NAME, SimpleQParserPlugin.class
  };

  /** return a {@link QParser} */
  public abstract QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req);

  @Override
  public String getName() {
    // TODO: ideally use the NAME property that each qparser plugin has

    return this.getClass().getName();
  }

  @Override
  public String getVersion() {
    return null;
  }

  @Override
  public String getDescription() {
    return "";  // UI required non-null to work
  }

  @Override
  public Category getCategory() {
    return Category.QUERYPARSER;
  }

  @Override
  public String getSource() {
    return "$URL: http://svn.apache.org/repos/asf/lucene/dev/trunk/solr/core/src/java/org/apache/solr/search/QParserPlugin.java $";
  }

  @Override
  public URL[] getDocs() {
    return new URL[0];
  }

  @Override
  public NamedList getStatistics() {
    return null;
  }
}


text:
package pl.maciejwalkowiak.plist;

/**
 * Main java-plist-serializer interface, representing a component that serializes Java objects to Apple Property Lists
 * {@see http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html}
 *
 *
 * @author Maciej Walkowiak
 */
public interface PlistSerializer {
	static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\">";
	static final String FOOTER = "</plist>";

	/**
	 * Serializes object to plist and creates valid XML by wrapping it around XML header,
	 * plist DOCTYPE and <plist> XML tag.
	 *
	 * @param objectToConvert object to serialize
	 * @return a String containing valid XML
	 */
	String toXmlPlist(Object objectToConvert);

	/**
	 * Serializes object into plist XML
	 *
	 * @param objectToConvert object to serialize
	 * @return a String containing XML representation without XML header, DOCTYPE
	 */
	String serialize(Object objectToConvert);
}


text:
namespace spvtools {
namespace fuzz {
namespace {

TEST(TransformationCompositeExtractTest, BasicTest) {
  std::string shader = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
               OpName %4 "main"
               OpName %8 "a"
               OpName %10 "b"
               OpName %17 "FunnyPoint"
               OpMemberName %17 0 "x"
               OpMemberName %17 1 "y"
               OpMemberName %17 2 "z"
               OpName %19 "p"
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeInt 32 1
          %7 = OpTypePointer Function %6
         %12 = OpTypeBool
         %16 = OpTypeFloat 32
         %17 = OpTypeStruct %16 %16 %6
         %81 = OpTypeStruct %17 %16
         %18 = OpTypePointer Function %17
         %20 = OpConstant %6 0
         %23 = OpTypePointer Function %16
         %26 = OpConstant %6 1
         %30 = OpConstant %6 2
         %80 = OpUndef %16
          %4 = OpFunction %2 None %3
          %5 = OpLabel
          %8 = OpVariable %7 Function
         %10 = OpVariable %7 Function
         %19 = OpVariable %18 Function
          %9 = OpLoad %6 %8
         %11 = OpLoad %6 %10
        %100 = OpCompositeConstruct %17 %80 %80 %26
        %104 = OpCompositeConstruct %81 %100 %80
         %13 = OpIEqual %12 %9 %11
               OpSelectionMerge %15 None
               OpBranchConditional %13 %14 %25
         %14 = OpLabel
         %21 = OpLoad %6 %8
         %22 = OpConvertSToF %16 %21
        %101 = OpCompositeConstruct %17 %22 %80 %30
         %24 = OpAccessChain %23 %19 %20
               OpStore %24 %22
               OpBranch %15
         %25 = OpLabel
         %27 = OpLoad %6 %10
         %28 = OpConvertSToF %16 %27
        %102 = OpCompositeConstruct %17 %80 %28 %27
         %29 = OpAccessChain %23 %19 %26
               OpStore %29 %28
               OpBranch %15
         %15 = OpLabel
         %31 = OpAccessChain %23 %19 %20
         %32 = OpLoad %16 %31
         %33 = OpAccessChain %23 %19 %26
         %34 = OpLoad %16 %33
        %103 = OpCompositeConstruct %17 %34 %32 %9
         %35 = OpFAdd %16 %32 %34
         %36 = OpConvertFToS %6 %35
         %37 = OpAccessChain %7 %19 %30
               OpStore %37 %36
               OpReturn
               OpFunctionEnd
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_4;
  const auto consumer = nullptr;
  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
  spvtools::ValidatorOptions validator_options;
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));
  TransformationContext transformation_context(
      MakeUnique<FactManager>(context.get()), validator_options);
  // Instruction does not exist.
  ASSERT_FALSE(TransformationCompositeExtract(
                   MakeInstructionDescriptor(36, SpvOpIAdd, 0), 200, 101, {0})
                   .IsApplicable(context.get(), transformation_context));

  // Id for composite is not a composite.
  ASSERT_FALSE(
      TransformationCompositeExtract(
          MakeInstructionDescriptor(37, SpvOpAccessChain, 0), 200, 32, {})
          .IsApplicable(context.get(), transformation_context));

  // Composite does not dominate instruction being inserted before.
  ASSERT_FALSE(
      TransformationCompositeExtract(
          MakeInstructionDescriptor(37, SpvOpAccessChain, 0), 200, 101, {0})
          .IsApplicable(context.get(), transformation_context));

  // Too many indices for extraction from struct composite.
  ASSERT_FALSE(
      TransformationCompositeExtract(
          MakeInstructionDescriptor(24, SpvOpAccessChain, 0), 200, 101, {0, 0})
          .IsApplicable(context.get(), transformation_context));

  // Too many indices for extraction from struct composite.
  ASSERT_FALSE(
      TransformationCompositeExtract(
          MakeInstructionDescriptor(13, SpvOpIEqual, 0), 200, 104, {0, 0, 0})
          .IsApplicable(context.get(), transformation_context));

  // Out of bounds index for extraction from struct composite.
  ASSERT_FALSE(
      TransformationCompositeExtract(
          MakeInstructionDescriptor(13, SpvOpIEqual, 0), 200, 104, {0, 3})
          .IsApplicable(context.get(), transformation_context));

  // Result id already used.
  ASSERT_FALSE(TransformationCompositeExtract(
                   MakeInstructionDescriptor(35, SpvOpFAdd, 0), 80, 103, {0})
                   .IsApplicable(context.get(), transformation_context));

  TransformationCompositeExtract transformation_1(
      MakeInstructionDescriptor(36, SpvOpConvertFToS, 0), 201, 100, {2});
  ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(201));
  ASSERT_EQ(nullptr, context->get_instr_block(201));
  uint32_t num_uses_of_100_before = context->get_def_use_mgr()->NumUses(100);
  ASSERT_TRUE(
      transformation_1.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation_1, context.get(),
                        &transformation_context);
  ASSERT_EQ(SpvOpCompositeExtract,
            context->get_def_use_mgr()->GetDef(201)->opcode());
  ASSERT_EQ(15, context->get_instr_block(201)->id());
  ASSERT_EQ(num_uses_of_100_before + 1,
            context->get_def_use_mgr()->NumUses(100));
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));

  TransformationCompositeExtract transformation_2(
      MakeInstructionDescriptor(37, SpvOpAccessChain, 0), 202, 104, {0, 2});
  ASSERT_TRUE(
      transformation_2.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation_2, context.get(),
                        &transformation_context);
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));

  TransformationCompositeExtract transformation_3(
      MakeInstructionDescriptor(29, SpvOpAccessChain, 0), 203, 104, {0});
  ASSERT_TRUE(
      transformation_3.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation_3, context.get(),
                        &transformation_context);
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));

  TransformationCompositeExtract transformation_4(
      MakeInstructionDescriptor(24, SpvOpStore, 0), 204, 101, {0});
  ASSERT_TRUE(
      transformation_4.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation_4, context.get(),
                        &transformation_context);
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));

  TransformationCompositeExtract transformation_5(
      MakeInstructionDescriptor(29, SpvOpBranch, 0), 205, 102, {2});
  ASSERT_TRUE(
      transformation_5.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation_5, context.get(),
                        &transformation_context);
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));

  TransformationCompositeExtract transformation_6(
      MakeInstructionDescriptor(37, SpvOpReturn, 0), 206, 103, {1});
  ASSERT_TRUE(
      transformation_6.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation_6, context.get(),
                        &transformation_context);
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));

  ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous(
      MakeDataDescriptor(201, {}), MakeDataDescriptor(100, {2})));
  ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous(
      MakeDataDescriptor(202, {}), MakeDataDescriptor(104, {0, 2})));
  ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous(
      MakeDataDescriptor(203, {}), MakeDataDescriptor(104, {0})));
  ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous(
      MakeDataDescriptor(204, {}), MakeDataDescriptor(101, {0})));
  ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous(
      MakeDataDescriptor(205, {}), MakeDataDescriptor(102, {2})));
  ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous(
      MakeDataDescriptor(206, {}), MakeDataDescriptor(103, {1})));

  std::string after_transformation = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
               OpName %4 "main"
               OpName %8 "a"
               OpName %10 "b"
               OpName %17 "FunnyPoint"
               OpMemberName %17 0 "x"
               OpMemberName %17 1 "y"
               OpMemberName %17 2 "z"
               OpName %19 "p"
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeInt 32 1
          %7 = OpTypePointer Function %6
         %12 = OpTypeBool
         %16 = OpTypeFloat 32
         %17 = OpTypeStruct %16 %16 %6
         %81 = OpTypeStruct %17 %16
         %18 = OpTypePointer Function %17
         %20 = OpConstant %6 0
         %23 = OpTypePointer Function %16
         %26 = OpConstant %6 1
         %30 = OpConstant %6 2
         %80 = OpUndef %16
          %4 = OpFunction %2 None %3
          %5 = OpLabel
          %8 = OpVariable %7 Function
         %10 = OpVariable %7 Function
         %19 = OpVariable %18 Function
          %9 = OpLoad %6 %8
         %11 = OpLoad %6 %10
        %100 = OpCompositeConstruct %17 %80 %80 %26
        %104 = OpCompositeConstruct %81 %100 %80
         %13 = OpIEqual %12 %9 %11
               OpSelectionMerge %15 None
               OpBranchConditional %13 %14 %25
         %14 = OpLabel
         %21 = OpLoad %6 %8
         %22 = OpConvertSToF %16 %21
        %101 = OpCompositeConstruct %17 %22 %80 %30
         %24 = OpAccessChain %23 %19 %20
        %204 = OpCompositeExtract %16 %101 0
               OpStore %24 %22
               OpBranch %15
         %25 = OpLabel
         %27 = OpLoad %6 %10
         %28 = OpConvertSToF %16 %27
        %102 = OpCompositeConstruct %17 %80 %28 %27
        %203 = OpCompositeExtract %17 %104 0
         %29 = OpAccessChain %23 %19 %26
               OpStore %29 %28
        %205 = OpCompositeExtract %6 %102 2
               OpBranch %15
         %15 = OpLabel
         %31 = OpAccessChain %23 %19 %20
         %32 = OpLoad %16 %31
         %33 = OpAccessChain %23 %19 %26
         %34 = OpLoad %16 %33
        %103 = OpCompositeConstruct %17 %34 %32 %9
         %35 = OpFAdd %16 %32 %34
        %201 = OpCompositeExtract %6 %100 2
         %36 = OpConvertFToS %6 %35
        %202 = OpCompositeExtract %6 %104 0 2
         %37 = OpAccessChain %7 %19 %30
               OpStore %37 %36
        %206 = OpCompositeExtract %16 %103 1
               OpReturn
               OpFunctionEnd
  )";
  ASSERT_TRUE(IsEqual(env, after_transformation, context.get()));
}

TEST(TransformationCompositeExtractTest, IllegalInsertionPoints) {
  std::string shader = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main" %51 %27
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
               OpName %4 "main"
               OpName %25 "buf"
               OpMemberName %25 0 "value"
               OpName %27 ""
               OpName %51 "color"
               OpMemberDecorate %25 0 Offset 0
               OpDecorate %25 Block
               OpDecorate %27 DescriptorSet 0
               OpDecorate %27 Binding 0
               OpDecorate %51 Location 0
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeFloat 32
          %7 = OpTypeVector %6 4
         %10 = OpConstant %6 0.300000012
         %11 = OpConstant %6 0.400000006
         %12 = OpConstant %6 0.5
         %13 = OpConstant %6 1
         %14 = OpConstantComposite %7 %10 %11 %12 %13
         %15 = OpTypeInt 32 1
         %18 = OpConstant %15 0
         %25 = OpTypeStruct %6
         %26 = OpTypePointer Uniform %25
         %27 = OpVariable %26 Uniform
         %28 = OpTypePointer Uniform %6
         %32 = OpTypeBool
        %103 = OpConstantTrue %32
         %34 = OpConstant %6 0.100000001
         %48 = OpConstant %15 1
         %50 = OpTypePointer Output %7
         %51 = OpVariable %50 Output
        %100 = OpTypePointer Function %6
          %4 = OpFunction %2 None %3
          %5 = OpLabel
        %101 = OpVariable %100 Function
        %102 = OpVariable %100 Function
               OpBranch %19
         %19 = OpLabel
         %60 = OpPhi %7 %14 %5 %58 %20
         %59 = OpPhi %15 %18 %5 %49 %20
         %29 = OpAccessChain %28 %27 %18
         %30 = OpLoad %6 %29
         %31 = OpConvertFToS %15 %30
         %33 = OpSLessThan %32 %59 %31
               OpLoopMerge %21 %20 None
               OpBranchConditional %33 %20 %21
         %20 = OpLabel
         %39 = OpCompositeExtract %6 %60 0
         %40 = OpFAdd %6 %39 %34
         %55 = OpCompositeInsert %7 %40 %60 0
         %44 = OpCompositeExtract %6 %60 1
         %45 = OpFSub %6 %44 %34
         %58 = OpCompositeInsert %7 %45 %55 1
         %49 = OpIAdd %15 %59 %48
               OpBranch %19
         %21 = OpLabel
               OpStore %51 %60
               OpSelectionMerge %105 None
               OpBranchConditional %103 %104 %105
        %104 = OpLabel
               OpBranch %105
        %105 = OpLabel
               OpReturn
               OpFunctionEnd
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_4;
  const auto consumer = nullptr;
  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
  spvtools::ValidatorOptions validator_options;
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));
  TransformationContext transformation_context(
      MakeUnique<FactManager>(context.get()), validator_options);
  // Cannot insert before the OpVariables of a function.
  ASSERT_FALSE(
      TransformationCompositeExtract(
          MakeInstructionDescriptor(101, SpvOpVariable, 0), 200, 14, {0})
          .IsApplicable(context.get(), transformation_context));
  ASSERT_FALSE(
      TransformationCompositeExtract(
          MakeInstructionDescriptor(101, SpvOpVariable, 1), 200, 14, {1})
          .IsApplicable(context.get(), transformation_context));
  ASSERT_FALSE(
      TransformationCompositeExtract(
          MakeInstructionDescriptor(102, SpvOpVariable, 0), 200, 14, {1})
          .IsApplicable(context.get(), transformation_context));
  // OK to insert right after the OpVariables.
  ASSERT_FALSE(TransformationCompositeExtract(
                   MakeInstructionDescriptor(102, SpvOpBranch, 1), 200, 14, {1})
                   .IsApplicable(context.get(), transformation_context));

  // Cannot insert before the OpPhis of a block.
  ASSERT_FALSE(TransformationCompositeExtract(
                   MakeInstructionDescriptor(60, SpvOpPhi, 0), 200, 14, {2})
                   .IsApplicable(context.get(), transformation_context));
  ASSERT_FALSE(TransformationCompositeExtract(
                   MakeInstructionDescriptor(59, SpvOpPhi, 0), 200, 14, {3})
                   .IsApplicable(context.get(), transformation_context));
  // OK to insert after the OpPhis.
  ASSERT_TRUE(
      TransformationCompositeExtract(
          MakeInstructionDescriptor(59, SpvOpAccessChain, 0), 200, 14, {3})
          .IsApplicable(context.get(), transformation_context));

  // Cannot insert before OpLoopMerge
  ASSERT_FALSE(TransformationCompositeExtract(
                   MakeInstructionDescriptor(33, SpvOpBranchConditional, 0),
                   200, 14, {3})
                   .IsApplicable(context.get(), transformation_context));

  // Cannot insert before OpSelectionMerge
  ASSERT_FALSE(TransformationCompositeExtract(
                   MakeInstructionDescriptor(21, SpvOpBranchConditional, 0),
                   200, 14, {2})
                   .IsApplicable(context.get(), transformation_context));
}

TEST(TransformationCompositeExtractTest, AddSynonymsForRelevantIds) {
  std::string shader = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
               OpName %4 "main"
               OpName %8 "a"
               OpName %10 "b"
               OpName %17 "FunnyPoint"
               OpMemberName %17 0 "x"
               OpMemberName %17 1 "y"
               OpMemberName %17 2 "z"
               OpName %19 "p"
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeInt 32 1
          %7 = OpTypePointer Function %6
         %12 = OpTypeBool
         %16 = OpTypeFloat 32
         %17 = OpTypeStruct %16 %16 %6
         %81 = OpTypeStruct %17 %16
         %18 = OpTypePointer Function %17
         %20 = OpConstant %6 0
         %23 = OpTypePointer Function %16
         %26 = OpConstant %6 1
         %30 = OpConstant %6 2
         %80 = OpUndef %16
          %4 = OpFunction %2 None %3
          %5 = OpLabel
          %8 = OpVariable %7 Function
         %10 = OpVariable %7 Function
         %19 = OpVariable %18 Function
          %9 = OpLoad %6 %8
         %11 = OpLoad %6 %10
        %100 = OpCompositeConstruct %17 %80 %80 %26
        %104 = OpCompositeConstruct %81 %100 %80
         %13 = OpIEqual %12 %9 %11
               OpSelectionMerge %15 None
               OpBranchConditional %13 %14 %25
         %14 = OpLabel
         %21 = OpLoad %6 %8
         %22 = OpConvertSToF %16 %21
        %101 = OpCompositeConstruct %17 %22 %80 %30
         %24 = OpAccessChain %23 %19 %20
               OpStore %24 %22
               OpBranch %15
         %25 = OpLabel
         %27 = OpLoad %6 %10
         %28 = OpConvertSToF %16 %27
        %102 = OpCompositeConstruct %17 %80 %28 %27
         %29 = OpAccessChain %23 %19 %26
               OpStore %29 %28
               OpBranch %15
         %15 = OpLabel
         %31 = OpAccessChain %23 %19 %20
         %32 = OpLoad %16 %31
         %33 = OpAccessChain %23 %19 %26
         %34 = OpLoad %16 %33
        %103 = OpCompositeConstruct %17 %34 %32 %9
         %35 = OpFAdd %16 %32 %34
         %36 = OpConvertFToS %6 %35
         %37 = OpAccessChain %7 %19 %30
               OpStore %37 %36
               OpReturn
               OpFunctionEnd
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_4;
  const auto consumer = nullptr;
  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
  spvtools::ValidatorOptions validator_options;
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));
  TransformationContext transformation_context(
      MakeUnique<FactManager>(context.get()), validator_options);
  TransformationCompositeExtract transformation(
      MakeInstructionDescriptor(36, SpvOpConvertFToS, 0), 201, 100, {2});
  ASSERT_TRUE(
      transformation.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context);
  ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous(
      MakeDataDescriptor(201, {}), MakeDataDescriptor(100, {2})));
}

TEST(TransformationCompositeExtractTest, DontAddSynonymsForIrrelevantIds) {
  std::string shader = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
               OpName %4 "main"
               OpName %8 "a"
               OpName %10 "b"
               OpName %17 "FunnyPoint"
               OpMemberName %17 0 "x"
               OpMemberName %17 1 "y"
               OpMemberName %17 2 "z"
               OpName %19 "p"
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeInt 32 1
          %7 = OpTypePointer Function %6
         %12 = OpTypeBool
         %16 = OpTypeFloat 32
         %17 = OpTypeStruct %16 %16 %6
         %81 = OpTypeStruct %17 %16
         %18 = OpTypePointer Function %17
         %20 = OpConstant %6 0
         %23 = OpTypePointer Function %16
         %26 = OpConstant %6 1
         %30 = OpConstant %6 2
         %80 = OpUndef %16
          %4 = OpFunction %2 None %3
          %5 = OpLabel
          %8 = OpVariable %7 Function
         %10 = OpVariable %7 Function
         %19 = OpVariable %18 Function
          %9 = OpLoad %6 %8
         %11 = OpLoad %6 %10
        %100 = OpCompositeConstruct %17 %80 %80 %26
        %104 = OpCompositeConstruct %81 %100 %80
         %13 = OpIEqual %12 %9 %11
               OpSelectionMerge %15 None
               OpBranchConditional %13 %14 %25
         %14 = OpLabel
         %21 = OpLoad %6 %8
         %22 = OpConvertSToF %16 %21
        %101 = OpCompositeConstruct %17 %22 %80 %30
         %24 = OpAccessChain %23 %19 %20
               OpStore %24 %22
               OpBranch %15
         %25 = OpLabel
         %27 = OpLoad %6 %10
         %28 = OpConvertSToF %16 %27
        %102 = OpCompositeConstruct %17 %80 %28 %27
         %29 = OpAccessChain %23 %19 %26
               OpStore %29 %28
               OpBranch %15
         %15 = OpLabel
         %31 = OpAccessChain %23 %19 %20
         %32 = OpLoad %16 %31
         %33 = OpAccessChain %23 %19 %26
         %34 = OpLoad %16 %33
        %103 = OpCompositeConstruct %17 %34 %32 %9
         %35 = OpFAdd %16 %32 %34
         %36 = OpConvertFToS %6 %35
         %37 = OpAccessChain %7 %19 %30
               OpStore %37 %36
               OpReturn
               OpFunctionEnd
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_4;
  const auto consumer = nullptr;
  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
  spvtools::ValidatorOptions validator_options;
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));
  TransformationContext transformation_context(
      MakeUnique<FactManager>(context.get()), validator_options);
  transformation_context.GetFactManager()->AddFactIdIsIrrelevant(100);
  TransformationCompositeExtract transformation(
      MakeInstructionDescriptor(36, SpvOpConvertFToS, 0), 201, 100, {2});
  ASSERT_TRUE(
      transformation.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context);
  ASSERT_FALSE(transformation_context.GetFactManager()->IsSynonymous(
      MakeDataDescriptor(201, {}), MakeDataDescriptor(100, {2})));
}

TEST(TransformationCompositeExtractTest, DontAddSynonymInDeadBlock) {
  std::string shader = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 320
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeInt 32 1
          %7 = OpTypeVector %6 2
          %8 = OpTypePointer Function %7
         %10 = OpConstant %6 0
         %11 = OpConstant %6 1
         %12 = OpConstantComposite %7 %10 %11
         %13 = OpTypeBool
         %14 = OpConstantFalse %13
          %4 = OpFunction %2 None %3
          %5 = OpLabel
          %9 = OpVariable %8 Function
               OpStore %9 %12
               OpSelectionMerge %16 None
               OpBranchConditional %14 %15 %16
         %15 = OpLabel
               OpBranch %16
         %16 = OpLabel
               OpReturn
               OpFunctionEnd
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_4;
  const auto consumer = nullptr;
  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
  spvtools::ValidatorOptions validator_options;
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));
  TransformationContext transformation_context(
      MakeUnique<FactManager>(context.get()), validator_options);
  transformation_context.GetFactManager()->AddFactBlockIsDead(15);
  TransformationCompositeExtract transformation(
      MakeInstructionDescriptor(15, SpvOpBranch, 0), 100, 12, {0});
  ASSERT_TRUE(
      transformation.IsApplicable(context.get(), transformation_context));
  ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context);
  ASSERT_FALSE(transformation_context.GetFactManager()->IsSynonymous(
      MakeDataDescriptor(100, {}), MakeDataDescriptor(12, {0})));
}

}  // namespace
}  // namespace fuzz
}  // namespace spvtools


text:
$(document).ready(function () {
	$('#admin_login').validate();
	$('#category_create').validate();
	$('#category_modify').validate();

	 $(".carefulDelete").click(function() {
        if(confirm("Confirm to Delete?")){
            return true;
        }else{

            return false;
        }
    });
});


text:
package org.keycloak.connections.mongo.impl.types;

import com.mongodb.BasicDBObject;
import org.keycloak.connections.mongo.api.types.Mapper;
import org.keycloak.connections.mongo.api.types.MapperContext;
import org.keycloak.connections.mongo.api.types.MapperRegistry;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Marek Posolda
 */
public class BasicDBObjectToMapMapper implements Mapper<BasicDBObject, Map> {

    private final MapperRegistry mapperRegistry;

    public BasicDBObjectToMapMapper(MapperRegistry mapperRegistry) {
        this.mapperRegistry = mapperRegistry;
    }

    @Override
    public Map convertObject(MapperContext<BasicDBObject, Map> context) {
        BasicDBObject dbObjectToConvert = context.getObjectToConvert();
        Type expectedElementValueType = context.getGenericTypes().get(1);

        HashMap<String, Object> result = new HashMap<String, Object>();
        for (Map.Entry<String, Object> entry : dbObjectToConvert.entrySet()) {
            String key = entry.getKey();
            Object dbValue = entry.getValue();

            // Workaround as manually inserted numbers into mongo may be treated as "Double"
            if (dbValue instanceof Double && expectedElementValueType == Integer.class) {
                dbValue = ((Double)dbValue).intValue();
            }

            MapperContext<Object, Object> newContext = getMapperContext(dbValue, expectedElementValueType);
            Object value = mapperRegistry.convertDBObjectToApplicationObject(newContext);

            if (key.contains(MapMapper.DOT_PLACEHOLDER)) {
                key = key.replaceAll(MapMapper.DOT_PLACEHOLDER, ".");
            }

            result.put(key, value);
        }
        return result;
    }

    @Override
    public Class<? extends BasicDBObject> getTypeOfObjectToConvert() {
        return BasicDBObject.class;
    }

    @Override
    public Class<Map> getExpectedReturnType() {
        return Map.class;
    }

    private MapperContext<Object, Object> getMapperContext(Object dbValue, Type expectedElementValueType) {
        if (expectedElementValueType instanceof Class) {
            Class<?> clazz = (Class<?>) expectedElementValueType;
            return new MapperContext<>(dbValue, clazz, null);
        } else if (expectedElementValueType instanceof ParameterizedType) {
            ParameterizedType parameterized = (ParameterizedType) expectedElementValueType;
            Class<?> expectedClazz = (Class<?>) parameterized.getRawType();
            Type[] generics = parameterized.getActualTypeArguments();

            return new MapperContext<>(dbValue, expectedClazz, Arrays.asList(generics));
        } else {
            throw new IllegalArgumentException("Unexpected type: '" + expectedElementValueType + "' for converting " + dbValue);
        }
    }
}


text:
package websocket

import (
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"github.com/op/go-logging"
	"net"
	"net/http"
	"sync"
	"time"

	"github.com/gorilla/websocket"
)

// size of channel that the websocket writer
// routine pulls from
const WS_WRITE_CAPACITY = 5000
// size of channel that the websocket reader
// routine pushes websocket updates into
const WS_READ_CAPACITY = 10
// seconds to wait in between re-sending
// the keep alive ping
const KEEP_ALIVE_TIMEOUT = 10

func newWs(baseURL string, logTransport bool, log *logging.Logger) *ws {
	return &ws{
		BaseURL:      baseURL,
		downstream:   make(chan []byte, WS_READ_CAPACITY),
		quit:         make(chan error),
		kill:         make(chan interface{}),
		logTransport: logTransport,
		log:          log,
		lock:         &sync.RWMutex{},
		createTime:   time.Now(),
		writeChan:    make(chan []byte, WS_WRITE_CAPACITY),
	}
}

type ws struct {
	ws            *websocket.Conn
	lock          *sync.RWMutex
	BaseURL       string
	TLSSkipVerify bool
	downstream    chan []byte
	logTransport  bool
	log           *logging.Logger
	createTime    time.Time
	writeChan     chan []byte

	kill chan interface{} // signal to routines to kill
	quit chan error    	  // signal to parent with error, if applicable
}

func (w *ws) Connect() error {
	if w.ws != nil {
		return nil // no op
	}
	var d = websocket.Dialer{
		Subprotocols:    []string{"p1", "p2"},
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		Proxy:           http.ProxyFromEnvironment,
		HandshakeTimeout: time.Second * 10,
	}

	d.TLSClientConfig = &tls.Config{InsecureSkipVerify: w.TLSSkipVerify}

	w.log.Infof("connecting ws to %s", w.BaseURL)
	ws, resp, err := d.Dial(w.BaseURL, nil)
	if err != nil {
		if err == websocket.ErrBadHandshake {
			w.log.Errorf("bad handshake: status code %d", resp.StatusCode)
		}
		return err
	}
	w.ws = ws
	go w.listenWriteChannel()
	go w.listenWs()
	// Gorilla/go dont natively support keep alive pinging
	// so we need to keep sending a message down the channel to stop
	// tcp killing the connection
	go w.keepAlivePinger()
	return nil
}

func (w *ws) keepAlivePinger() {
	for {
		pingTimer := time.After(time.Second * KEEP_ALIVE_TIMEOUT)
		select {
		case <-w.kill:
			return
		case <-pingTimer:
			w.writeChan <- []byte("ping")
		}
	}
}

// Send marshals the given interface and then sends it to the API. This method
// can block so specify a context with timeout if you don't want to wait for too
// long.
func (w *ws) Send(ctx context.Context, msg interface{}) error {
	bs, err := json.Marshal(msg)
	if err != nil {
		return err
	}

	select {
	case <- ctx.Done():
		return ctx.Err()
	case <- w.kill: // ws closed
		return fmt.Errorf("websocket connection closed")
	default:
	}
	w.log.Debug("ws->srv: %s", string(bs))
	// push request into writer channel
	w.writeChan <- bs
	return nil
}

func (w *ws) Done() <-chan error {
	return w.quit
}

// listen for write requests and perform them
func (w *ws) listenWriteChannel() {
	for {
		select {
		case <-w.kill: // ws closed
			return
		case message := <- w.writeChan:
			wsWriter, err := w.ws.NextWriter(websocket.TextMessage)
			if err != nil {
				w.log.Error("Unable to provision ws connection writer: ", err)
				w.stop(err)
				return
			}
			_, err = wsWriter.Write(message)
			if err != nil {
				w.log.Error("Unable to write to ws: ", err)
				w.stop(err)
				return
			}
			if err := wsWriter.Close(); err != nil {
				w.log.Error("Unable to close ws connection writer: ", err)
				w.stop(err)
				return
			}
		}
	}
}

// listen on ws & fwd to listen()
func (w *ws) listenWs() {
	for {
		if w.ws == nil {
			return
		}
		select {
		case <-w.kill: // ws connection ended
			return
		default:
			_, msg, err := w.ws.ReadMessage()
			if err != nil {
				if cl, ok := err.(*websocket.CloseError); ok {
					w.log.Errorf("close error code: %d", cl.Code)
				}
				// a read during normal shutdown results in an OpError: op on closed connection
				if _, ok := err.(*net.OpError); ok {
					// general read error on a closed network connection, OK
					return
				}

				w.stop(err)
				return
			}
			w.log.Debugf("srv->ws: %s", string(msg))
			w.lock.RLock()
			if w.downstream == nil {
				w.lock.RUnlock()
				return
			}
			w.downstream <- msg
			w.lock.RUnlock()
		}
	}
}

func (w *ws) Listen() <-chan []byte {
	return w.downstream
}

func (w *ws) stop(err error) {
	w.lock.Lock()
	defer w.lock.Unlock()
	if w.ws != nil {
		close(w.kill)
		w.quit <- err // pass error back
		close(w.quit) // signal to parent listeners
		close(w.downstream)
		w.downstream = nil
		if err := w.ws.Close(); err != nil {
			w.log.Error(fmt.Errorf("error closing websocket: %s", err))
		}
		w.ws = nil
	}
}

// Close the websocket connection
func (w *ws) Close() {
	w.stop(fmt.Errorf("transport connection Close called"))
}


text:
@interface BubbleView : UIView

@property (nonatomic, retain) UIColor *fillColor;

@end


text:
var searchData=
[
  ['application',['Application',['../classwxump_1_1_application.html#aa214267e1c947f9150ed3aa7da293f9e',1,'wxump::Application']]],
  ['attachlistener',['attachListener',['../classwxump_1_1_application.html#a6860e1ba884ec0b0d3de7dfbb3338f20',1,'wxump::Application']]]
];


text:
package org.puyallupfamilyhistorycenter.service.models;

import com.google.gson.Gson;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 *
 * @author tibbitts
 */

@Ignore
@RunWith(Parameterized.class)
public class PersonTest {

    @Parameters
    public static List<Object[]> parameters() {
        return Arrays.asList(new Object[][] {
            { "{\"living\":true}", new PersonBuilder().build() },
            { "{\"id\":\"asdf-sdf\",\"living\":true}", new PersonBuilder().withId("asdf-sdf").build() },
            { "{\"name\":\"Graham Trey Tibbitts\",\"living\":true}", new PersonBuilder().withName("Graham Trey Tibbitts").build() },
            { "{\"gender\":\"male\",\"living\":true}", new PersonBuilder().withGender("male").build() },
            {
                "{\"living\":true,\"facts\":[{\"type\":\"birth\",\"date\":\"23 December 1897\",\"sortableDate\":\"18971223\",\"place\":\"San Jacinto, Riverside, California, United States\"}]}",
                new PersonBuilder().withFacts(new Fact[] {new Fact("birth", "23 December 1897", "+18971223", 1897, "San Jacinto, Riverside, California, United States")}).build()
            },
            {
                "{\"living\":true,\"parents\":[{\"id\":\"asdf-sdf\",\"name\":\"William Datus Tibbitts\",\"relationship\":\"father\"}]}",
                new PersonBuilder().withParents(new PersonReference[] {new PersonReference("asdf-sdf", "William Datus Tibbitts", "father")}).build()
            },
            {
                "{\"living\":true,\"spouses\":[{\"id\":\"asdf-sdf\",\"name\":\"Katrina Kay Huffman\",\"relationship\":\"wife\"}]}",
                new PersonBuilder().withSpouses(new PersonReference[] {new PersonReference("asdf-sdf", "Katrina Kay Huffman", "wife")}).build()
            },
            {
                "{\"living\":true,\"children\":[{\"id\":\"asdf-sdf\",\"name\":\"Allison Kay Huffman\",\"relationship\":\"daughter\"}]}",
                new PersonBuilder().withChildren(new PersonReference[] {new PersonReference("asdf-sdf", "Allison Kay Huffman", "daughter")}).build()
            },
            { "{\"id\":\"asdf-sdf\","
                    + "\"name\":\"Graham Trey Tibbitts\","
                    + "\"gender\":\"male\","
                    + "\"living\":true,"
                    + "\"facts\":[{\"type\":\"birth\",\"date\":\"23 December 1897\",\"sortableDate\":\"18971223\",\"place\":\"San Jacinto, Riverside, California, United States\"}],"
                    + "\"parents\":[{\"id\":\"asdf-sdf\",\"name\":\"William Datus Tibbitts\",\"relationship\":\"father\"}],"
                    + "\"spouses\":[{\"id\":\"asdf-sdf\",\"name\":\"Katrina Kay Huffman\",\"relationship\":\"wife\"}],"
                    + "\"children\":[{\"id\":\"asdf-sdf\",\"name\":\"Allison Kay Huffman\",\"relationship\":\"daughter\"}]}",
                new PersonBuilder().withId("asdf-sdf")
                        .withName("Graham Trey Tibbitts")
                        .withGender("male")
                        .withFacts(new Fact[] {new Fact("birth", "23 December 1897", "+18971223", 1897, "San Jacinto, Riverside, California, United States")})
                        .withParents(new PersonReference[] {new PersonReference("asdf-sdf", "William Datus Tibbitts", "father")})
                        .withSpouses(new PersonReference[] {new PersonReference("asdf-sdf", "Katrina Kay Huffman", "wife")})
                        .withChildren(new PersonReference[] {new PersonReference("asdf-sdf", "Allison Kay Huffman", "daughter")})
                        .build()
            },
        });
    }

    private static final Gson GSON = new Gson();
    private final String json;
    private final Person person;
    public PersonTest(String json, Person person) {
        this.person = person;
        this.json = json;
    }

    @Test
    public void testSerialize() {
        String serialized = GSON.toJson(person);
        assertEquals(json, serialized);
    }

    @Test
    public void testDeserialize() {
        Person deserialized = GSON.fromJson(json, Person.class);
        assertEquals(person, deserialized);
    }

}


text:
package com.tle.web.selection.section;

import com.tle.beans.item.VersionSelection;
import com.tle.web.sections.SectionInfo;

public interface VersionChoiceDecider {
  VersionSelection getVersionSelection(SectionInfo info);
}