text:
[![GitHub version](https://badge.fury.io/gh/andrewradev%2Fswitch.vim.svg)](https://badge.fury.io/gh/andrewradev%2Fswitch.vim)
[![Build Status](https://secure.travis-ci.org/AndrewRadev/switch.vim.svg?branch=master)](http://travis-ci.org/AndrewRadev/switch.vim)

## Screencast!

This plugin is easier to demonstrate than explain. You can find a screencast
[here](http://youtu.be/zIOOLZJb87U).

## Usage

The main entry point of the plugin is a single command, `:Switch`. When the
command is executed, the plugin looks for one of a few specific patterns under
the cursor and performs a substitution depending on the pattern. For example, if
the cursor is on the "true" in the following code:

``` ruby
flag = true
```

Then, upon executing `:Switch`, the "true" will turn into "false".

There's a default mapping to trigger the command, `gs`. Note that this is
already a Vim built-in, but it doesn't seem particularly useful.

If you'd like to change the mapping, change the value of `g:switch_mapping`.
For example, to map it to "-", place the following in your .vimrc:

``` vim
let g:switch_mapping = "-"
```

To avoid the default mapping completely, set the variable to an empty string:

``` vim
let g:switch_mapping = ""
```

See the "customization" section below for information on how to create several
mappings with different definitions.

There are three main principles that the substitution follows:

1. The cursor needs to be on the match. Regardless of the pattern, the plugin
   only performs the substitution if the cursor is positioned in the matched
   text.

2. When several patterns match, the shortest match is performed. For example,
   in ruby, the following switch is defined:

   ``` ruby
   { :foo => true }
   # switches into:
   { foo: true }
   ```

   This works if the cursor is positioned somewhere on the ":foo =>" part, but
   if it's on top of "true", the abovementioned true -> false substitution will
   be performed instead. If you want to perform a "larger" substitution instead,
   you could move your cursor away from the "smaller" match. In this case,
   move the cursor away from the "true" keyword.

3. When several patterns with the same size match, the order of the
   definitions is respected. For instance, in eruby, the following code can be
   transformed:

   ``` erb
   <% if foo? %>
   could switch into:
   <%# if foo? %>
   but instead, it would switch into:
   <% if true or (foo?) %>
   ```

   The second switch will be performed, simply because in the definition list,
   the pattern was placed at a higher spot. In this case, this seems to make
   sense to prioritize one over the other. If it's needed to prioritize in a
   different way, the definition list should be redefined by the user.

## Advanced usage

Instead of using the `:Switch` and `:SwitchReverse` commands, you can use the
autoloaded function `switch#Switch`. Calling it without any arguments is the
same as calling the `:Switch` command:

``` vim
:call switch#Switch()
" equivalent to:
:Switch
```

However, you can also call the function with a dict of options. Instead of
`:SwitchReverse`, you can invoke it with the `reverse` option:

``` vim
:call switch#Switch({'reverse': 1})
" or,
:call switch#Switch({'reverse': v:true})
" equivalent to:
:SwitchReverse
```

The other option you can provide is `definitions` to set an explicit list of
definitions that are different from the built-ins.

``` vim
:call switch#Switch({'definitions': list_of_definitions})
```

The `switch#Switch()` function returns 1 if it succeeded, and 0 if it failed.
You can use the return value to decide if you'd like to apply some other mapping.

See below in "Customization" for more details and examples on how to write
use this function.

## Customization

*Note: for more switches by the community, take a look at the
[wiki](https://github.com/AndrewRadev/switch.vim/wiki)*

There are two variables that hold the global definition list and the
buffer-local definition list -- `g:switch_definitions` and
`b:switch_definitions`, respectively. These contain the definitions for the
built-ins provided by the plugin. In order to add the switches you want, you
should override `g:switch_custom_definitions` and
`b:switch_custom_definitions` instead.

The format of the variables is a simple List of items. Each item can be either
a List or a Dict.

### List definitions

``` vim
let g:switch_custom_definitions =
    \ [
    \   ['foo', 'bar', 'baz']
    \ ]
```

With this definition list, if the plugin encounters "foo" under the cursor, it
will be changed to "bar". If it sees "bar", it will change it to "baz", and
"baz" would be turned into "foo". This is the simple case of a definition that
is implemented (in a slightly different way) by the "toggle.vim" plugin.

You might want this to work for different capitalizations, like with `true`
and `True` and `TRUE`. You might also want to also affect only word
boundaries. While you could use the more complicated dict definition, a simple
way to tackle these scenarios is with modifier functions:

- `switch#NormalizedCase`
- `switch#Words`
- `switch#NormalizedCaseWords`

Here's how you might use these:

``` vim
let g:switch_custom_definitions =
    \ [
    \   switch#NormalizedCase(['one', 'two']),
    \   switch#Words(['three', 'four']),
    \   switch#NormalizedCaseWords(['five', 'six']),
    \ ]
```

The result of this is that:
- The first definition would switch between "one" and "two", between "One" and
  "Two", and between "ONE" and "TWO".
- The second definition would switch between "three" and "four" only at word
  boundaries, as if the patterns have `\<` and `\>` modifiers added to them.
- The third would switch between "five"/"six", "Five"/"Six", "FIVE"/"SIX" only
  at word boundaries with a combination of the above.

See `:help switch-internals` for some information on the underlying data
format if you'd like to use a different method to generate definitions (like,
say, loading JSON).

Leaving lists aside, the more complicated (and more powerful) way to define a
switch pattern is by using a Dict. In fact, a list definition is processed
into three dict definitions, one for each pair of switches.

### Dict definitions

``` vim
autocmd FileType eruby let b:switch_custom_definitions =
    \ [
    \   {
    \     ':\(\k\+\)\s\+=>': '\1:',
    \     '\<\(\k\+\):':     ':\1 =>',
    \   },
    \ ]
```

When in the eruby filetype, the hash will take effect. The plugin will look
for something that looks like `:foo =>` and replace it with `foo: `, or the
reverse -- `foo: `, so it could turn it into `:foo =>`. The search string is
fed to the `search()` function, so all special patterns like `\%l` have effect
in it. And the replacement string is used in the `:substitute` command, so all
of its replacement patterns work as well.

Notice the use of `autocmd FileType eruby` to set the buffer-local variable
whenever an eruby file is loaded. The same effect could be achieved by placing
this definition in `ftplugin/eruby.vim`.

Another interesting example is the following definition:

``` vim
autocmd FileType php let b:switch_custom_definitions =
      \ [
      \   {
      \     '<?php echo \(.\{-}\) ?>':        '<?php \1 ?>',
      \     '<?php \%(echo\)\@!\(.\{-}\) ?>': '<?php echo \1 ?>',
      \   }
      \ ]
```

In this case, when in the "php" filetype, the plugin will attempt to remove
the "echo" in "<?php echo 'something' ?>" or vice-versa. However, the second
pattern wouldn't work properly if it didn't contain "\%(echo\)\@!". This
pattern asserts that, in this place of the text, there is no "echo".
Otherwise, the second pattern would match as well. Using the `\@!` pattern in
strategic places is important in many cases.

For even more complicated substitutions, you can use the nested form.

### Nested dict definitions

The following expression replaces underscored identifier names with their
camelcased versions.

``` vim
let b:switch_custom_definitions = [
      \   {
      \     '\<[a-z0-9]\+_\k\+\>': {
      \       '_\(.\)': '\U\1'
      \     },
      \     '\<[a-z0-9]\+[A-Z]\k\+\>': {
      \       '\([A-Z]\)': '_\l\1'
      \     },
      \   }
      \ ]
```

If the cursor is on "foo_bar_baz", then switching would produce "fooBarBaz"
and vice-versa. The logic is as follows:

  - The keys of the dict are patterns, just like the "normal" dict version.
  - The values of the dict are dicts with patterns for keys and replacements
    for values.

The goal of this form is to enable substituting several different kinds of
patterns within the limits of another one. In this example, there's no way to
define this switch using the simpler form, since there's an unknown number of
underscores in the variable name and all of them need to be replaced in order
to make the switch complete.

The nested patterns differ from the simple one in that each one of them is
replaced globally, only within the limits of the "parent" pattern.

Note that this particular example is **NOT** included as a built-in, since it
may overshadow other ones and is probably not that useful, either (it's rare
that a language would require changing between the two forms). An example usage
may be within javascript, if your server-side variables are underscored and the
client-side ones need to be camelcased. For something more complete, you can
take a look at [this gist](https://gist.github.com/othree/5655583).

You could also use a separate mapping for that.

### Separate mappings

While there's a default mapping for `:Switch`, you could actually define
several mappings with your own custom definitions:

``` vim
let g:variable_style_switch_definitions = [
      \   {
      \     '\<[a-z0-9]\+_\k\+\>': {
      \       '_\(.\)': '\U\1'
      \     },
      \     '\<[a-z0-9]\+[A-Z]\k\+\>': {
      \       '\([A-Z]\)': '_\l\1'
      \     },
      \   }
      \ ]
nnoremap + :call switch#Switch({'definitions': g:variable_style_switch_definitions})<cr>
nnoremap - :Switch<cr>
```

With this, typing `-` would invoke the built-in switch definitions, while
typing `+` would switch between camelcase and underscored variable styles.
This may be particularly useful if you have several clashing switches on
patterns that match similar things.

### More complicated mappings

By using the `switch#Switch()` function, you can also write more complicated
mappings that check if a switch succeeded, and apply some fallback if it
didn't. The function returns 1 for success and 0 for failure.

For example, if you want to switch, or fall back to activating the
[speeddating](https://github.com/tpope/vim-speeddating) plugin, you could map
`<c-a>` and `<c-x>` like so:

``` vim
" Don't use default mappings
let g:speeddating_no_mappings = 1

" Avoid issues because of us remapping <c-a> and <c-x> below
nnoremap <Plug>SpeedDatingFallbackUp <c-a>
nnoremap <Plug>SpeedDatingFallbackDown <c-x>

" Manually invoke speeddating in case switch didn't work
nnoremap <c-a> :if !switch#Switch() <bar>
      \ call speeddating#increment(v:count1) <bar> endif<cr>
nnoremap <c-x> :if !switch#Switch({'reverse': 1}) <bar>
      \ call speeddating#increment(-v:count1) <bar> endif<cr>
```

## Builtins

Here's a list of all the built-in switch definitions. To see the actual
definitions with their patterns and replacements, look at the file
[plugin/switch.vim](https://github.com/AndrewRadev/switch.vim/blob/master/plugin/switch.vim).

### Global

* Boolean conditions:
  ```
  foo && bar
  foo || bar
  ```

* Boolean constants:
  ```
  flag = true
  flag = false

  flag = True
  flag = False
  ```

### Ruby

* Hash style:
  ``` ruby
  foo = { :one => 'two' }
  foo = { one: 'two' }
  ```

* If-clauses:
  ``` ruby
  if predicate?
    puts 'Hello, World!'
  end

  if true or (predicate?)
    puts 'Hello, World!'
  end

  if false and (predicate?)
    puts 'Hello, World!'
  end
  ```

* Rspec `should`/`should_not`:
  ``` ruby
  1.should eq 1
  1.should_not eq 1
  ```

* Tap:
  ``` ruby
  foo = user.comments.map(&:author).first
  foo = user.comments.tap { |o| puts o.inspect }.map(&:author).first
  ```

* String style:
  ``` ruby
  foo = 'bar'
  foo = "baz"
  foo = :baz
  ```
  (Note that it only works for single-word strings.)

* Ruby block shorthands:
  ``` ruby
  do_something { |x| x.some_work! }
  do_something(&:some_work!)
  ```

* Array shorthands:
  ``` ruby
  ['one', 'two', 'three']
  %w(one two three)
  ```

  ``` ruby
  [:one, :two, :three]
  %i(one two three)
  ```
  (In this case, be careful to not have the cursor on one of the strings/symbols, or you'll trigger the string switch as seen above.)

### PHP "echo" in tags:

``` php
<?php "Text" ?>
<?php echo "Text" ?>
```

### Eruby

* If-clauses:
  ``` erb
  <% if predicate? %>
    <%= 'Hello, World!' %>
  <% end %>

  <% if true or (predicate?) %>
    <%= 'Hello, World!' %>
  <% end %>

  <% if false and (predicate?) %>
    <%= 'Hello, World!' %>
  <% end %>
  ```

* Tag type:
  ``` erb
  <% something %>
  <%# something %>
  <%= something %>
  ```

* Hash style:
  ``` erb
  <% foo = { :one => 'two' } %>
  <% foo = { one: 'two' } %>
  ```

### Haml

* If-clauses:
  ``` haml
  - if predicate?
    Hello, World!

  - if true or (predicate?)
    Hello, World!

  - if false and (predicate?)
    Hello, World!
  ```

* Tag type:
  ``` haml
  - something
  -# something
  = something
  ```

* Hash style:
  ``` haml
  %a{:href => '/example'}
  %a{href: '/example'}
  ```

### C++ pointer dots/arrows:

``` cpp
Object* foo = bar.baz;
Object* foo = bar->baz;
```
### JavaScript

* Function definitions:
  ``` javascript
  function example(one, two) { }
  var example = function(one, two) { }
  ```

* ES6-style arrow functions:
  ``` javascript
  var example = function(one, two) { }
  var example = (one, two) => { }
  ```

* ES6-style variable declarations:
  ``` javascript
  var example
  let example
  const example
  // var -> let
  // let -> const
  // const -> let
  ```
  Switching to var from const or let is unsupported, since it's assumed to be an unlikely case.

### CoffeeScript arrows

``` coffeescript
functionCall (foo) ->
functionCall (foo) =>
```

### CoffeeScript dictionary shorthands

``` coffeescript
foo = {one, two}
foo = {one: one, two}
```

### Clojure

* String style:
  ``` clojure
  "baz"
  'bar
  :baz
  ```
  (Note that it only works for single-word strings, such as `baz`, `b-a-z`, or `**`.)

* If-clauses:
  ``` clojure
  (if predicate?
    (prn "Hello, world!")
    (prn "oh..."))

  (if (or true predicate?)
    (prn "Hello, world!")
    (prn "oh..."))

  (if (and false predicate?)
    (prn "Hello, world!")
    (prn "oh..."))
  ```
  (Note that it also works for `if-not`, `when`, and `when-not`.)

### Scala

* String style:
  ``` scala
  "foo bar"
  s"foo bar"
  f"foo bar"
  """foo bar"""
  s"""foo bar"""
  f"""foo bar"""
  ```

### Git Rebase

* Git Rebase Commands
  ```
    pick -> fixup -> reword -> edit -> squash -> exec -> break -> drop -> label -> reset -> merge -> (loops back to pick)

    p -> fixup
    f -> reword
    r -> edit
    e -> squash
    s -> exec
    x -> break
    b -> drop
    d -> label
    l -> reset
    t -> merge
    m -> pick
  ```

### Elixir

Charlist -> Binary -> Atom

``` elixir
foo = 'bar'
foo = "bar"
foo = :bar
```

Elixir list shorthands

``` elixir
["one", "two", "three"]
~w(one two three)

[:one, :two, :three]
~w(one two three)a
```

Capitalized boolean constants :

``` elixir
flag = True
flag = False
```

### Rust

Void typecheck

``` rust
let value = complicated_expression();
let value: () = complicated_expression();
```

### TOML

Particularly for files named `Cargo.toml` with the `toml` filetype (not built-in, but there are plugins for it):

``` toml
structopt = "0.3.5"
structopt = { version = "0.3.5" }
```

## Similar work

This plugin is very similar to two other ones:
  - [toggle.vim](http://www.vim.org/scripts/script.php?script_id=895)
  - [cycle.vim](https://github.com/zef/vim-cycle)

Both of these work on replacing a specific word under the cursor with a
different one. The benefit of switch.vim is that it works for much more
complicated patterns. The drawback is that this makes extending it more
involved. I encourage anyone that doesn't need the additional power in
switch.vim to take a look at one of these two.

## Contributing

If you'd like to hack on the plugin, please see
[CONTRIBUTING.md](https://github.com/AndrewRadev/switch.vim/blob/master/CONTRIBUTING.md) first.

## Issues

Any issues and suggestions are very welcome on the
[github bugtracker](https://github.com/AndrewRadev/switch.vim/issues).


text:
CREATE TABLE [Sales].[BuyingGroups_Archive] (
    [BuyingGroupID]   INT           NOT NULL,
    [BuyingGroupName] NVARCHAR (50) NOT NULL,
    [LastEditedBy]    INT           NOT NULL,
    [ValidFrom]       DATETIME2 (7) NOT NULL,
    [ValidTo]         DATETIME2 (7) NOT NULL
);

GO
CREATE CLUSTERED INDEX [ix_BuyingGroups_Archive]
    ON [Sales].[BuyingGroups_Archive]([ValidTo] ASC, [ValidFrom] ASC) WITH (DATA_COMPRESSION = PAGE);

redpajama_set_name: RedPajamaGithub


text:
package androidx.camera.camera2.internal;

import static com.google.common.truth.Truth.assertThat;

import static org.mockito.Mockito.when;

import android.os.Build;
import android.view.Display;
import android.view.Surface;

import androidx.camera.core.CameraInfo;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.DisplayOrientedMeteringPointFactory;
import androidx.camera.core.MeteringPoint;
import androidx.camera.core.MeteringPointFactory;
import androidx.camera.testing.fakes.FakeCameraInfoInternal;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.internal.DoNotInstrument;

@RunWith(RobolectricTestRunner.class)
@DoNotInstrument
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
public class DisplayOrientedMeteringPointFactoryTest {
    private static final float WIDTH = 480;
    private static final float HEIGHT = 640;

    private Display mMockDisplay;

    private CameraInfo mFrontCameraInfo;
    private CameraInfo mBackCameraInfo;

    @Before
    public void setUp() {
        mFrontCameraInfo = new FakeCameraInfoInternal(270, CameraSelector.LENS_FACING_FRONT);
        mBackCameraInfo = new FakeCameraInfoInternal(90, CameraSelector.LENS_FACING_BACK);

        mMockDisplay = Mockito.mock(Display.class);
        when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_0);
    }

    @Test
    public void defaultAreaSize() {
        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mBackCameraInfo, WIDTH, HEIGHT);

        MeteringPoint point = factory.createPoint(0, 0);
        assertThat(point.getSize()).isEqualTo(MeteringPointFactory.getDefaultPointSize());
        assertThat(point.getSurfaceAspectRatio()).isNull();
    }

    @Test
    public void createPointWithValidAreaSize() {
        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mBackCameraInfo, WIDTH, HEIGHT);

        final float areaSize = 0.2f;
        MeteringPoint point = factory.createPoint(0, 0, areaSize);
        assertThat(point.getSize()).isEqualTo(areaSize);
        assertThat(point.getSurfaceAspectRatio()).isNull();
    }

    @Test
    public void display0_back() {
        when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_0);

        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mBackCameraInfo, WIDTH, HEIGHT);

        MeteringPoint meteringPoint = factory.createPoint(0f, 0f);
        assertThat(meteringPoint.getX()).isEqualTo(0f);
        assertThat(meteringPoint.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint2 = factory.createPoint(0f, HEIGHT);
        assertThat(meteringPoint2.getX()).isEqualTo(1f);
        assertThat(meteringPoint2.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint3 = factory.createPoint(WIDTH, 0f);

        assertThat(meteringPoint3.getX()).isEqualTo(0f);
        assertThat(meteringPoint3.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint4 = factory.createPoint(WIDTH, HEIGHT);

        assertThat(meteringPoint4.getX()).isEqualTo(1f);
        assertThat(meteringPoint4.getY()).isEqualTo(0f);
    }

    @Test
    public void display0_front() {
        when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_0);

        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mFrontCameraInfo, WIDTH, HEIGHT);

        MeteringPoint meteringPoint = factory.createPoint(0f, 0f);
        assertThat(meteringPoint.getX()).isEqualTo(1f);
        assertThat(meteringPoint.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint2 = factory.createPoint(0f, HEIGHT);
        assertThat(meteringPoint2.getX()).isEqualTo(0f);
        assertThat(meteringPoint2.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint3 = factory.createPoint(WIDTH, 0f);

        assertThat(meteringPoint3.getX()).isEqualTo(1f);
        assertThat(meteringPoint3.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint4 = factory.createPoint(WIDTH, HEIGHT);

        assertThat(meteringPoint4.getX()).isEqualTo(0f);
        assertThat(meteringPoint4.getY()).isEqualTo(0f);
    }

    @Test
    public void display90_back() {
        when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_90);

        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mBackCameraInfo, WIDTH, HEIGHT);

        MeteringPoint meteringPoint = factory.createPoint(0f, 0f);
        assertThat(meteringPoint.getX()).isEqualTo(0f);
        assertThat(meteringPoint.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint2 = factory.createPoint(0f, HEIGHT);
        assertThat(meteringPoint2.getX()).isEqualTo(0f);
        assertThat(meteringPoint2.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint3 = factory.createPoint(WIDTH, 0f);

        assertThat(meteringPoint3.getX()).isEqualTo(1f);
        assertThat(meteringPoint3.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint4 = factory.createPoint(WIDTH, HEIGHT);

        assertThat(meteringPoint4.getX()).isEqualTo(1f);
        assertThat(meteringPoint4.getY()).isEqualTo(1f);
    }

    @Test
    public void display90_front() {
        when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_90);

        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mFrontCameraInfo, WIDTH, HEIGHT);

        MeteringPoint meteringPoint = factory.createPoint(0f, 0f);
        assertThat(meteringPoint.getX()).isEqualTo(1f);
        assertThat(meteringPoint.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint2 = factory.createPoint(0f, HEIGHT);
        assertThat(meteringPoint2.getX()).isEqualTo(1f);
        assertThat(meteringPoint2.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint3 = factory.createPoint(WIDTH, 0f);

        assertThat(meteringPoint3.getX()).isEqualTo(0f);
        assertThat(meteringPoint3.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint4 = factory.createPoint(WIDTH, HEIGHT);

        assertThat(meteringPoint4.getX()).isEqualTo(0f);
        assertThat(meteringPoint4.getY()).isEqualTo(1f);
    }

    @Test
    public void display180_back() {
        when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_180);

        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mBackCameraInfo, WIDTH, HEIGHT);

        MeteringPoint meteringPoint = factory.createPoint(0f, 0f);
        assertThat(meteringPoint.getX()).isEqualTo(1f);
        assertThat(meteringPoint.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint2 = factory.createPoint(0f, HEIGHT);
        assertThat(meteringPoint2.getX()).isEqualTo(0f);
        assertThat(meteringPoint2.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint3 = factory.createPoint(WIDTH, 0f);

        assertThat(meteringPoint3.getX()).isEqualTo(1f);
        assertThat(meteringPoint3.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint4 = factory.createPoint(WIDTH, HEIGHT);

        assertThat(meteringPoint4.getX()).isEqualTo(0f);
        assertThat(meteringPoint4.getY()).isEqualTo(1f);
    }

    @Test
    public void display180_front() {
        when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_180);

        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mFrontCameraInfo, WIDTH, HEIGHT);

        MeteringPoint meteringPoint = factory.createPoint(0f, 0f);
        assertThat(meteringPoint.getX()).isEqualTo(0f);
        assertThat(meteringPoint.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint2 = factory.createPoint(0f, HEIGHT);
        assertThat(meteringPoint2.getX()).isEqualTo(1f);
        assertThat(meteringPoint2.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint3 = factory.createPoint(WIDTH, 0f);

        assertThat(meteringPoint3.getX()).isEqualTo(0f);
        assertThat(meteringPoint3.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint4 = factory.createPoint(WIDTH, HEIGHT);

        assertThat(meteringPoint4.getX()).isEqualTo(1f);
        assertThat(meteringPoint4.getY()).isEqualTo(1f);
    }

    @Test
    public void display270_back() {
        when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_270);

        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mBackCameraInfo, WIDTH, HEIGHT);

        MeteringPoint meteringPoint = factory.createPoint(0f, 0f);
        assertThat(meteringPoint.getX()).isEqualTo(1f);
        assertThat(meteringPoint.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint2 = factory.createPoint(0f, HEIGHT);
        assertThat(meteringPoint2.getX()).isEqualTo(1f);
        assertThat(meteringPoint2.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint3 = factory.createPoint(WIDTH, 0f);

        assertThat(meteringPoint3.getX()).isEqualTo(0f);
        assertThat(meteringPoint3.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint4 = factory.createPoint(WIDTH, HEIGHT);

        assertThat(meteringPoint4.getX()).isEqualTo(0f);
        assertThat(meteringPoint4.getY()).isEqualTo(0f);
    }

    @Test
    public void display270_front() {
        when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_270);

        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mFrontCameraInfo, WIDTH, HEIGHT);

        MeteringPoint meteringPoint = factory.createPoint(0f, 0f);
        assertThat(meteringPoint.getX()).isEqualTo(0f);
        assertThat(meteringPoint.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint2 = factory.createPoint(0f, HEIGHT);
        assertThat(meteringPoint2.getX()).isEqualTo(0f);
        assertThat(meteringPoint2.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint3 = factory.createPoint(WIDTH, 0f);

        assertThat(meteringPoint3.getX()).isEqualTo(1f);
        assertThat(meteringPoint3.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint4 = factory.createPoint(WIDTH, HEIGHT);

        assertThat(meteringPoint4.getX()).isEqualTo(1f);
        assertThat(meteringPoint4.getY()).isEqualTo(0f);
    }

    @Test
    public void display0_front_useCustomDisplay() {
        when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_270);

        DisplayOrientedMeteringPointFactory factory = new DisplayOrientedMeteringPointFactory(
                mMockDisplay, mFrontCameraInfo, WIDTH, HEIGHT);

        MeteringPoint meteringPoint = factory.createPoint(0f, 0f);
        assertThat(meteringPoint.getX()).isEqualTo(0f);
        assertThat(meteringPoint.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint2 = factory.createPoint(0f, HEIGHT);
        assertThat(meteringPoint2.getX()).isEqualTo(0f);
        assertThat(meteringPoint2.getY()).isEqualTo(0f);

        MeteringPoint meteringPoint3 = factory.createPoint(WIDTH, 0f);

        assertThat(meteringPoint3.getX()).isEqualTo(1f);
        assertThat(meteringPoint3.getY()).isEqualTo(1f);

        MeteringPoint meteringPoint4 = factory.createPoint(WIDTH, HEIGHT);

        assertThat(meteringPoint4.getX()).isEqualTo(1f);
        assertThat(meteringPoint4.getY()).isEqualTo(0f);
    }

}


text:
mod validate_connections;

use validate_connections::transform_fixture;
use fixture_tests::test_fixture;

#[test]
fn connection() {
    let input = include_str!("validate_connections/fixtures/connection.graphql");
    let expected = include_str!("validate_connections/fixtures/connection.expected");
    test_fixture(transform_fixture, "connection.graphql", "validate_connections/fixtures/connection.expected", input, expected);
}

#[test]
fn connection_directions() {
    let input = include_str!("validate_connections/fixtures/connection-directions.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-directions.expected");
    test_fixture(transform_fixture, "connection-directions.graphql", "validate_connections/fixtures/connection-directions.expected", input, expected);
}

#[test]
fn connection_empty_filters() {
    let input = include_str!("validate_connections/fixtures/connection-empty-filters.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-empty-filters.expected");
    test_fixture(transform_fixture, "connection-empty-filters.graphql", "validate_connections/fixtures/connection-empty-filters.expected", input, expected);
}

#[test]
fn connection_filters() {
    let input = include_str!("validate_connections/fixtures/connection-filters.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-filters.expected");
    test_fixture(transform_fixture, "connection-filters.graphql", "validate_connections/fixtures/connection-filters.expected", input, expected);
}

#[test]
fn connection_filters_null_invalid() {
    let input = include_str!("validate_connections/fixtures/connection-filters-null.invalid.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-filters-null.invalid.expected");
    test_fixture(transform_fixture, "connection-filters-null.invalid.graphql", "validate_connections/fixtures/connection-filters-null.invalid.expected", input, expected);
}

#[test]
fn connection_generate_filters() {
    let input = include_str!("validate_connections/fixtures/connection-generate-filters.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-generate-filters.expected");
    test_fixture(transform_fixture, "connection-generate-filters.graphql", "validate_connections/fixtures/connection-generate-filters.expected", input, expected);
}

#[test]
fn connection_invalid_key_name_invalid() {
    let input = include_str!("validate_connections/fixtures/connection-invalid-key-name.invalid.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-invalid-key-name.invalid.expected");
    test_fixture(transform_fixture, "connection-invalid-key-name.invalid.graphql", "validate_connections/fixtures/connection-invalid-key-name.invalid.expected", input, expected);
}

#[test]
fn connection_invalid_key_type_invalid() {
    let input = include_str!("validate_connections/fixtures/connection-invalid-key-type.invalid.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-invalid-key-type.invalid.expected");
    test_fixture(transform_fixture, "connection-invalid-key-type.invalid.graphql", "validate_connections/fixtures/connection-invalid-key-type.invalid.expected", input, expected);
}

#[test]
fn connection_invalid_type_invalid() {
    let input = include_str!("validate_connections/fixtures/connection-invalid-type.invalid.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-invalid-type.invalid.expected");
    test_fixture(transform_fixture, "connection-invalid-type.invalid.graphql", "validate_connections/fixtures/connection-invalid-type.invalid.expected", input, expected);
}

#[test]
fn connection_missing_edges_selection_invalid() {
    let input = include_str!("validate_connections/fixtures/connection-missing-edges-selection.invalid.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-missing-edges-selection.invalid.expected");
    test_fixture(transform_fixture, "connection-missing-edges-selection.invalid.graphql", "validate_connections/fixtures/connection-missing-edges-selection.invalid.expected", input, expected);
}

#[test]
fn connection_missing_first_arg_invalid() {
    let input = include_str!("validate_connections/fixtures/connection-missing-first-arg.invalid.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-missing-first-arg.invalid.expected");
    test_fixture(transform_fixture, "connection-missing-first-arg.invalid.graphql", "validate_connections/fixtures/connection-missing-first-arg.invalid.expected", input, expected);
}

#[test]
fn connection_with_aliased_edges_page_info() {
    let input = include_str!("validate_connections/fixtures/connection-with-aliased-edges-page-info.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-with-aliased-edges-page-info.expected");
    test_fixture(transform_fixture, "connection-with-aliased-edges-page-info.graphql", "validate_connections/fixtures/connection-with-aliased-edges-page-info.expected", input, expected);
}

#[test]
fn connection_with_custom_handler() {
    let input = include_str!("validate_connections/fixtures/connection-with-custom-handler.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-with-custom-handler.expected");
    test_fixture(transform_fixture, "connection-with-custom-handler.graphql", "validate_connections/fixtures/connection-with-custom-handler.expected", input, expected);
}

#[test]
fn connection_with_invalid_custom_handler_invalid() {
    let input = include_str!("validate_connections/fixtures/connection-with-invalid-custom-handler.invalid.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-with-invalid-custom-handler.invalid.expected");
    test_fixture(transform_fixture, "connection-with-invalid-custom-handler.invalid.graphql", "validate_connections/fixtures/connection-with-invalid-custom-handler.invalid.expected", input, expected);
}

#[test]
fn connection_with_page_info() {
    let input = include_str!("validate_connections/fixtures/connection-with-page-info.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-with-page-info.expected");
    test_fixture(transform_fixture, "connection-with-page-info.graphql", "validate_connections/fixtures/connection-with-page-info.expected", input, expected);
}

#[test]
fn connection_with_variables() {
    let input = include_str!("validate_connections/fixtures/connection-with-variables.graphql");
    let expected = include_str!("validate_connections/fixtures/connection-with-variables.expected");
    test_fixture(transform_fixture, "connection-with-variables.graphql", "validate_connections/fixtures/connection-with-variables.expected", input, expected);
}


text:
import select
import uuid
import os
import docker
from docker.errors import DockerException
from girder_worker import logger

def select_loop(exit_condition=lambda: True, readers=None, writers=None):
    """
    Run a select loop for a set of readers and writers

    :param exit_condition: A function to evaluate to determine if the select
        loop should terminate if all pipes are empty.
    :type exit_condition: function
    :param readers: The list of ReaderStreamConnector's that will be added to the
        select call.
    :type readers: list
    :param writers: The list of WriteStreamConnector's that will be added to the
        select call.
    :type writers: list
    """

    BUF_LEN = 65536

    try:
        while True:
            # We evaluate this first so that we get one last iteration of
            # of the loop before breaking out of the loop.
            exit = exit_condition()

            open_writers = [writer for writer in writers if writer.fileno() is not None]

            # get ready pipes, timeout of 100 ms
            readable, writable, _ = select.select(readers, open_writers, (), 0.1)

            for ready in readable:
                read = ready.read(BUF_LEN)
                if read == 0:
                    readers.remove(ready)

            for ready in writable:
                # TODO for now it's OK for the input reads to block since
                # input generally happens first, but we should consider how to
                # support non-blocking stream inputs in the future.
                written = ready.write(BUF_LEN)
                if written == 0:
                    writers.remove(ready)

            need_opening = [writer for writer in writers if writer.fileno() is None]
            for connector in need_opening:
                connector.open()

            # all pipes empty?
            empty = (not readers or not readable) and (not writers or not writable)

            if (empty and exit):
                break

    finally:
        for stream in readers + writers:
            stream.close()

CONTAINER_PATH = '/mnt/girder_worker/data'

def chmod_writable(host_paths):
    """
    Since files written by docker containers are owned by root, we can't
    clean them up in the worker process since that typically doesn't run
    as root. So, we run a lightweight container to make the temp dir cleanable.
    """
    if not isinstance(host_paths, (list, tuple)):
        host_paths = (host_paths,)

    if 'DOCKER_CLIENT_TIMEOUT' in os.environ:
        timeout = int(os.environ['DOCKER_CLIENT_TIMEOUT'])
        client = docker.from_env(version='auto', timeout=timeout)
    else:
        client = docker.from_env(version='auto')

    config = {
        'tty': True,
        'volumes': {},
        'detach': False,
        'remove': True
    }

    container_paths = []
    for host_path in host_paths:
        container_path = os.path.join(CONTAINER_PATH, uuid.uuid4().hex)
        container_paths.append(container_path)
        config['volumes'][host_path] = {
            'bind': container_path,
            'mode': 'rw'
        }

    args = ['chmod', '-R', 'a+rw'] + container_paths

    try:
        client.containers.run('busybox:latest', args, **config)
    except DockerException:
        logger.exception('Error setting perms on docker volumes %s.' % host_paths)
        raise


text:
<?php
//----------------------------------------------------------------------
// Copyright (c) 2012-2016 Raytheon BBN Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and/or hardware specification (the "Work") to
// deal in the Work without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Work, and to permit persons to whom the Work
// 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 Work.
//
// THE WORK 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, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
// IN THE WORK.
//----------------------------------------------------------------------

require_once('pa_constants.php');
require_once('sa_constants.php');

// Routines to help support pending users requests on either projects or slices

function user_context_query($account_id, $context_type)
{
  if ($context_type == CS_CONTEXT_TYPE::SLICE)
    return slice_user_context_query($account_id);
  else
    return project_user_context_query($account_id);
}

function get_request_tablename($context_type)
{
  global $SA_SLICE_MEMBER_REQUEST_TABLENAME;
  global $PA_PROJECT_MEMBER_REQUEST_TABLENAME;

  if ($context_type == CS_CONTEXT_TYPE::SLICE)
    return $SA_SLICE_MEMBER_REQUEST_TABLENAME;
  else
    return $PA_PROJECT_MEMBER_REQUEST_TABLENAME;
}

// Define the specific function to call to determine what projects a given user can act on.
// (That is, requests about these projects can be handled by this user.)
function project_user_context_query($account_id)
{
  global $PA_PROJECT_MEMBER_TABLENAME;
  $conn = db_conn();
  return "select " . PA_PROJECT_MEMBER_TABLE_FIELDNAME::PROJECT_ID
  . " FROM " . $PA_PROJECT_MEMBER_TABLENAME
  . " WHERE " . PA_PROJECT_MEMBER_TABLE_FIELDNAME::ROLE
  . " IN (" . $conn->quote(CS_ATTRIBUTE_TYPE::LEAD, 'integer') . ", " .
    $conn->quote(CS_ATTRIBUTE_TYPE::ADMIN, 'integer') . ")"
    . " AND " . PA_PROJECT_MEMBER_TABLE_FIELDNAME::MEMBER_ID . " = " .
    $conn->quote($account_id, 'text');

}

// Define the specific function to call to determine what slices are relevant to a given user
// (That is, requests about that slice are for this user)
function slice_user_context_query($account_id)
{
  global $SA_SLICE_MEMBER_TABLENAME;
  return "select " . SA_SLICE_MEMBER_TABLE_FIELDNAME::SLICE_ID
    . " FROM " . $SA_SLICE_MEMBER_TABLENAME
    . " WHERE " . SA_SLICE_MEMBER_TABLE_FIELDNAME::ROLE
    . " IN (" . $conn->quote(CS_ATTRIBUTE_TYPE::LEAD, 'integer') . ", " . $conn->quote(CS_ATTRIBUTE_TYPE::ADMIN, 'integer') . ")"
    . " AND " . SA_SLICE_MEMBER_TABLE_FIELDNAME::MEMBER_ID . " = " . $conn->quote($account_id, 'text');

}

?>


text:
import { IServerChannel, IChannel } from 'vs/base/parts/ipc/common/ipc';
import { Emitter, Event } from 'vs/base/common/event';
import { IUserDataSyncService, IManualSyncTask, IUserDataManifest, SyncStatus, IResourcePreview, ISyncResourceHandle, ISyncResourcePreview, ISyncTask, SyncResource, UserDataSyncError } from 'vs/platform/userDataSync/common/userDataSync';
import { URI } from 'vs/base/common/uri';
import { ILogService } from 'vs/platform/log/common/log';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CancellationToken } from 'vs/base/common/cancellation';
import { isArray } from 'vs/base/common/types';

type ManualSyncTaskEvent<T> = { manualSyncTaskId: string, data: T };

export class UserDataSyncChannel implements IServerChannel {

	private readonly manualSyncTasks = new Map<string, { manualSyncTask: IManualSyncTask, disposables: DisposableStore }>();
	private readonly onManualSynchronizeResources = new Emitter<ManualSyncTaskEvent<[SyncResource, URI[]][]>>();

	constructor(private readonly service: IUserDataSyncService, private readonly logService: ILogService) { }

	listen(_: unknown, event: string): Event<any> {
		switch (event) {
			// sync
			case 'onDidChangeStatus': return this.service.onDidChangeStatus;
			case 'onDidChangeConflicts': return this.service.onDidChangeConflicts;
			case 'onDidChangeLocal': return this.service.onDidChangeLocal;
			case 'onDidChangeLastSyncTime': return this.service.onDidChangeLastSyncTime;
			case 'onSyncErrors': return this.service.onSyncErrors;
			case 'onDidResetLocal': return this.service.onDidResetLocal;
			case 'onDidResetRemote': return this.service.onDidResetRemote;

			// manual sync
			case 'manualSync/onSynchronizeResources': return this.onManualSynchronizeResources.event;
		}

		throw new Error(`Event not found: ${event}`);
	}

	async call(context: any, command: string, args?: any): Promise<any> {
		try {
			const result = await this._call(context, command, args);
			return result;
		} catch (e) {
			this.logService.error(e);
			throw e;
		}
	}

	private async _call(context: any, command: string, args?: any): Promise<any> {
		switch (command) {

			// sync
			case '_getInitialData': return Promise.resolve([this.service.status, this.service.conflicts, this.service.lastSyncTime]);
			case 'replace': return this.service.replace(URI.revive(args[0]));
			case 'reset': return this.service.reset();
			case 'resetRemote': return this.service.resetRemote();
			case 'resetLocal': return this.service.resetLocal();
			case 'hasPreviouslySynced': return this.service.hasPreviouslySynced();
			case 'hasLocalData': return this.service.hasLocalData();
			case 'accept': return this.service.accept(args[0], URI.revive(args[1]), args[2], args[3]);
			case 'resolveContent': return this.service.resolveContent(URI.revive(args[0]));
			case 'getLocalSyncResourceHandles': return this.service.getLocalSyncResourceHandles(args[0]);
			case 'getRemoteSyncResourceHandles': return this.service.getRemoteSyncResourceHandles(args[0]);
			case 'getAssociatedResources': return this.service.getAssociatedResources(args[0], { created: args[1].created, uri: URI.revive(args[1].uri) });
			case 'getMachineId': return this.service.getMachineId(args[0], { created: args[1].created, uri: URI.revive(args[1].uri) });

			case 'createManualSyncTask': return this.createManualSyncTask();
		}

		// manual sync
		if (command.startsWith('manualSync/')) {
			const manualSyncTaskCommand = command.substring('manualSync/'.length);
			const manualSyncTaskId = args[0];
			const manualSyncTask = this.getManualSyncTask(manualSyncTaskId);
			args = (<Array<any>>args).slice(1);

			switch (manualSyncTaskCommand) {
				case 'preview': return manualSyncTask.preview();
				case 'accept': return manualSyncTask.accept(URI.revive(args[0]), args[1]);
				case 'merge': return manualSyncTask.merge(URI.revive(args[0]));
				case 'discard': return manualSyncTask.discard(URI.revive(args[0]));
				case 'discardConflicts': return manualSyncTask.discardConflicts();
				case 'apply': return manualSyncTask.apply();
				case 'pull': return manualSyncTask.pull();
				case 'push': return manualSyncTask.push();
				case 'stop': return manualSyncTask.stop();
				case '_getStatus': return manualSyncTask.status;
				case 'dispose': return this.disposeManualSyncTask(manualSyncTask);
			}
		}

		throw new Error('Invalid call');
	}

	private getManualSyncTask(manualSyncTaskId: string): IManualSyncTask {
		const value = this.manualSyncTasks.get(this.createKey(manualSyncTaskId));
		if (!value) {
			throw new Error(`Manual sync taks not found: ${manualSyncTaskId}`);
		}
		return value.manualSyncTask;
	}

	private async createManualSyncTask(): Promise<{ id: string, manifest: IUserDataManifest | null, status: SyncStatus }> {
		const disposables = new DisposableStore();
		const manualSyncTask = disposables.add(await this.service.createManualSyncTask());
		disposables.add(manualSyncTask.onSynchronizeResources(synchronizeResources => this.onManualSynchronizeResources.fire({ manualSyncTaskId: manualSyncTask.id, data: synchronizeResources })));
		this.manualSyncTasks.set(this.createKey(manualSyncTask.id), { manualSyncTask, disposables });
		return { id: manualSyncTask.id, manifest: manualSyncTask.manifest, status: manualSyncTask.status };
	}

	private disposeManualSyncTask(manualSyncTask: IManualSyncTask): void {
		manualSyncTask.dispose();
		const key = this.createKey(manualSyncTask.id);
		this.manualSyncTasks.get(key)?.disposables.dispose();
		this.manualSyncTasks.delete(key);
	}

	private createKey(manualSyncTaskId: string): string { return `manualSyncTask-${manualSyncTaskId}`; }

}

export class UserDataSyncChannelClient extends Disposable implements IUserDataSyncService {

	declare readonly _serviceBrand: undefined;

	private readonly channel: IChannel;

	private _status: SyncStatus = SyncStatus.Uninitialized;
	get status(): SyncStatus { return this._status; }
	private _onDidChangeStatus: Emitter<SyncStatus> = this._register(new Emitter<SyncStatus>());
	readonly onDidChangeStatus: Event<SyncStatus> = this._onDidChangeStatus.event;

	get onDidChangeLocal(): Event<SyncResource> { return this.channel.listen<SyncResource>('onDidChangeLocal'); }

	private _conflicts: [SyncResource, IResourcePreview[]][] = [];
	get conflicts(): [SyncResource, IResourcePreview[]][] { return this._conflicts; }
	private _onDidChangeConflicts: Emitter<[SyncResource, IResourcePreview[]][]> = this._register(new Emitter<[SyncResource, IResourcePreview[]][]>());
	readonly onDidChangeConflicts: Event<[SyncResource, IResourcePreview[]][]> = this._onDidChangeConflicts.event;

	private _lastSyncTime: number | undefined = undefined;
	get lastSyncTime(): number | undefined { return this._lastSyncTime; }
	private _onDidChangeLastSyncTime: Emitter<number> = this._register(new Emitter<number>());
	readonly onDidChangeLastSyncTime: Event<number> = this._onDidChangeLastSyncTime.event;

	private _onSyncErrors: Emitter<[SyncResource, UserDataSyncError][]> = this._register(new Emitter<[SyncResource, UserDataSyncError][]>());
	readonly onSyncErrors: Event<[SyncResource, UserDataSyncError][]> = this._onSyncErrors.event;

	get onDidResetLocal(): Event<void> { return this.channel.listen<void>('onDidResetLocal'); }
	get onDidResetRemote(): Event<void> { return this.channel.listen<void>('onDidResetRemote'); }

	constructor(userDataSyncChannel: IChannel) {
		super();
		this.channel = {
			call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
				return userDataSyncChannel.call(command, arg, cancellationToken)
					.then(null, error => { throw UserDataSyncError.toUserDataSyncError(error); });
			},
			listen<T>(event: string, arg?: any): Event<T> {
				return userDataSyncChannel.listen(event, arg);
			}
		};
		this.channel.call<[SyncStatus, [SyncResource, IResourcePreview[]][], number | undefined]>('_getInitialData').then(([status, conflicts, lastSyncTime]) => {
			this.updateStatus(status);
			this.updateConflicts(conflicts);
			if (lastSyncTime) {
				this.updateLastSyncTime(lastSyncTime);
			}
			this._register(this.channel.listen<SyncStatus>('onDidChangeStatus')(status => this.updateStatus(status)));
			this._register(this.channel.listen<number>('onDidChangeLastSyncTime')(lastSyncTime => this.updateLastSyncTime(lastSyncTime)));
		});
		this._register(this.channel.listen<[SyncResource, IResourcePreview[]][]>('onDidChangeConflicts')(conflicts => this.updateConflicts(conflicts)));
		this._register(this.channel.listen<[SyncResource, Error][]>('onSyncErrors')(errors => this._onSyncErrors.fire(errors.map(([source, error]) => ([source, UserDataSyncError.toUserDataSyncError(error)])))));
	}

	createSyncTask(): Promise<ISyncTask> {
		throw new Error('not supported');
	}

	async createManualSyncTask(): Promise<IManualSyncTask> {
		const { id, manifest, status } = await this.channel.call<{ id: string, manifest: IUserDataManifest | null, status: SyncStatus }>('createManualSyncTask');
		const that = this;
		const manualSyncTaskChannelClient = new ManualSyncTaskChannelClient(id, manifest, status, {
			async call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
				return that.channel.call<T>(`manualSync/${command}`, [id, ...(isArray(arg) ? arg : [arg])], cancellationToken);
			},
			listen<T>(event: string, arg?: any): Event<T> {
				return Event.map(
					Event.filter(that.channel.listen<{ manualSyncTaskId: string, data: T }>(`manualSync/${event}`, arg), e => !manualSyncTaskChannelClient.isDiposed() && e.manualSyncTaskId === id),
					e => e.data);
			}
		});
		return manualSyncTaskChannelClient;
	}

	replace(uri: URI): Promise<void> {
		return this.channel.call('replace', [uri]);
	}

	reset(): Promise<void> {
		return this.channel.call('reset');
	}

	resetRemote(): Promise<void> {
		return this.channel.call('resetRemote');
	}

	resetLocal(): Promise<void> {
		return this.channel.call('resetLocal');
	}

	hasPreviouslySynced(): Promise<boolean> {
		return this.channel.call('hasPreviouslySynced');
	}

	hasLocalData(): Promise<boolean> {
		return this.channel.call('hasLocalData');
	}

	accept(syncResource: SyncResource, resource: URI, content: string | null, apply: boolean): Promise<void> {
		return this.channel.call('accept', [syncResource, resource, content, apply]);
	}

	resolveContent(resource: URI): Promise<string | null> {
		return this.channel.call('resolveContent', [resource]);
	}

	async getLocalSyncResourceHandles(resource: SyncResource): Promise<ISyncResourceHandle[]> {
		const handles = await this.channel.call<ISyncResourceHandle[]>('getLocalSyncResourceHandles', [resource]);
		return handles.map(({ created, uri }) => ({ created, uri: URI.revive(uri) }));
	}

	async getRemoteSyncResourceHandles(resource: SyncResource): Promise<ISyncResourceHandle[]> {
		const handles = await this.channel.call<ISyncResourceHandle[]>('getRemoteSyncResourceHandles', [resource]);
		return handles.map(({ created, uri }) => ({ created, uri: URI.revive(uri) }));
	}

	async getAssociatedResources(resource: SyncResource, syncResourceHandle: ISyncResourceHandle): Promise<{ resource: URI, comparableResource: URI }[]> {
		const result = await this.channel.call<{ resource: URI, comparableResource: URI }[]>('getAssociatedResources', [resource, syncResourceHandle]);
		return result.map(({ resource, comparableResource }) => ({ resource: URI.revive(resource), comparableResource: URI.revive(comparableResource) }));
	}

	async getMachineId(resource: SyncResource, syncResourceHandle: ISyncResourceHandle): Promise<string | undefined> {
		return this.channel.call<string | undefined>('getMachineId', [resource, syncResourceHandle]);
	}

	private async updateStatus(status: SyncStatus): Promise<void> {
		this._status = status;
		this._onDidChangeStatus.fire(status);
	}

	private async updateConflicts(conflicts: [SyncResource, IResourcePreview[]][]): Promise<void> {
		// Revive URIs
		this._conflicts = conflicts.map(([syncResource, conflicts]) =>
		([
			syncResource,
			conflicts.map(r =>
			({
				...r,
				localResource: URI.revive(r.localResource),
				remoteResource: URI.revive(r.remoteResource),
				previewResource: URI.revive(r.previewResource),
			}))
		]));
		this._onDidChangeConflicts.fire(this._conflicts);
	}

	private updateLastSyncTime(lastSyncTime: number): void {
		if (this._lastSyncTime !== lastSyncTime) {
			this._lastSyncTime = lastSyncTime;
			this._onDidChangeLastSyncTime.fire(lastSyncTime);
		}
	}
}

class ManualSyncTaskChannelClient extends Disposable implements IManualSyncTask {

	private readonly channel: IChannel;

	get onSynchronizeResources(): Event<[SyncResource, URI[]][]> { return this.channel.listen<[SyncResource, URI[]][]>('onSynchronizeResources'); }

	private _status: SyncStatus;
	get status(): SyncStatus { return this._status; }

	constructor(
		readonly id: string,
		readonly manifest: IUserDataManifest | null,
		status: SyncStatus,
		manualSyncTaskChannel: IChannel
	) {
		super();
		this._status = status;
		const that = this;
		this.channel = {
			async call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
				try {
					const result = await manualSyncTaskChannel.call<T>(command, arg, cancellationToken);
					if (!that.isDiposed()) {
						that._status = await manualSyncTaskChannel.call<SyncStatus>('_getStatus');
					}
					return result;
				} catch (error) {
					throw UserDataSyncError.toUserDataSyncError(error);
				}
			},
			listen<T>(event: string, arg?: any): Event<T> {
				return manualSyncTaskChannel.listen(event, arg);
			}
		};
	}

	async preview(): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('preview');
		return this.deserializePreviews(previews);
	}

	async accept(resource: URI, content?: string | null): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('accept', [resource, content]);
		return this.deserializePreviews(previews);
	}

	async merge(resource?: URI): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('merge', [resource]);
		return this.deserializePreviews(previews);
	}

	async discard(resource: URI): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('discard', [resource]);
		return this.deserializePreviews(previews);
	}

	async discardConflicts(): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('discardConflicts');
		return this.deserializePreviews(previews);
	}

	async apply(): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('apply');
		return this.deserializePreviews(previews);
	}

	pull(): Promise<void> {
		return this.channel.call('pull');
	}

	push(): Promise<void> {
		return this.channel.call('push');
	}

	stop(): Promise<void> {
		return this.channel.call('stop');
	}

	private _disposed = false;
	isDiposed() { return this._disposed; }

	override dispose(): void {
		this._disposed = true;
		this.channel.call('dispose');
	}

	private deserializePreviews(previews: [SyncResource, ISyncResourcePreview][]): [SyncResource, ISyncResourcePreview][] {
		return previews.map(([syncResource, preview]) =>
		([
			syncResource,
			{
				isLastSyncFromCurrentMachine: preview.isLastSyncFromCurrentMachine,
				resourcePreviews: preview.resourcePreviews.map(r => ({
					...r,
					localResource: URI.revive(r.localResource),
					remoteResource: URI.revive(r.remoteResource),
					previewResource: URI.revive(r.previewResource),
					acceptedResource: URI.revive(r.acceptedResource),
				}))
			}
		]));
	}
}


text:
package org.onosproject.p4runtime.api;

import com.google.common.annotations.Beta;
import org.onosproject.net.pi.model.PiPipeconf;
import org.onosproject.net.pi.runtime.PiActionGroup;
import org.onosproject.net.pi.model.PiActionProfileId;
import org.onosproject.net.pi.runtime.PiCounterCellData;
import org.onosproject.net.pi.runtime.PiCounterCellId;
import org.onosproject.net.pi.model.PiCounterId;
import org.onosproject.net.pi.runtime.PiPacketOperation;
import org.onosproject.net.pi.runtime.PiTableEntry;
import org.onosproject.net.pi.model.PiTableId;

import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * Client to control a P4Runtime device.
 */
@Beta
public interface P4RuntimeClient {

    /**
     * Type of write operation.
     */
    enum WriteOperationType {
        UNSPECIFIED,
        INSERT,
        MODIFY,
        DELETE
    }

    /**
     * Sets the device pipeline according to the given pipeconf, and for the given byte buffer representing the
     * target-specific data to be used in the P4Runtime's SetPipelineConfig message. This method should be called
     * before any other method of this client.
     *
     * @param pipeconf   pipeconf
     * @param deviceData target-specific data
     * @return a completable future of a boolean, true if the operations was successful, false otherwise.
     */
    CompletableFuture<Boolean> setPipelineConfig(PiPipeconf pipeconf, ByteBuffer deviceData);

    /**
     * Initializes the stream channel, after which all messages received from the device will be notified using the
     * {@link P4RuntimeController} event listener.
     *
     * @return a completable future of a boolean, true if the operations was successful, false otherwise.
     */
    CompletableFuture<Boolean> initStreamChannel();

    /**
     * Performs the given write operation for the given table entries and pipeconf.
     *
     * @param entries  table entries
     * @param opType   operation type
     * @param pipeconf pipeconf currently deployed on the device
     * @return true if the operation was successful, false otherwise.
     */
    CompletableFuture<Boolean> writeTableEntries(Collection<PiTableEntry> entries, WriteOperationType opType,
                                                 PiPipeconf pipeconf);

    /**
     * Dumps all entries currently installed in the given table, for the given pipeconf.
     *
     * @param tableId  table identifier
     * @param pipeconf pipeconf currently deployed on the device
     * @return completable future of a collection of table entries
     */
    CompletableFuture<Collection<PiTableEntry>> dumpTable(PiTableId tableId, PiPipeconf pipeconf);

    /**
     * Executes a packet-out operation for the given pipeconf.
     *
     * @param packet   packet-out operation to be performed by the device
     * @param pipeconf pipeconf currently deployed on the device
     * @return a completable future of a boolean, true if the operations was successful, false otherwise.
     */
    CompletableFuture<Boolean> packetOut(PiPacketOperation packet, PiPipeconf pipeconf);

    /**
     * Returns the value of all counter cells for the given set of counter identifiers and pipeconf.
     *
     * @param counterIds counter identifiers
     * @param pipeconf   pipeconf
     * @return collection of counter data
     */
    CompletableFuture<Collection<PiCounterCellData>> readAllCounterCells(Set<PiCounterId> counterIds,
                                                                         PiPipeconf pipeconf);

    /**
     * Returns a collection of counter data corresponding to the given set of counter cell identifiers, for the given
     * pipeconf.
     *
     * @param cellIds  set of counter cell identifiers
     * @param pipeconf pipeconf
     * @return collection of counter data
     */
    CompletableFuture<Collection<PiCounterCellData>> readCounterCells(Set<PiCounterCellId> cellIds,
                                                                      PiPipeconf pipeconf);

    /**
     * Performs the given write operation for the given action group members and pipeconf.
     *
     * @param group    action group
     * @param opType   write operation type
     * @param pipeconf the pipeconf currently deployed on the device
     * @return true if the operation was successful, false otherwise
     */
    CompletableFuture<Boolean> writeActionGroupMembers(PiActionGroup group,
                                                       WriteOperationType opType,
                                                       PiPipeconf pipeconf);

    /**
     * Performs the given write operation for the given action group and pipeconf.
     *
     * @param group    the action group
     * @param opType   write operation type
     * @param pipeconf the pipeconf currently deployed on the device
     * @return true if the operation was successful, false otherwise
     */
    CompletableFuture<Boolean> writeActionGroup(PiActionGroup group,
                                                WriteOperationType opType,
                                                PiPipeconf pipeconf);

    /**
     * Dumps all groups currently installed for the given action profile.
     *
     * @param actionProfileId the action profile id
     * @param pipeconf        the pipeconf currently deployed on the device
     * @return completable future of a collection of groups
     */
    CompletableFuture<Collection<PiActionGroup>> dumpGroups(PiActionProfileId actionProfileId,
                                                            PiPipeconf pipeconf);

    /**
     * Shutdown the client by terminating any active RPC such as the stream channel.
     */
    void shutdown();

    /**
     * Sends a master arbitration update to the device.
     *
     * @return a completable future containing true if the operation was successful; false otherwise
     */
    CompletableFuture<Boolean> sendMasterArbitrationUpdate();

    // TODO: work in progress.
}


text:
Ideas to detect plagiarism:

PLEASE ADD/EDIT THIS

-Unevenness of style:
</br>(some very sophisticated sentences followed by some amateurish ones). This can be detected by rating each word with commonness (an integer - apis for this). (i.e. 'the' = 1st used word, 'benevolent' = nth used word). Find stark contrasts excluding common words like 'a' 'the' etc.

-Web Crawling: Limited by internet speeds — perhaps there could be an offline trunk of essays from these sites to quickly scan through?
</br>Substring Matching
Crawl popular essay sites/ other sources online.
</br>+Quickly check substrings for copy/paste plagiarism.
</br>+Replace words in sentences with synonyms from the thesaurus and check for similarities.
(While checking using the previous 2 methods, allow for not completely verbatim matching. I.e. if a few words are different, still raise a red flag)
</br>+Check for sentence structure differences - i.e. if the student took a sentence/idea and shifted around the words. This might be accomplished with identifying verb/noun/etc in the sentence and comparing. (what thing (noun) did what (verb) and how (adjective)).
</br>+Bag of words - Compare word frequency of student's essay to these essays (https://en.wikipedia.org/wiki/Bag-of-words_model - see the diagram at the top for a great explanation). We'll probably have to use a library or api for this.
</br>+Word Frequency using aspell. We could use this website http://app.aspell.net/lookup-freq?words=hi%0D%0A  But we would probably have to build our own or figure out how there's works we can download it at http://wordlist.aspell.net/

-Profile Comparison (stylometry): Probably an SQL database and server will be required for this.
Build a profile on each student throughout the year by storing their previous essays. Analyze these previous essays and compare it to the submitted one and check for inconsistencies in writing style/syntax/etc.
</br>Bag of words
</br>Use word frequency to compare to student's previous essays (https://en.wikipedia.org/wiki/Bag-of-words_model - see the diagram at the top for a great explanation). We'll probably have to use a library or api for this.
</br>*Markov chains
</br>Build markov chains from student's previous work. Run the new essay through the program, and rank the probability that the student would use each word (after the other/in context) based on their previous work. This is how autocorrect works. (https://en.wikipedia.org/wiki/Markov_chain and http://www.in-vacua.com/markov_text.html)

-SMMRY.com:
</br>We have 10,000 free api requests because we're educational. They have a terrific algorithm for extracting main ideas and this may be a good idea just to get a "second opinion." (In addition to our own algorithm).


text:
layout: post
title:  "My 3 Favorite Chrome Dev Tools...So Far"
---

# Chrome Dev Tools FTW!

So if you are like me, you 💚 your dev tools. Yes, that is a green heart because green is my favorite color. The awesome peeps at Google put in a lot of work, blood, sweat, and tears to make the dev tools what they are today. New features seem to be released all the time.

# My favs!

Refresh Detroit put out a call for lightning talks and I decided to submit last minute on 3 of my favorite dev tools so far.

1. Device Frame (Chrome Canary).
2. A11Y (Chrome and Chrome Canary).
3. Color Picker (Chrome and Chrome Canary).

Such great tools that I use regularly, with the exception of the accessibility tool used for audits. I have however used this tool to run my own personal a11y audits but currently it is not used for any accessibility work at my job.

Below are my slides from Refresh Detroit.

<script async class="speakerdeck-embed" data-id="07cee2608997464a900f3459f8094bab" data-ratio="1.77777777777778" src="//speakerdeck.com/assets/embed.js"></script>


text:
<?php
	$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;

	$bdd = new PDO('mysql:host=localhost;dbname=pgallery', 'root', '', $pdo_options);

	$bdd->exec("SET CHARACTER SET utf8");


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title> ModularAdmin - Free Dashboard Theme | HTML Version </title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/vendor.css">

 <button class="collapse-btn" id="sidebar-collapse-btn">

    		</button>

                        <form role="search">

  <input type="search" placeholder="Search">

                        </form>

                          View on GitHub
                          Download .zip

    			      8

 Zack Alien pushed new commit: Fix page load performance issue.

 Amaya Hatsumi started new task: Dashboard UI design..

 Andy Nouman deployed new version of NodeJS REST Api V3

    			            View All

    			      John Doe

                                      Profile
                                      Notifications
                                      Settings

                                      Logout

 Modular Admin

                                      Dashboard

                                      Items Manager

    								Items List

    								Item Editor

                                      Charts

    								Flot Charts

    								Morris Charts

                                      Tables

    								Static Tables

    								Responsive Tables

                                      Forms

                                      UI Elements

    								Buttons

    								Cards

    								Typography

    								Icons

    								Grid

                                      Pages

    								Login

    								Sign Up

    								Reset

    								Error 404 App

    								Error 404 Global

    								Error 500 App

    								Error 500 Global

                                      Theme Docs

 fixed

 static

 Sidebar:

    				                        <input class="radio" type="radio" name="sidebarPosition" value="sidebar-fixed" >

    				                        <input class="radio" type="radio" name="sidebarPosition" value="">

 Header:

    				                        <input class="radio" type="radio" name="headerPosition" value="header-fixed">

    				                        <input class="radio" type="radio" name="headerPosition" value="">

 Footer:

    				                        <input class="radio" type="radio" name="footerPosition" value="footer-fixed">

    				                        <input class="radio" type="radio" name="footerPosition" value="">

                                  Customize

404

				Sorry, page not found

You better try our awesome search:

 <input type="text" class="form-control">
			                <button class="btn btn-primary" type="button">Search</button>

  Back to Dashboard

 created by ModularCode

 get in touch

 <button type="button" class="close" data-dismiss="modal" aria-label="Close">
    					×
    					Close
    				</button>

Media Library

 Gallery

 Upload

                                                <form action="/" method="POST" enctype="multipart/form-data" class="dropzone needsclick dz-clickable" id="demo-upload">

 Drop files here or click to upload.

                                                </form>

 <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Insert Selected</button>

 <button type="button" class="close" data-dismiss="modal" aria-label="Close">
    					×
    				</button>

 Alert

Are you sure want to do this?

 <button type="button" class="btn btn-primary" data-dismiss="modal">Yes</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button>


text:
import {isValid as isValidCPF} from './cpf'
import {isValid as isValidCNPJ} from './cnpj'

export default function (
  func: string,
  registerType: string,
  registerNumber: string
): void {
  switch (registerType) {
    case '01':
      if (!isValidCPF(registerNumber)) {
        throw new TypeError(
          `On function \`${func}\` registerNumber is invalid:
        \nExpect: \`registerType\` value is \`01\` so \`registerNumber\` should be a valid CPF
        \nActual: \`registerNumber\` is not a valid CPF`
        )
      }
      break
    case '02':
      if (!isValidCNPJ(registerNumber)) {
        throw new TypeError(`On function \`${func}\` registerNumber is invalid:
        \nExpect: \`registerType\` value is \`02\` so \`registerNumber\` should be a valid CNPJ
        \nActual: \`registerNumber\` is not a valid CNPJ`)
      }
      break
    default:
  }
}


text:
namespace Falcor.Server.Routing
{
    internal sealed class ErrorHandlerResult : RouteHandlerResult
    {
        public ErrorHandlerResult(string error = null)
        {
            Error = error;
        }

        public string Error { get; }

        public override RouteResult ToRouteResult(FalcorPath unmatchedPath) => new RejectedRouteResult(Error);
    }
}


text:
'use strict';

import React from 'react';
import {RouteHandler} from 'react-router';
import {root} from 'baobab-react/higher-order';
import GlobalTree from 'trees/global.tree';

class Layout extends React.Component {
  render() {
    return (
      <div className="app-content">
        <RouteHandler tree={this.props.tree} />
      </div>
    );
  }
}

export default root(Layout, GlobalTree);

// Export a un-decorated version of the component for testing
export let TestComponent = Layout;


text:
package org.elasticsearch.client.ml;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.util.Objects;

/**
 * Response indicating if the Machine Learning Job is now opened or not
 */
public class OpenJobResponse implements ToXContentObject {

    private static final ParseField OPENED = new ParseField("opened");
    private static final ParseField NODE = new ParseField("node");

    public static final ConstructingObjectParser<OpenJobResponse, Void> PARSER =
        new ConstructingObjectParser<>("open_job_response", true,
            (a) -> new OpenJobResponse((Boolean) a[0], (String) a[1]));

    static {
        PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), OPENED);
        PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), NODE);
    }

    private final boolean opened;
    private final String node;

    OpenJobResponse(boolean opened, String node) {
        this.opened = opened;
        this.node = node;
    }

    public static OpenJobResponse fromXContent(XContentParser parser) throws IOException {
        return PARSER.parse(parser, null);
    }

    /**
     * Has the job opened or not
     *
     * @return boolean value indicating the job opened status
     */
    public boolean isOpened() {
        return opened;
    }

    /**
     * The node that the job was assigned to
     *
     * @return The ID of a node if the job was assigned to a node.  If an empty string is returned
     *         it means the job was allowed to open lazily and has not yet been assigned to a node.
     *         If null is returned it means the server version is too old to return node
     *         information.
     */
    public String getNode() {
        return node;
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }

        if (other == null || getClass() != other.getClass()) {
            return false;
        }

        OpenJobResponse that = (OpenJobResponse) other;
        return opened == that.opened
            && Objects.equals(node, that.node);
    }

    @Override
    public int hashCode() {
        return Objects.hash(opened, node);
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        builder.field(OPENED.getPreferredName(), opened);
        if (node != null) {
            builder.field(NODE.getPreferredName(), node);
        }
        builder.endObject();
        return builder;
    }
}


text:
package com.media.car.entity.System;

import java.io.Serializable;

/**
 * Created by Administrator on 2016/12/29.
 */
public class CarSysUser implements Serializable{
    private Long id;
    private String userAccount;
    private String userName;
    private String userPassword;
    private Long deptId;
    private  String userRealName;
    private String userPhone;
    private String userEmail;
    private String userAddress;
    private String userQq;
    private String userGender;
    private String remark;
    private String createTime;
    private String updateTime;
    private Long createUser;
    private Long updateUser;
    private String status;
    private String free;
    private String isSys;

    public Long getId(){
        return id;
    }
    public void setId(Long id){
        this.id = id;
    }

    public String getUserAccount(){return userAccount;}
    public void setUserAccount(String userAccount){this.userAccount = userAccount;}

    public String getUserPassword(){
        return  userPassword;
    }
    public void setUserPassword(String userPassword){
        this.userPassword = userPassword;
    }

    public String getUserName(){
        return  userName;
    }
    public void setUserName(String userName){
        this.userName = userName;
    }

    public String getUserRealName(){
        return  userRealName;
    }
    public void setUserRealName(String userRealName){
        this.userRealName = userRealName;
    }

    public String getUserPhone(){
        return  userPhone;
    }
    public void setUserPhone(String userPhone){
        this.userPhone = userPhone;
    }

    public String getUserEmail(){
        return  userEmail;
    }
    public void setUserEmail(String userEmail){
        this.userEmail = userEmail;
    }

    public String getUserAddress(){
        return  userAddress;
    }
    public void setUserAddress(String userAddress){
        this.userAddress = userAddress;
    }

    public String getUserQq(){
        return  userQq;
    }
    public void setUserQq(String userQq){
        this.userQq = userQq;
    }

    public String getUserGender(){
        return  userGender;
    }
    public void setUserGender(String userGender){
        this.userGender = userGender;
    }

    public Long getDeptId(){
        return deptId;
    }
    public void setDeptId(Long deptId){
        this.deptId = deptId;
    }

    public String getRemark(){return remark;}
    public void setRemark(String remark){this.remark = remark;}

    public String getCreateTime(){return createTime;}
    public void setCreateTime(String createTime){this.createTime = createTime;}

    public String getUpdateTime(){return updateTime;}
    public void setUpdateTime(String updateTime){this.updateTime = updateTime;}

    public Long getCreateUser(){return createUser;}
    public void setCreateUser(Long createUser){this.createUser = createUser;}

    public Long getUpdateUser(){return updateUser;}
    public void setUpdateUser(Long updateUser){this.updateUser = updateUser;}

    public String getStatus(){return status;}
    public void setStatus(String status){this.status = status;}

    public String getFree(){return free;}
    public void setFree(String free){this.free = free;}

    public String getIsSys(){return isSys;}
    public void setIsSys(String isSys){this.isSys = isSys;}
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HitTestResult.cs" company="Helix Toolkit">
//   Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// <summary>
//   Provides a hit test result.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace HelixToolkit.Wpf.SharpDX
{
    using System.Windows.Media.Media3D;

    /// <summary>
    /// Provides a hit test result.
    /// </summary>
    public struct HitTestResult
    {
        /// <summary>
        /// Gets the distance between the hit intersection and the inner coordinate space
        /// of the System.Windows.Media.Media3D.Visual3D which initiated the hit test.
        ///
        /// Double that indicates the distance between the hit intersection and the inner
        /// coordinate space of the System.Windows.Media.Media3D.Visual3D which initiated
        /// the hit test.
        /// </summary>
        public double Distance { get; set; }

        /// <summary>
        /// Gets the Model3D intersected by the ray along which the hit test was performed.
        /// Model3D intersected by the ray.
        /// </summary>
        public GeometryModel3D ModelHit { get; set; }

        /// <summary>
        /// Gets the Point3D at the intersection between the ray along which the hit
        /// test was performed and the hit object.
        /// Point3D at which the hit object was intersected by the ray.
        /// </summary>
        public Point3D PointHit { get; set; }

        /// <summary>
        /// The normal vector of the triangle hit.
        /// </summary>
        public Vector3D NormalAtHit { get; set; }

        /// <summary>
        /// Indicates if this Result has data from a valid hit.
        /// </summary>
        public bool IsValid { get; set; }

        /// <summary>
        /// This is a tag to add additional data.
        /// </summary>
        public object Tag { get; set; }
    }
}


text:
1.  {!create-stream.md!}

1.  Next, on your {{ settings_html|safe }}, create a bot and
    note its email and API key.

1.  In Home Assistant, you need to add the `notify` service to your
    `configuration.yaml` file.  This should look something like this:

    ![](/static/images/integrations/homeassistant/001.png)

1.  The `api_key` parameter should correspond to your bot's key. The `stream`
    parameter is not necessarily required; if not given, it will default to
    the `homeassistant` stream.

1.  And the URL under `resource` should start with:

    `{{ api_url }}/v1/external/homeassistant`

1.  Finally, you need to configure a trigger for the service by adding
    an automation entry in the HomeAssistant `configuration.yaml` file.

    ![](/static/images/integrations/homeassistant/002.png)

    The `data` object takes at least a `message` property and an optional
    `title` parameter which will be the conversation topic and which defaults
    to `homeassistant` if not given.

{!congrats.md!}

![](/static/images/integrations/homeassistant/003.png)


text:
SpecBegin(JRMPushHandler)

__block JRMPushHandler *pushHandler;

describe(@"Alert View", ^{
    it(@"is shown with the push string as its message", ^{
        id mockAlertView = [OCMockObject mockForClass:[UIAlertView class]];
        [[[mockAlertView stub] andReturn:mockAlertView] alloc];
        (void)[[[mockAlertView expect] andReturn:mockAlertView] initWithTitle:OCMOCK_ANY message:@"alert string" delegate:OCMOCK_ANY cancelButtonTitle:OCMOCK_ANY otherButtonTitles:OCMOCK_ANY, nil];
        [[mockAlertView expect] show];

        pushHandler = [[JRMPushHandler alloc] init];
        [pushHandler handlePush:@{@"aps": @{@"alert": @"alert string"}}];

        [mockAlertView verify];
        [mockAlertView stopMocking];
    });
});

__block OCMockObject *mock;

describe(@"Push Handler", ^{

    beforeEach(^{
        pushHandler = [[JRMPushHandler alloc] init];
        mock = [OCMockObject partialMockForObject:pushHandler];
    });

    it(@"creates an alert view when it is asked to handle a push with an alert", ^{
        [[mock expect] alertViewForMessage:[OCMArg isKindOfClass:[NSString class]] andOtherButtonTitles:[OCMArg any]];
        [pushHandler handlePush:@{@"aps": @{@"alert": @"alert string"}}];
    });

    it(@"includes a View button in the alert when the push includes a url", ^{
        [[mock expect] alertViewForMessage:[OCMArg isKindOfClass:[NSString class]] andOtherButtonTitles:@[@"View"]];
        [pushHandler handlePush:@{@"aps": @{@"alert": @"alert string"}, @"url": @"http://example.com"}];
    });

    it(@"doesn't include any additional buttons in the alert when the push doesn't include a url", ^{
        [[mock expect] alertViewForMessage:[OCMArg isKindOfClass:[NSString class]] andOtherButtonTitles:nil];
        [pushHandler handlePush:@{@"aps": @{@"alert": @"alert string"}}];
    });

    afterEach(^{
        [mock verify];
    });

});

SpecEnd


text:
¿Confirmás que querés eliminar el tipo de couch?

            Descripción: <?php echo $tipoDeCouch[0]->descripcion_tipo; ?>

        <?php
        if ($tiene_couches) {
            ?>

Nota: hay al menos un couch que tiene esta descripción.

No se puede eliminar el tipo de couch; el mismo se deshabilitará para que no lo pueda usar ningún couch de ahora en más.

            <?php
        }
        ?>

<?php
if ($tiene_couches) {
    ?>

Los siguientes couch, que utilizan este tipo de couch, continuarán listándose sin cambios:

            <?php echo $listing; ?>

    <?php
}

echo form_open($uri_base . '/d', 'formEliminar');
?>
<button type='submit' class='btn btn-primary'>
     confirmar
</button>
<a href='<?php echo site_url("admin/tipo-couch"); ?>' class="btn btn-alert">
     cancelar

<?php
echo form_close();


text:
package org.apache.airavata.workflow.model.graph.ws;

import java.io.File;
import java.io.IOException;

import com.google.gson.JsonObject;
import org.apache.airavata.common.utils.IOUtil;
import org.apache.airavata.common.utils.JSONUtil;
import org.apache.airavata.common.utils.XMLUtil;
import org.apache.airavata.workflow.model.exceptions.WorkflowRuntimeException;
import org.apache.airavata.workflow.model.graph.ControlEdge;
import org.apache.airavata.workflow.model.graph.ControlPort;
import org.apache.airavata.workflow.model.graph.DataEdge;
import org.apache.airavata.workflow.model.graph.EPRPort;
import org.apache.airavata.workflow.model.graph.GraphException;
import org.apache.airavata.workflow.model.graph.GraphFactory;
import org.apache.airavata.workflow.model.graph.GraphSchema;
import org.apache.airavata.workflow.model.graph.Port;
import org.apache.airavata.workflow.model.graph.Port.Kind;
import org.apache.airavata.workflow.model.graph.amazon.InstanceDataPort;
import org.apache.airavata.workflow.model.graph.amazon.InstanceNode;
import org.apache.airavata.workflow.model.graph.amazon.TerminateInstanceNode;
import org.apache.airavata.workflow.model.graph.impl.EdgeImpl;
import org.apache.airavata.workflow.model.graph.impl.NodeImpl;
import org.apache.airavata.workflow.model.graph.impl.PortImpl;
import org.apache.airavata.workflow.model.graph.system.BlockNode;
import org.apache.airavata.workflow.model.graph.system.ConstantNode;
import org.apache.airavata.workflow.model.graph.system.DoWhileNode;
import org.apache.airavata.workflow.model.graph.system.EndBlockNode;
import org.apache.airavata.workflow.model.graph.system.EndDoWhileNode;
import org.apache.airavata.workflow.model.graph.system.EndForEachNode;
import org.apache.airavata.workflow.model.graph.system.EndifNode;
import org.apache.airavata.workflow.model.graph.system.ForEachNode;
import org.apache.airavata.workflow.model.graph.system.IfNode;
import org.apache.airavata.workflow.model.graph.system.InputNode;
import org.apache.airavata.workflow.model.graph.system.MemoNode;
import org.apache.airavata.workflow.model.graph.system.OutputNode;
import org.apache.airavata.workflow.model.graph.system.ReceiveNode;
import org.apache.airavata.workflow.model.graph.system.StreamSourceNode;
import org.apache.airavata.workflow.model.graph.system.SystemDataPort;
import org.apache.airavata.workflow.model.utils.MessageConstants;
import org.xmlpull.infoset.XmlElement;

/**
 * The GraphFactory class is a factory to create nodes, ports, and edges.
 *
 */
public class WSGraphFactory implements GraphFactory {

	/**
	 * Creates a empty Graph
	 *
	 * @return the empty graph created
	 */
	public static WSGraph createGraph() {
		return createWSGraph();
	}

	/**
	 * Reads a specified file and creates a graph.
	 *
	 * @param file
	 * @return The graph created
	 * @throws GraphException
	 * @throws IOException
	 */
	public static WSGraph createGraph(File file) throws GraphException,
			IOException {
		String graphString = IOUtil.readFileToString(file);
		return createGraph(graphString);
	}

	/**
	 * @param graphString
	 * @return the graph created
	 * @throws GraphException
	 */
	public static WSGraph createGraph(String graphString) throws GraphException {
		XmlElement graphElement;
        JsonObject graphElementJSON;
		try {
//			graphElement = XMLUtil.stringToXmlElement(graphString);
            graphElementJSON = JSONUtil.stringToJSONObject(graphString);
        } catch (RuntimeException e) {
			throw new GraphException(MessageConstants.XML_ERROR, e);
		}
		return createGraph(graphElementJSON);
	}

	/**
	 * @param graphElement
	 * @return The graph created
	 * @throws GraphException
	 */
	public static WSGraph createGraph(XmlElement graphElement)
			throws GraphException {
		try {
			WSGraph graph = createWSGraph();
			graph.parse(graphElement);
			return graph;
		} catch (RuntimeException e) {
			throw new GraphException(MessageConstants.XML_ERROR, e);
		}
	}

    public static WSGraph createGraph(JsonObject graphObject) throws GraphException {
        WSGraph graph = createWSGraph();
        graph.parse(graphObject);
        return graph;
    }

	/**
	 * @see org.apache.airavata.workflow.model.graph.GraphFactory#createNode(org.xmlpull.infoset.XmlElement)
	 */
	public NodeImpl createNode(XmlElement nodeElement) throws GraphException {
		String type = nodeElement.attributeValue(GraphSchema.NS,
				GraphSchema.NODE_TYPE_ATTRIBUTE);
		if (type == null) {
			// Old graphs don't have the namespace for the attribute.
			type = nodeElement.attributeValue(GraphSchema.NODE_TYPE_ATTRIBUTE);
		}

		NodeImpl node;
		if (GraphSchema.NODE_TYPE_WS.equals(type)) {
			node = new WSNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_STREAM_SOURCE.equals(type)) {
			node = new StreamSourceNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_WORKFLOW.equals(type)) {
			node = new WorkflowNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_INPUT.equals(type)) {
			node = new InputNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_OUTPUT.equals(type)) {
			node = new OutputNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_CONSTANT.equals(type)) {
			node = new ConstantNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_SPLIT.equals(type)) {
			node = new ForEachNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_MERGE.equals(type)) {
			node = new EndForEachNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_IF.equals(type)) {
			node = new IfNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_ENDIF.equals(type)) {
			node = new EndifNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_DOWHILE.equals(type)) {
			node = new DoWhileNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_ENDDOWHILE.equals(type)) {
			node = new EndDoWhileNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_MEMO.equals(type)) {
			node = new MemoNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_RECEIVE.equals(type)) {
			node = new ReceiveNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_BLOCK.equals(type)) {
			node = new BlockNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_ENDBLOCK.equals(type)) {
			node = new EndBlockNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_INSTANCE.equals(type)) {
			node = new InstanceNode(nodeElement);
		} else if (GraphSchema.NODE_TYPE_TERMINATE.equals(type)) {
			node = new TerminateInstanceNode(nodeElement);
		} else {
			// Default is WsNode for backward compatibility.
			node = new WSNode(nodeElement);
		}
		return node;
	}

    public NodeImpl createNode(JsonObject nodeObject) throws GraphException {

        String type = nodeObject.getAsJsonPrimitive(GraphSchema.NODE_TYPE_ATTRIBUTE).getAsString();

        NodeImpl node;
        if (GraphSchema.NODE_TYPE_WS.equals(type)) {
            node = new WSNode(nodeObject);
        } else if (GraphSchema.NODE_TYPE_WORKFLOW.equals(type)) {
            node = new WorkflowNode(nodeObject);
        } else if (GraphSchema.NODE_TYPE_INPUT.equals(type)) {
            node = new InputNode(nodeObject);
        } else if (GraphSchema.NODE_TYPE_OUTPUT.equals(type)) {
            node = new OutputNode(nodeObject);
/*        } else if (GraphSchema.NODE_TYPE_STREAM_SOURCE.equals(type)) {
            node = new StreamSourceNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_CONSTANT.equals(type)) {
            node = new ConstantNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_SPLIT.equals(type)) {
            node = new ForEachNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_MERGE.equals(type)) {
            node = new EndForEachNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_IF.equals(type)) {
            node = new IfNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_ENDIF.equals(type)) {
            node = new EndifNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_DOWHILE.equals(type)) {
            node = new DoWhileNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_ENDDOWHILE.equals(type)) {
            node = new EndDoWhileNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_MEMO.equals(type)) {
            node = new MemoNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_RECEIVE.equals(type)) {
            node = new ReceiveNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_BLOCK.equals(type)) {
            node = new BlockNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_ENDBLOCK.equals(type)) {
            node = new EndBlockNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_INSTANCE.equals(type)) {
            node = new InstanceNode(nodeElement);
        } else if (GraphSchema.NODE_TYPE_TERMINATE.equals(type)) {
            node = new TerminateInstanceNode(nodeElement);*/
        } else {
            // Default is WsNode for backward compatibility.
            node = new WSNode(nodeObject);
        }

        return node;
    }
	/**
	 * @see org.apache.airavata.workflow.model.graph.GraphFactory#createPort(org.xmlpull.infoset.XmlElement)
	 */
	public PortImpl createPort(JsonObject portObject) {

        String type = portObject.getAsJsonPrimitive(GraphSchema.PORT_TYPE_ATTRIBUTE).getAsString();
        PortImpl port;
        if (GraphSchema.PORT_TYPE_WS_DATA.equals(type)) {
            port = new WSPort(portObject);
        } else if (GraphSchema.PORT_TYPE_SYSTEM_DATA.equals(type)) {
            port = new SystemDataPort(portObject);
        } else if (GraphSchema.PORT_TYPE_CONTROL.equals(type)) {
            port = new ControlPort(portObject);
/*        } else if (GraphSchema.PORT_TYPE_EPR.equals(type)) {
            port = new EPRPort(portElement);
        } else if (GraphSchema.PORT_TYPE_INSTANCE.equals(type)) {
            port = new InstanceDataPort(portElement);*/
        } else {
            // Default is WsPort because of backword compatibility
            port = new WSPort(portObject);
        }
        return port;
    }

    public PortImpl createPort(XmlElement portElement) {
        String type = portElement.attributeValue(GraphSchema.NS,
                GraphSchema.PORT_TYPE_ATTRIBUTE);
        if (type == null) {
            // Old graphs don't have the namespace for the attribute.
            type = portElement.attributeValue(GraphSchema.PORT_TYPE_ATTRIBUTE);
        }
        PortImpl port;
        if (GraphSchema.PORT_TYPE_WS_DATA.equals(type)) {
            port = new WSPort(portElement);
        } else if (GraphSchema.PORT_TYPE_SYSTEM_DATA.equals(type)) {
            port = new SystemDataPort(portElement);
        } else if (GraphSchema.PORT_TYPE_CONTROL.equals(type)) {
            port = new ControlPort(portElement);
        } else if (GraphSchema.PORT_TYPE_EPR.equals(type)) {
            port = new EPRPort(portElement);
        } else if (GraphSchema.PORT_TYPE_INSTANCE.equals(type)) {
            port = new InstanceDataPort(portElement);
        } else {
            // Default is WsPort because of backword compatibility
            port = new WSPort(portElement);
        }
        return port;
    }
	/**
	 * @see org.apache.airavata.workflow.model.graph.GraphFactory#createEdge(org.apache.airavata.workflow.model.graph.Port,
	 *      org.apache.airavata.workflow.model.graph.Port)
	 */
	public EdgeImpl createEdge(Port fromPort, Port toPort) {
		Kind fromKind = fromPort.getKind();
		Kind toKind = toPort.getKind();
		if (!((fromKind == Kind.DATA_OUT && toKind == Kind.DATA_IN)
				|| (fromKind == Kind.CONTROL_OUT && toKind == Kind.CONTROL_IN) || (fromKind == Kind.EPR && toKind == Kind.DATA_IN))) {
			throw new WorkflowRuntimeException();
		}
		EdgeImpl edge;
		if (toKind == Kind.DATA_IN) {
			edge = new DataEdge();
		} else if (toKind == Kind.CONTROL_IN) {
			edge = new ControlEdge();
		} else {
			// Should not happen.
			throw new WorkflowRuntimeException();
		}
		return edge;
	}

	/**
	 * @see org.apache.airavata.workflow.model.graph.GraphFactory#createEdge(org.xmlpull.infoset.XmlElement)
	 */
	public EdgeImpl createEdge(XmlElement edgeElement) {
		String type = edgeElement.attributeValue(GraphSchema.NS,
				GraphSchema.EDGE_TYPE_ATTRIBUTE);
		EdgeImpl edge;
		if (GraphSchema.EDGE_TYPE_DATA.equals(type)) {
			edge = new DataEdge(edgeElement);
		} else if (GraphSchema.PORT_TYPE_CONTROL.equals(type)) {
			edge = new ControlEdge(edgeElement);
		} else {
			// Default is WsPort because of backword compatibility
			edge = new DataEdge(edgeElement);
		}
		return edge;
	}

    public EdgeImpl createEdge(JsonObject edgeObject) {
        String type = edgeObject.getAsJsonPrimitive(GraphSchema.EDGE_TYPE_ATTRIBUTE).getAsString();
        EdgeImpl edge;
        if (GraphSchema.EDGE_TYPE_DATA.equals(type)) {
            edge = new DataEdge(edgeObject);
        } else if (GraphSchema.PORT_TYPE_CONTROL.equals(type)) {
            edge = new ControlEdge(edgeObject);
        } else {
            // Default is WsPort because of backword compatibility
            edge = new DataEdge(edgeObject);
        }
        return edge;
    }

    /**
	 * @return The graph created.
	 */
	private static WSGraph createWSGraph() {
		return new WSGraph(new WSGraphFactory());
	}
}