text:
define([
  'color',
  'defaults'
], function( Color, Defaults ) {
  'use strict';

  function Entity() {
    this._position = {
      x: 0,
      y: 0
    };

    this._velocity = {
      x: 0,
      y: 0
    };

    this._width  = 0;
    this._height = 0;

    this._color = new Color();
  }

  Entity.prototype.getX = function() {
    return this.getPosition().x;
  };

  Entity.prototype.setX = function( x ) {
    this._position.x = x;
  };

  Entity.prototype.getY = function() {
    return this.getPosition().y;
  };

  Entity.prototype.setY = function( y ) {
    this._position.y = y;
  };

  Entity.prototype.getPosition = function() {
    return this._position;
  };

  Entity.prototype.setPosition = function() {
    if ( arguments.length === 1 ) {
      this.setX( arguments[0].x );
      this.setY( arguments[0].y );
    }
    else if ( arguments.length === 2 ) {
      this.setX( arguments[0] );
      this.setY( arguments[1] );
    }
  };

  Entity.prototype.getLeft = function() {
    return this.getX() - this.getHalfWidth();
  };

  Entity.prototype.setLeft = function( left ) {
    this.setX( left + this.getHalfWidth() );
  };

  Entity.prototype.getTop = function() {
    return this.getY() - this.getHalfHeight();
  };

  Entity.prototype.setTop = function( top ) {
    this.setY( top + this.getHalfHeight() );
  };

  Entity.prototype.getRight = function() {
    return this.getX() + this.getHalfWidth();
  };

  Entity.prototype.setRight = function( right ) {
    this.setX( right - this.getHalfWidth() );
  };

  Entity.prototype.getBottom = function() {
    return this.getY() + this.getHalfHeight();
  };

  Entity.prototype.setBottom = function( bottom ) {
    this.setY( bottom - this.getHalfHeight() );
  };

  Entity.prototype.setTopLeft = function() {
    if ( arguments.length === 1 ) {
      this.setLeft( arguments[0].x );
      this.setTop( arguments[0].y );
    }
    else if ( arguments.length === 2 ) {
      this.setLeft( arguments[0] );
      this.setTop( arguments[1] );
    }
  };

  Entity.prototype.getVelocityX = function() {
    return this._velocity.x;
  };

  Entity.prototype.setVelocityX = function( velocityX ) {
    this._velocity.x = velocityX;
  };

  Entity.prototype.getVelocityY = function() {
    return this._velocity.y;
  };

  Entity.prototype.setVelocityY = function( velocityY ) {
    this._velocity.y = velocityY;
  };

  Entity.prototype.getVelocity = function() {
    return this._velocity;
  };

  Entity.prototype.setVelocity = function() {
    if ( arguments.length === 1 ) {
      this._velocity = arguments[0];
    }
    else if ( arguments.length === 2 ) {
      this.setVelocityX( arguments[0] );
      this.setVelocityY( arguments[1] );
    }
  };

  Entity.prototype.getWidth = function() {
    return this._width;
  };

  Entity.prototype.getHalfWidth = function() {
    return this.getWidth() / 2;
  };

  Entity.prototype.setWidth = function( width ) {
    this._width = width;
  };

  Entity.prototype.getHeight = function() {
    return this._height;
  };

  Entity.prototype.getHalfHeight = function() {
    return this.getHeight() / 2;
  };

  Entity.prototype.setHeight = function( height ) {
    this._height = height;
  };

  Entity.prototype.getColor = function() {
    return this._color;
  };

  Entity.prototype.setColor = function() {
    this.getColor().set.apply( this.getColor(), arguments );
  };

  Entity.prototype.update = function( elapsedTime ) {
    // this.setVelocityX( this.getVelocityX() * 0.95 );
    // this.setVelocityY( this.getVelocityY() * 0.95 );

    if ( Math.abs( this.getVelocityX() ) < Defaults.EPSILON ) {
      this.setVelocityX( 0 );
    }
    if ( Math.abs( this.getVelocityY() ) < Defaults.EPSILON ) {
      this.setVelocityY( 0 );
    }

    this.setX( this.getX() + this.getVelocityX() * elapsedTime );
    this.setY( this.getY() + this.getVelocityY() * elapsedTime );

    // if ( this.getX() - this.getHalfWidth() <= 0 ) {
    //   this.setX( this.getHalfWidth() );
    // }
    // if ( this.getX() + this.getHalfWidth() >= Game.instance.WIDTH ) {
    //   this.setX( Game.instance.WIDTH - this.getHalfWidth() );
    // }
    // if ( this.getY() - this.getHalfHeight() <= 0 ) {
    //   this.setY( this.getHalfHeight() );
    // }
    // if ( this.getY() + this.getHalfHeight() >= Game.instance.HEIGHT ) {
    //   this.setY( Game.instance.HEIGHT - this.getHalfHeight() );
    // }
  };

  Entity.prototype.draw = function( ctx ) {
    ctx.fillStyle = this.getColor().toString();
    ctx.fillRect(
      this.getX() - this.getHalfWidth(),
      this.getY() - this.getHalfHeight(),
      this.getWidth(),
      this.getHeight()
    );
  };

  Entity.prototype.hit = function( x, y ) {
    if ( this.contains( x, y ) ) {
      return this;
    }

    return null;
  };

  Entity.prototype.contains = function( x, y ) {
    return Math.abs( x - this.getX() ) <= this.getHalfWidth() &&
           Math.abs( y - this.getY() ) <= this.getHalfHeight();
  };

  return Entity;
});


text:
ARG PY_VERSION
FROM tensorflow/build:2.10-python$PY_VERSION as base_install

ENV TF_NEED_CUDA="1"
ARG PY_VERSION
ARG TF_VERSION

# TODO: Remove this if tensorflow/build container removes their keras-nightly install
# https://github.com/tensorflow/build/issues/78
RUN python -m pip uninstall -y keras-nightly

RUN python -m pip install --default-timeout=1000 tensorflow==$TF_VERSION

COPY tools/install_deps/ /install_deps
RUN python -m pip install -r /install_deps/pytest.txt

COPY requirements.txt .
RUN python -m pip install -r requirements.txt

COPY ./ /addons
WORKDIR /addons

# -------------------------------------------------------------------
FROM base_install as tfa_gpu_tests
CMD ["bash", "tools/testing/build_and_run_tests.sh"]

# -------------------------------------------------------------------
FROM base_install as make_wheel
ARG NIGHTLY_FLAG
ARG NIGHTLY_TIME
ARG SKIP_CUSTOM_OP_TESTS

RUN python configure.py

# Test Before Building
RUN bash tools/testing/build_and_run_tests.sh $SKIP_CUSTOM_OP_TESTS

# Build
RUN bazel build \
        --noshow_progress \
        --noshow_loading_progress \
        --verbose_failures \
        --test_output=errors \
        --crosstool_top=@ubuntu20.04-gcc9_manylinux2014-cuda11.2-cudnn8.1-tensorrt7.2_config_cuda//crosstool:toolchain \
        build_pip_pkg && \
    # Package Whl
    bazel-bin/build_pip_pkg artifacts $NIGHTLY_FLAG

RUN bash tools/releases/tf_auditwheel_patch.sh
RUN python -m auditwheel repair --plat manylinux2014_x86_64 artifacts/*.whl
RUN ls -al wheelhouse/

# -------------------------------------------------------------------

FROM python:$PY_VERSION as test_wheel_in_fresh_environment

ARG TF_VERSION
ARG SKIP_CUSTOM_OP_TESTS

RUN python -m pip install --default-timeout=1000 tensorflow==$TF_VERSION

COPY --from=make_wheel /addons/wheelhouse/ /addons/wheelhouse/
RUN pip install /addons/wheelhouse/*.whl

RUN if [[ -z "$SKIP_CUSTOM_OP_TESTS" ]] ; then python -c "import tensorflow_addons as tfa; print(tfa.register_all())" ; else python -c "import tensorflow_addons as tfa; print(tfa.register_all(custom_kernels=False))" ; fi

# -------------------------------------------------------------------
FROM scratch as output

COPY --from=test_wheel_in_fresh_environment /addons/wheelhouse/ .

redpajama_set_name: RedPajamaGithub


text:
git 04a07feb482ea8c735658367f986e6c305027ec0

---

# Laravel Elixir

- [Введение](#introduction)
- [Установка и настройка](#installation)
- [Использование](#usage)
- [Gulp](#gulp)
- [Расширения](#extensions)

## Введение

Laravel Elixir предназначен для сборки файлов вашего фронтэнда в css- и js-файлы, а также для выполнения различных задач, построенных на слежении за изменениями в файлах вашего проекта - например, запуска тестов. Laravel Elixir представляет собой гибкий и простой API для [Gulp](http://gulpjs.com).

## Установка и настройка

### Установка node.js

Сначала убедитесь, стоит ли у вас node.js:

    node -v

По умолчанию node.js есть в Laravel Homestead. Если вы не используете его, вы можете [установить её вручную](http://nodejs.org/download/).

### Gulp

Далее, вам нужно глобально установить [Gulp](http://gulpjs.com).

    npm install --global gulp

### Laravel Elixir

Осталось установить собственно Elixir. В корне папки фреймворка вы можете видеть файл `package.json`. Он похож на `composer.json`, только предназначен не для Composer, а для пакетного менеджера node.js , который называется `npm`. Вы можете установить зависимости, заданные в этом файле одной командой:

    npm install

## Использование

Команды elixir записываются в файле `gulpfile.js`.

#### Компиляция Less

```javascript
elixir(function(mix) {
    mix.less("app.less");
});
```
В данном примере подразумевается, что ваши less-файлы находятся в `resources/assets/less`.

#### Компиляция Sass

```javascript
elixir(function(mix) {
    mix.sass("app.sass");
});
```

Подразумевается, что ваши sass-файлы находятся в `resources/assets/sass`.

#### Компиляция CoffeeScript

```javascript
elixir(function(mix) {
    mix.coffee();
});
```

Подразумевается, что ваши CoffeeScript-файлы находятся в `resources/assets/coffee`.

#### Компиляция всех Less и CoffeeScript файлов

```javascript
elixir(function(mix) {
    mix.less()
       .coffee();
});
```

#### Запуск PHPUnit тестов

```javascript
elixir(function(mix) {
    mix.phpUnit();
});
```

#### Запуск PHPSpec тестов

```javascript
elixir(function(mix) {
    mix.phpSpec();
});
```

#### Объединение Stylesheets

```javascript
elixir(function(mix) {
    mix.styles([
        "normalize.css",
        "main.css"
    ]);
});
```

Пути задаются относительно директории `resources/css`.

#### Объединение Stylesheets и сохранение в определённое место

```javascript
elixir(function(mix) {
    mix.styles([
        "normalize.css",
        "main.css"
    ], 'public/build/css/everything.css');
});
```

#### Объединение Stylesheets в заданном каталоге

```javascript
elixir(function(mix) {
    mix.styles([
        "normalize.css",
        "main.css"
    ], 'public/build/css/everything.css', 'public/css');
});
```

Третий аргумент в `styles` и `scripts` определяет папку, относительно которой будут искаться заданные файлы.

#### Объединение всех css в папке

```javascript
elixir(function(mix) {
    mix.stylesIn("public/css");
});
```

#### Объединение javascript

```javascript
elixir(function(mix) {
    mix.scripts([
        "jquery.js",
        "app.js"
    ]);
});
```

Как и в случае с css, пути задаются относительно папки `resources/js`

#### Объединение всех js в папке

```javascript
elixir(function(mix) {
    mix.scriptsIn("public/js/some/directory");
});
```

#### Объединение нескольких наборов js

```javascript
elixir(function(mix) {
    mix.scripts(['jquery.js', 'main.js'], 'public/js/main.js')
       .scripts(['forum.js', 'threads.js'], 'public/js/forum.js');
});
```

#### Добавление версии файла

```javascript
elixir(function(mix) {
    mix.version("css/all.css");
});
```

Файл будет сохранён с уникальным именем (к имени файла добавляется хэш содержимого и получается что-то вроде `all-16d570a7.css`), чтобы исключить кэширование его на клиенте.

Внутри ваших шаблонов вы можете использовать хэлпер `elixir()` для указания урла для такого файла:

```html
<link rel="stylesheet" href="{{ elixir("css/all.css") }}">
```

Этот хэлпер считает хэш указанного файла и добавляет его в урл. Все происходит автоматически !

#### Копировать файл в новое место

```javascript
elixir(function(mix) {
    mix.copy('vendor/foo/bar.css', 'public/css/bar.css');
});
```

#### Копировать каталог в новое место

```javascript
elixir(function(mix) {
    mix.copy('vendor/package/views', 'resources/views');
});
```

#### Соединение методов

Вы можете образовывать цепочки из методов:

```javascript
elixir(function(mix) {
    mix.less("app.less")
       .coffee()
       .phpUnit()
       .version("css/bootstrap.css");
});
```

## Gulp

Для выполнения зарегистрированных команд нужно запустить в командной строке `gulp`

#### Выполнение всех зарегистрированных команд

    gulp

#### Запуск команд при изменении файлов

    gulp watch

#### Запуск тестов при изменении классов

    gulp tdd

> **Note:** По умолчанию подразумевается, что конамды выполняются в development-окружении и собираемые скрипты не минифицируются. Чтобы добавить минификацию запустите `gulp --production`.

## Расширение

Вы можете создавать свои gulp-задачи и добавлять в elixir.
Например, сделаем шуточную задачу, которая выводит в терминал некое сообщение:

```javascript
 var gulp = require("gulp");
 var shell = require("gulp-shell");
 var elixir = require("laravel-elixir");

 elixir.extend("message", function(message) {

     gulp.task("say", function() {
         gulp.src("").pipe(shell("say " + message));
     });

     return this.queueTask("say");

 });
```

Первый аргумент в `extend` - имя задачи, которое мы будет далее использовать в нашем gulpfile.js , а второй - функция-замыкание с собственно кодом задачи, написанной для gulp.

Вы также можете мониторить изменения в заданных файлах:

```javascript
this.registerWatcher("message", "**/*.php");
```

Когда файл с путём, удовлетворяющем регекспу `**/*.php`, будет изменён - запустится задача `message`.

That's it! You may either place this at the top of your Gulpfile, or instead extract it to a custom tasks file. If you choose the latter approach, simply require it into your Gulpfile, like so:

Вы можете разместить этот код в верхней части вашего `gulpfile.js` , или в сыойм файле, и подключить его в `gulpfile.js` следующей конструкцией:

```javascript
require("./custom-tasks")
```

Дальше вы можете добавлять свою команду в микс:

```javascript
elixir(function(mix) {
    mix.message("Tea, Earl Grey, Hot");
});
```

Теперь, как только gulp исполнит какую-либо задачу, в терминал выведется строка "Tea, Earl Grey, Hot".


text:
package com.calendarfx.view;

import com.calendarfx.model.Entry;
import impl.com.calendarfx.view.MonthViewSkin;
import javafx.beans.Observable;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.scene.control.Skin;
import javafx.util.Callback;
import org.controlsfx.control.PropertySheet.Item;

import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.Optional;

import static java.util.Objects.requireNonNull;

/**
 * Visualizes an entire month including the last days of the previous month and
 * the first days of the next month. Each day is shown in its own box with its
 * entries. These entries are of type {@link MonthEntryView}.
 *

 *

 *
 *

 */
public class MonthView extends MonthViewBase implements ZonedDateTimeProvider {

    private static final String DEFAULT_STYLE_CLASS = "month-view";

    /**
     * Constructs a new month view.
     */
    public MonthView() {
        getStyleClass().add(DEFAULT_STYLE_CLASS);

        setEntryViewFactory(MonthEntryView::new);

        new CreateDeleteHandler(this);

        getSelectedDates().addListener((Observable it) -> {
            if (getSelectedDates().size() == 1) {
                LocalDate date = getSelectedDates().iterator().next();
                setDate(date);
            }
        });
    }

    @Override
    protected Skin<?> createDefaultSkin() {
        return new MonthViewSkin(this);
    }

    @Override
    public final ZonedDateTime getZonedDateTimeAt(double x, double y) {
        MonthViewSkin skin = (MonthViewSkin) getSkin();
        return skin.getZonedDateTimeAt(x, y);
    }

    private final BooleanProperty showCurrentWeek = new SimpleBooleanProperty(
            this, "showCurrentWeek", true); //$NON-NLS-1$

    /**
     * Controls whether the view will highlight the current week. The image
     * below shows an example:
     *

     *
     *
     * @see DateControl#todayProperty()
     *
     * @return true if the current week will be highlighted
     */
    public final BooleanProperty showCurrentWeekProperty() {
        return showCurrentWeek;
    }

    /**
     * Sets the value of {@link #showCurrentWeekProperty()}.
     *
     * @param show
     *            if true will highlight the current week
     */
    public final void setShowCurrentWeek(boolean show) {
        showCurrentWeekProperty().set(show);
    }

    /**
     * Returns the value of {@link #showCurrentWeekProperty()}.
     *
     * @return true if the current week will be highlighted
     */
    public final boolean isShowCurrentWeek() {
        return showCurrentWeekProperty().get();
    }

    private final BooleanProperty showWeekends = new SimpleBooleanProperty(
            this, "showWeekends", true); //$NON-NLS-1$

    /**
     * Controls whether the view will show weekend days differently than regular
     * week days. The image below shows an example:
     *

     *
     *
     * @return true if the weekend days will be shown differently
     */
    public final BooleanProperty showWeekendsProperty() {
        return showWeekends;
    }

    /**
     * Sets the value of {@link #showWeekendsProperty()}.
     *
     * @param show
     *            if true will show weekend days differently
     */
    public final void setShowWeekends(boolean show) {
        showWeekendsProperty().set(show);
    }

    /**
     * Returns the value of {@link #showWeekendsProperty()}.
     *
     * @return true if weekend days will be shown differently
     */
    public final boolean isShowWeekends() {
        return showWeekendsProperty().get();
    }

    private final BooleanProperty showWeekdays = new SimpleBooleanProperty(
            this, "showWeekdays", true); //$NON-NLS-1$

    /**
     * Controls whether the view will show the names of the week days ("Mo",
     * "Tu", "We", ...). The image below shows an example:
     *

     *
     *
     * @return true if the week day names will be shown
     */
    public final BooleanProperty showWeekdaysProperty() {
        return showWeekdays;
    }

    /**
     * Sets the value of {@link #showWeekdaysProperty()}.
     *
     * @param show
     *            if true will show the names of the week days
     */
    public final void setShowWeekdays(boolean show) {
        showWeekdaysProperty().set(show);
    }

    /**
     * Returns the value of {@link #showWeekdaysProperty()}.
     *
     * @return true if week day names will be shown
     */
    public final boolean isShowWeekdays() {
        return showWeekdaysProperty().get();
    }

    private final BooleanProperty showTimedEntries = new SimpleBooleanProperty(this,
            "showTimedEntries", true); //$NON-NLS-1$

    /**
     * Controls whether the view will show calendar entries that are not "full-day" entries
     * (e.g. "soccer training from 6pm till 8pm").
     *
     * @return true if timed entries will be shown
     */
    public final BooleanProperty showTimedEntriesProperty() {
        return showTimedEntries;
    }

    /**
     * Sets the value of {@link #showTimedEntriesProperty()}.
     *
     * @param show
     *            if true timed entries will be shown
     */
    public final void setShowTimedEntries(boolean show) {
        showTimedEntriesProperty().set(show);
    }

    /**
     * Returns the value of {@link #showTimedEntriesProperty()}.
     *
     * @return true if timed entries will be shown
     */
    public final boolean isShowTimedEntries() {
        return showTimedEntriesProperty().get();
    }

    private final BooleanProperty showFullDayEntries = new SimpleBooleanProperty(this,
            "showFullDayEntries", true); //$NON-NLS-1$

    /**
     * Controls whether the view will show calendar entries that are "full-day" entries
     * (e.g. "Birthday Dirk").
     *
     * @return true if full day entries will be shown
     */
    public final BooleanProperty showFullDayEntriesProperty() {
        return showFullDayEntries;
    }

    /**
     * Sets the value of {@link #showFullDayEntriesProperty()}.
     *
     * @param show
     *            if true full-day entries will be shown
     */
    public final void setShowFullDayEntries(boolean show) {
        showFullDayEntriesProperty().set(show);
    }

    /**
     * Returns the value of {@link #showFullDayEntriesProperty()}.
     *
     * @return true if full-day entries will be shown
     */
    public final boolean isShowFullDayEntries() {
        return showFullDayEntriesProperty().get();
    }

    private final ObjectProperty<Callback<Entry<?>, MonthEntryView>> entryViewFactory = new SimpleObjectProperty<>(
            this, "entryViewFactory"); //$NON-NLS-1$

    /**
     * A factory used for creating instances of type {@link MonthEntryView}.
     * These views will be shown within each day cell.
Code Example

     *
     *

     * setEntryViewFactory(entry -> {
     * 	return new MonthEntryView(entry);
     * });
     *

     *
     * @return the entry view factory
     */
    public final ObjectProperty<Callback<Entry<?>, MonthEntryView>> entryViewFactoryProperty() {
        return entryViewFactory;
    }

    /**
     * Returns the value of {@link #entryViewFactoryProperty()}.
     *
     * @return the entry view factory
     */
    public final Callback<Entry<?>, MonthEntryView> getEntryViewFactory() {
        return entryViewFactoryProperty().get();
    }

    /**
     * Sets the value of {@link #entryViewFactoryProperty()}.
     *
     * @param factory the entry view factory
     */
    public final void setEntryViewFactory(
            Callback<Entry<?>, MonthEntryView> factory) {
        requireNonNull(factory);
        entryViewFactoryProperty().set(factory);
    }

    @Override
    public void goBack() {
        setDate(getDate().minusMonths(1));
    }

    @Override
    public void goForward() {
        setDate(getDate().plusMonths(1));
    }

    private static final String MONTH_PAGE_CATEGORY = "Month View"; //$NON-NLS-1$

    @Override
    public ObservableList<Item> getPropertySheetItems() {
        ObservableList<Item> items = super.getPropertySheetItems();

        items.add(new Item() {

            @Override
            public Optional<ObservableValue<?>> getObservableValue() {
                return Optional.of(showWeekdaysProperty());
            }

            @Override
            public void setValue(Object value) {
                setShowWeekdays((boolean) value);
            }

            @Override
            public Object getValue() {
                return isShowWeekdays();
            }

            @Override
            public Class<?> getType() {
                return Boolean.class;
            }

            @Override
            public String getName() {
                return "Show Weekdays"; //$NON-NLS-1$
            }

            @Override
            public String getDescription() {
                return "Show or hide the weekdays"; //$NON-NLS-1$
            }

            @Override
            public String getCategory() {
                return MONTH_PAGE_CATEGORY;
            }
        });

        items.add(new Item() {

            @Override
            public Optional<ObservableValue<?>> getObservableValue() {
                return Optional.of(showWeekendsProperty());
            }

            @Override
            public void setValue(Object value) {
                setShowWeekends((boolean) value);
            }

            @Override
            public Object getValue() {
                return isShowWeekends();
            }

            @Override
            public Class<?> getType() {
                return Boolean.class;
            }

            @Override
            public String getName() {
                return "Show Weekends"; //$NON-NLS-1$
            }

            @Override
            public String getDescription() {
                return "Mark the weekends"; //$NON-NLS-1$
            }

            @Override
            public String getCategory() {
                return MONTH_PAGE_CATEGORY;
            }
        });

        items.add(new Item() {

            @Override
            public Optional<ObservableValue<?>> getObservableValue() {
                return Optional.of(showWeekNumbersProperty());
            }

            @Override
            public void setValue(Object value) {
                setShowWeekNumbers((boolean) value);
            }

            @Override
            public Object getValue() {
                return isShowWeekNumbers();
            }

            @Override
            public Class<?> getType() {
                return Boolean.class;
            }

            @Override
            public String getName() {
                return "Show Week Numbers"; //$NON-NLS-1$
            }

            @Override
            public String getDescription() {
                return "Show or hide the week numbers"; //$NON-NLS-1$
            }

            @Override
            public String getCategory() {
                return MONTH_PAGE_CATEGORY;
            }
        });

        items.add(new Item() {

            @Override
            public Optional<ObservableValue<?>> getObservableValue() {
                return Optional.of(showCurrentWeekProperty());
            }

            @Override
            public void setValue(Object value) {
                setShowCurrentWeek((boolean) value);
            }

            @Override
            public Object getValue() {
                return isShowCurrentWeek();
            }

            @Override
            public Class<?> getType() {
                return Boolean.class;
            }

            @Override
            public String getName() {
                return "Show Current Week"; //$NON-NLS-1$
            }

            @Override
            public String getDescription() {
                return "Highlight the current week"; //$NON-NLS-1$
            }

            @Override
            public String getCategory() {
                return MONTH_PAGE_CATEGORY;
            }
        });

        items.add(new Item() {

            @Override
            public Optional<ObservableValue<?>> getObservableValue() {
                return Optional.of(showFullDayEntriesProperty());
            }

            @Override
            public void setValue(Object value) {
                setShowFullDayEntries((boolean) value);
            }

            @Override
            public Object getValue() {
                return isShowFullDayEntries();
            }

            @Override
            public Class<?> getType() {
                return Boolean.class;
            }

            @Override
            public String getName() {
                return "Show Full Day Entries"; //$NON-NLS-1$
            }

            @Override
            public String getDescription() {
                return "Show full day entries"; //$NON-NLS-1$
            }

            @Override
            public String getCategory() {
                return MONTH_PAGE_CATEGORY;
            }
        });

        items.add(new Item() {

            @Override
            public Optional<ObservableValue<?>> getObservableValue() {
                return Optional.of(showTimedEntriesProperty());
            }

            @Override
            public void setValue(Object value) {
                setShowTimedEntries((boolean) value);
            }

            @Override
            public Object getValue() {
                return isShowTimedEntries();
            }

            @Override
            public Class<?> getType() {
                return Boolean.class;
            }

            @Override
            public String getName() {
                return "Show Timed Entries"; //$NON-NLS-1$
            }

            @Override
            public String getDescription() {
                return "Show timed entries"; //$NON-NLS-1$
            }

            @Override
            public String getCategory() {
                return MONTH_PAGE_CATEGORY;
            }
        });

        return items;
    }
}


text:
package com.stratio.cassandra.lucene.search.condition.builder;

import com.stratio.cassandra.lucene.search.condition.MatchCondition;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;

/**
 * {@link ConditionBuilder} for building a new {@link MatchCondition}.
 *
 * @author Andres de la Pena {@literal <adelapena@stratio.com>}
 */
public class MatchConditionBuilder extends ConditionBuilder<MatchCondition, MatchConditionBuilder> {

    /** The name of the field to be matched. */
    @JsonProperty("field")
    private final String field;

    /** The value of the field to be matched. */
    @JsonProperty("value")
    private final Object value;

    /**
     * Creates a new {@link MatchConditionBuilder} for the specified field and value.
     *
     * @param field The name of the field to be matched.
     * @param value The value of the field to be matched.
     */
    @JsonCreator
    public MatchConditionBuilder(@JsonProperty("field") String field, @JsonProperty("value") Object value) {
        this.field = field;
        this.value = value;
    }

    /**
     * Returns the {@link MatchCondition} represented by this builder.
     *
     * @return The {@link MatchCondition} represented by this builder.
     */
    @Override
    public MatchCondition build() {
        return new MatchCondition(boost, field, value);
    }
}


text:
<html>
<head>
<script src="../../http/tests/inspector/inspector-test.js"></script>
<script src="../../http/tests/inspector/console-test.js"></script>
<script>

function test()
{
    var testCases = [
        "copy('qwerty')",
        "copy(document.querySelector('p'))",
        "copy({foo:'bar'})",
        "var a = {}; a.b = a; copy(a)",
        "copy(document.all)",
        "copy(NaN)",
        "copy(Infinity)",
        "copy(null)",
        "copy(undefined)",
        "copy(1)",
        "copy(true)",
        "copy(false)"
    ];

    function copyText(text) {
        InspectorTest.addResult("InspectorFrontendHost.copyText: " + text);
    }

    InspectorFrontendHost.copyText = copyText;

    for (var i = 0; i < testCases.length; ++i)
        RuntimeAgent.evaluate(testCases[i], "", true);

    RuntimeAgent.evaluate("copy(null)", "", true, InspectorTest.completeTest.bind(InspectorTest));
}

</script>
</head>

<body onload="runTest()">
<p>
    Tests that console's copy command is copying into front-end buffer.
</p>

</body>
</html>


text:
import { Observable } from 'rxjs/Observable';
import 'firebase/database';
export class FirebaseObjectObservable extends Observable {
    constructor(subscribe, $ref) {
        super(subscribe);
        this.$ref = $ref;
    }
    lift(operator) {
        const observable = new FirebaseObjectObservable();
        observable.source = this;
        observable.operator = operator;
        observable.$ref = this.$ref;
        return observable;
    }
    set(value) {
        if (!this.$ref) {
            throw new Error('No ref specified for this Observable!');
        }
        return this.$ref.set(value);
    }
    update(value) {
        if (!this.$ref) {
            throw new Error('No ref specified for this Observable!');
        }
        return this.$ref.update(value);
    }
    remove() {
        if (!this.$ref) {
            throw new Error('No ref specified for this Observable!');
        }
        return this.$ref.remove();
    }
}
//# sourceMappingURL=firebase_object_observable.js.map


text:
package org.kuali.rice.krad.datadictionary.validation.constraint;

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.kuali.rice.krad.datadictionary.AttributeDefinition;
import org.kuali.rice.krad.datadictionary.BusinessObjectEntry;
import org.kuali.rice.krad.datadictionary.validation.Address;
import org.kuali.rice.krad.datadictionary.validation.AttributeValueReader;
import org.kuali.rice.krad.datadictionary.validation.DictionaryObjectAttributeValueReader;
import org.kuali.rice.krad.datadictionary.validation.ErrorLevel;
import org.kuali.rice.krad.datadictionary.validation.constraint.ValidCharactersConstraint;
import org.kuali.rice.krad.datadictionary.validation.processor.ValidCharactersConstraintProcessor;
import org.kuali.rice.krad.datadictionary.validation.result.ConstraintValidationResult;
import org.kuali.rice.krad.datadictionary.validation.result.DictionaryValidationResult;

/**
 * Things this test should check:
 *
 * 1. value with all valid characters. (success) {@link #testValueAllValidChars()}
 * 2. value with invalid characters. (failure) {@link #testValueNotValidChars()}
 * 3. value with all valid characters. Allowing white space.(success) {@link #testValueAllValidCharsAllowWhitespace()}
 * 4. value with invalid characters. Allowing white space. (failure) {@link #testValueNotValidCharsAllowWhitespace()}
 * 5. value with all valid characters. Allowing white space, period, underscore and parenthesis. (success) {@link #testValueAllValidCharsAllowWhitespaceAndPeriodAndUnderscoreAndParenthesis()}
 * 6. value with invalid characters. Allowing white space, period, underscore and parenthesis. (failure) {@link #testValueNotValidCharsAllowWhitespaceAndPeriodAndUnderscoreAndParenthesis()}
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class AlphaNumericPatternConstraintTest {

	private AttributeDefinition street1Definition;
	private AttributeDefinition street2Definition;
	private AttributeDefinition postalCodeDefinition;

	private BusinessObjectEntry addressEntry;
	private DictionaryValidationResult dictionaryValidationResult;

	private ValidCharactersConstraintProcessor processor;

	private Address washingtonDCAddress = new Address("893 Presidential Ave", "(A_123) Suite 800.", "Washington", "DC", "NHW123A", "USA", null);
	private Address newYorkNYAddress = new Address("Presidential Street", "(A-123) Suite 800", "New York", "NY", "ZH 3456", "USA", null);
	private Address sydneyAUSAddress = new Address("Presidential Street-Ave.", "Suite_800.", "Sydney", "ZZ", "ZH-5656", "USA", null);

	private AlphaNumericPatternConstraint street1AlphaNumericPatternConstraint;
	private AlphaNumericPatternConstraint street2AlphaNumericPatternConstraint;
	private AlphaNumericPatternConstraint postalCodeAlphaNumericPatternConstraint;

	@Before
	public void setUp() throws Exception {

		processor = new ValidCharactersConstraintProcessor();

		dictionaryValidationResult = new DictionaryValidationResult();
		dictionaryValidationResult.setErrorLevel(ErrorLevel.NOCONSTRAINT);

		addressEntry = new BusinessObjectEntry();

		List<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>();

		street1AlphaNumericPatternConstraint = new AlphaNumericPatternConstraint();
        street1AlphaNumericPatternConstraint.setMessageKey("validate.dummykey");
        street1AlphaNumericPatternConstraint.setValidationMessageParams( new ArrayList<String>());
		street1AlphaNumericPatternConstraint.setAllowWhitespace(true);

		street1Definition = new AttributeDefinition();
		street1Definition.setName("street1");
		street1Definition.setValidCharactersConstraint(street1AlphaNumericPatternConstraint);
		attributes.add(street1Definition);

		street2AlphaNumericPatternConstraint = new AlphaNumericPatternConstraint();
        street2AlphaNumericPatternConstraint.setMessageKey("validate.dummykey");
        street2AlphaNumericPatternConstraint.setValidationMessageParams( new ArrayList<String>());
		street2AlphaNumericPatternConstraint.setAllowWhitespace(true);
		street2AlphaNumericPatternConstraint.setAllowParenthesis(true);
		street2AlphaNumericPatternConstraint.setAllowPeriod(true);
		street2AlphaNumericPatternConstraint.setAllowUnderscore(true);

		street2Definition = new AttributeDefinition();
		street2Definition.setName("street2");
		street2Definition.setValidCharactersConstraint(street2AlphaNumericPatternConstraint);
		attributes.add(street2Definition);

		postalCodeAlphaNumericPatternConstraint = new AlphaNumericPatternConstraint();
        postalCodeAlphaNumericPatternConstraint.setMessageKey("validate.dummykey");
        postalCodeAlphaNumericPatternConstraint.setValidationMessageParams( new ArrayList<String>());

		postalCodeDefinition = new AttributeDefinition();
		postalCodeDefinition.setName("postalCode");
		postalCodeDefinition.setValidCharactersConstraint(postalCodeAlphaNumericPatternConstraint);
		attributes.add(postalCodeDefinition);

		addressEntry.setAttributes(attributes);
	}

	@Test
	public void testValueAllValidChars() {
		ConstraintValidationResult result = process(washingtonDCAddress, "postalCode", postalCodeAlphaNumericPatternConstraint);
		Assert.assertEquals(0, dictionaryValidationResult.getNumberOfWarnings());
		Assert.assertEquals(0, dictionaryValidationResult.getNumberOfErrors());
		Assert.assertEquals(ErrorLevel.OK, result.getStatus());
		Assert.assertEquals(new ValidCharactersConstraintProcessor().getName(), result.getConstraintName());
	}

	@Test
	public void testValueNotValidChars() {
		ConstraintValidationResult result = process(newYorkNYAddress, "postalCode", postalCodeAlphaNumericPatternConstraint);
		Assert.assertEquals(0, dictionaryValidationResult.getNumberOfWarnings());
		Assert.assertEquals(1, dictionaryValidationResult.getNumberOfErrors());
		Assert.assertEquals(ErrorLevel.ERROR, result.getStatus());
		Assert.assertEquals(new ValidCharactersConstraintProcessor().getName(), result.getConstraintName());
	}

	@Test
	public void testValueAllValidCharsAllowWhitespace() {
		ConstraintValidationResult result = process(newYorkNYAddress, "street1", street1AlphaNumericPatternConstraint);
		Assert.assertEquals(0, dictionaryValidationResult.getNumberOfWarnings());
		Assert.assertEquals(0, dictionaryValidationResult.getNumberOfErrors());
		Assert.assertEquals(ErrorLevel.OK, result.getStatus());
		Assert.assertEquals(new ValidCharactersConstraintProcessor().getName(), result.getConstraintName());
	}

	@Test
	public void testValueNotValidCharsAllowWhitespace() {
		ConstraintValidationResult result = process(sydneyAUSAddress, "street1", street1AlphaNumericPatternConstraint);
		Assert.assertEquals(0, dictionaryValidationResult.getNumberOfWarnings());
		Assert.assertEquals(1, dictionaryValidationResult.getNumberOfErrors());
		Assert.assertEquals(ErrorLevel.ERROR, result.getStatus());
		Assert.assertEquals(new ValidCharactersConstraintProcessor().getName(), result.getConstraintName());
	}

	@Test
	public void testValueAllValidCharsAllowWhitespaceAndPeriodAndUnderscoreAndParenthesis() {
		ConstraintValidationResult result = process(washingtonDCAddress, "street2", street2AlphaNumericPatternConstraint);
		Assert.assertEquals(0, dictionaryValidationResult.getNumberOfWarnings());
		Assert.assertEquals(0, dictionaryValidationResult.getNumberOfErrors());
		Assert.assertEquals(ErrorLevel.OK, result.getStatus());
		Assert.assertEquals(new ValidCharactersConstraintProcessor().getName(), result.getConstraintName());
	}

	@Test
	public void testValueNotValidCharsAllowWhitespaceAndPeriodAndUnderscoreAndParenthesis() {
		ConstraintValidationResult result = process(newYorkNYAddress, "street2", street2AlphaNumericPatternConstraint);
		Assert.assertEquals(0, dictionaryValidationResult.getNumberOfWarnings());
		Assert.assertEquals(1, dictionaryValidationResult.getNumberOfErrors());
		Assert.assertEquals(ErrorLevel.ERROR, result.getStatus());
		Assert.assertEquals(new ValidCharactersConstraintProcessor().getName(), result.getConstraintName());
	}

	private ConstraintValidationResult process(Object object, String attributeName, ValidCharactersConstraint constraint) {
		AttributeValueReader attributeValueReader = new DictionaryObjectAttributeValueReader(object, "org.kuali.rice.kns.datadictionary.validation.MockAddress", addressEntry);
		attributeValueReader.setAttributeName(attributeName);

		Object value = attributeValueReader.getValue();
		return processor.process(dictionaryValidationResult, value, constraint, attributeValueReader).getFirstConstraintValidationResult();
	}
}


text:
set -e

source scripts/language_environment.sh "$@"

header "Check we can execute daff and git"
which $DAFF_SCRIPT
which git
$DAFF_SCRIPT version
git --version

header "Create a test git repository"
mkdir test_repo
cd test_repo
git init
git config user.email "nevyn@example.com"
git config user.name "Nevyn"
cp $org/test/data/broken_bridges.csv bridges.csv
git add bridges.csv
git commit -m "first version" -a
cp $org/test/data/bridges.csv bridges.csv
git commit -m "second version" -a
cd ..

header "Check git repository"
cd test_repo
git diff HEAD^1 > diff1
$DAFF_SCRIPT git csv
git diff HEAD^1 > diff2
cmp diff1 diff2 && {
    echo "Diff did not change, it should have changed"
    exit 1
} || echo "good"

cd $org


text:
'use strict';
const assert = require('assert');
const acl = require('../../');
const httpMocks = require('node-mocks-http');

let response = {
  success: {
    status: 200,
    success: true,
    message: 'ACCESS GRANTED'
  },
  restricted: {
    status: 'Access denied',
    success: false,
    message: 'Unauthorized access'
  }
};

describe('Testing Methods', function() {
  let req, res, data, next;
  beforeEach(function(done) {
    res = httpMocks.createResponse();
    next = function() {
      res.send(response.success);
    };
    done();
  });

  context('When action deny', function() {
    beforeEach(function(done) {
      acl.config({
        baseUrl: 'api',
        filename: 'methods-glob-deny.json',
        path: './tests/config'
      });
      done();
    });

    it('Should deny access to resource /api/mangoes/42', function(done) {
      req = httpMocks.createRequest({
        method: 'POST',
        url: '/api/mangoes/42'
      });

      req.decoded = {};
      req.session = {};
      req.decoded.role = 'user';
      acl.authorize(req, res, next);
      data = res._getData();
      assert(data, true);
      assert(typeof data, 'object');
      assert.deepEqual(data, response.restricted);
      done();
    });

    it('Should deny access to resource/api/mangoes/42', function(done) {
      req = httpMocks.createRequest({
        method: 'PUT',
        url: '/api/mangoes/42'
      });
      req.decoded = {};
      req.session = {};
      req.session.role = 'user';
      acl.authorize(req, res, next);
      data = res._getData();
      assert(data, true);
      assert(typeof data, 'object');
      assert.deepEqual(data, response.restricted);
      done();
    });

    it('Should deny access to resource /api/mangoes/42', function(done) {
      req = httpMocks.createRequest({
        method: 'DElETE',
        url: '/api/mangoes/42'
      });

      req.decoded = {};
      req.session = {};
      req.decoded.role = 'user';
      acl.authorize(req, res, next);
      data = res._getData();
      assert(data, true);
      assert.deepEqual(data, response.restricted);
      done();
    });
  });

  context('When action allow', function() {
    beforeEach(function(done) {
      acl.config({
        baseUrl: 'api',
        filename: 'methods-glob-allow.json',
        path: './tests/config'
      });
      done();
    });

    it('Should allow traffic to resources /api/mangoes/42', function(done) {
      req = httpMocks.createRequest({
        method: 'POST',
        url: '/api/mangoes/42'
      });

      req.decoded = {};
      req.session = {};
      req.decoded.role = 'user';
      acl.authorize(req, res, next);
      data = res._getData();

      assert(data, true);
      assert.deepEqual(data, response.success);
      done();
    });

    it('Should allow traffic to resources /api/mangoes/42', function(done) {
      req = httpMocks.createRequest({
        method: 'PUT',
        url: '/api/mangoes/42'
      });

      req.decoded = {};
      req.session = {};
      req.decoded.role = 'user';
      acl.authorize(req, res, next);
      data = res._getData();
      assert(data, true);
      assert.deepEqual(data, response.success);
      done();
    });

    it('Should allow traffic to resources /api/user/42', function(done) {
      req = httpMocks.createRequest({
        method: 'DElETE',
        url: '/api/mangoes/42'
      });
      req.decoded = {};
      req.session = {};
      req.decoded.role = 'user';
      acl.authorize(req, res, next);
      data = res._getData();
      assert(data, true);
      assert.deepEqual(data, response.success);
      done();
    });
  });

});


text:
namespace gl
{

class Context;

bool ValidateES3TexImageParameters(Context *context, GLenum target, GLint level, GLenum internalformat, bool isCompressed, bool isSubImage,
                                   GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth,
                                   GLint border, GLenum format, GLenum type, const GLvoid *pixels);

bool ValidateES3CopyTexImageParameters(Context *context, GLenum target, GLint level, GLenum internalformat,
                                       bool isSubImage, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y,
                                       GLsizei width, GLsizei height, GLint border);

bool ValidateES3TexStorageParameters(Context *context, GLenum target, GLsizei levels, GLenum internalformat,
                                     GLsizei width, GLsizei height, GLsizei depth);

bool ValidateFramebufferTextureLayer(Context *context, GLenum target, GLenum attachment,
                                     GLuint texture, GLint level, GLint layer);

bool ValidES3ReadFormatType(Context *context, GLenum internalFormat, GLenum format, GLenum type);

bool ValidateES3RenderbufferStorageParameters(Context *context, GLenum target, GLsizei samples,
                                              GLenum internalformat, GLsizei width, GLsizei height);

bool ValidateInvalidateFramebuffer(Context *context, GLenum target, GLsizei numAttachments,
                                   const GLenum *attachments);

bool ValidateClearBuffer(Context *context);

bool ValidateGetUniformuiv(Context *context, GLuint program, GLint location, GLuint* params);

bool ValidateReadBuffer(Context *context, GLenum mode);

bool ValidateCompressedTexImage3D(Context *context,
                                  GLenum target,
                                  GLint level,
                                  GLenum internalformat,
                                  GLsizei width,
                                  GLsizei height,
                                  GLsizei depth,
                                  GLint border,
                                  GLsizei imageSize,
                                  const GLvoid *data);
}

#endif // LIBANGLE_VALIDATION_ES3_H_


text:
if nil ~= require then
	require "fritomod/ReflectiveTestSuite";
	require "fritomod/Assert";
	require "fritomod/Tests";
end;

local Suite = ReflectiveTestSuite:New("sanity");

local function Count(...)
	local total = select("#", ...);
	local nonNils = 0;
	for i=1, total do
		if select(i, ...) ~= nil then
			nonNils = nonNils + 1;
		end;
	end;
	return total, nonNils;
end;

function Suite:TestTableNewIndexFiresOnEveryNil()
	local f=Tests.Flag();
	local t=setmetatable({}, {
		__newindex=function(self,k,v)
			f.Raise();
			rawset(self,k,v);
		end
	});
	t.a=true;
	f.Unset();
	t.a=nil;
	f.AssertUnset("newindex must not be fired on deleted indices");
	t.a=true;
	f.Assert("newindex is fired on setting nil indices, even if they're not completely new");
end;

function Suite:TestStringSub()
	Assert.Equals("BC", ("ABC"):sub(2));
end;

function Suite:TestPairsIteratesEverything()
	local a={true,false,true};
	local c={};
	for k,v in pairs(a) do
		c[k]=v;
	end;
	Assert.Equals(a,c);
end;

function Suite:TestZeroIsTruthy()
	assert(0 or false);
end;

function Suite:TestOneToOneForLoopIteratesOnce()
	local f=Tests.Flag();
	for i=1,1 do
		f:AssertUnset("Loop only loops once");
		f:Raise();
	end;
	f:Assert("Flag was raised");
end;

function Suite:TestMaxn()
	local t = {};
	table.insert(t, true);
	table.insert(t, true);
	table.insert(t, true);
	Assert.Equals(3, table.maxn(t));
	t[2] = nil;
	Assert.Equals(3, table.maxn(t));
	t[4] = true;
	table.remove(t,4);
	Assert.Equals(3, table.maxn(t));
end;

function Suite:TestNewProxy()
	local p=newproxy(true);
	local mt=getmetatable(p);
	mt. __newindex = function(self, key, value)
		print(key);
	end
	mt.__len = function()
		return 3;
	end;
	local c={};
	for i=1,#p do
		table.insert(c, i);
	end;
	Assert.Equals({1,2,3},c);
end

function Suite:TestSparseArray()
	local list = {nil, nil, nil};
	list[3] = true;
	Assert.Equals(3, #list, "Sparse array retains size");
end;

function Suite:TestSparseArrayIsWipedOutDuringRemoval()
	local list = {nil, nil, nil};
	list[3] = true;
	list[2] = true;
	table.remove(list, 3);
	Assert.Equals(0, #list, "Sparse array's size is lost due to table.remove");
end;

function Suite:TestVarargsSizeIsConstant()
	Assert.Equals(2, Count(nil, nil), "Varargs retains size in spite of nil values");
end;

function Suite:TestUnpackWithNils()
	local total, nonNils = Count(unpack({nil, 2}));
	Assert.Equals(2, total, "Unpack unpacks correctly when array is of correct size");
	Assert.Equals(1, nonNils, "Unpack passes non-nil values");
end;

-- Demonstrates that intermediate nil values cause problems even if the array exists
-- almost entirely as a non-nil structure. They even cause problems if the array has
-- existed with only non-nil elements.
--
-- In other words, you simply never know what the length is if your array is sparse and
-- you're performing insertions or deletions.
function Suite:TestArrayLengthIsAbsurd()
	local inconsistencies = {};
	for insertions=1, 100 do
		for removalIndex=1, insertions do
			local list = {};
			for i=1, insertions do
				table.insert(list, true);
			end;
			list[removalIndex] = nil;
			if removalIndex == insertions and #list ~= insertions - 1 then
				table.insert(inconsistencies, {insertions, removalIndex, #list});
			elseif #list ~= insertions then
				table.insert(inconsistencies, {insertions, removalIndex, #list});
			end;
		end;
	end;
	assert(#inconsistencies > 0, "Array length is inconsistent");
end;

-- Demonstrates that even primed arrays still have inconsistencies with array length.
-- While investigating supporting nil values in Curry, I found out that {nil, nil, nil, ...}
-- seemed to preserve its length in most cases as long as the last element was not nil.
-- This turned out to be false, as this test case demonstrates. Specifically, things
-- start falling apart around 17 insertions, and never get any better. It essentially
-- approaches the inconsistencies found in the previous test case.
--
-- It may be possible that supporting sub-16 nil arguments in currying is possible, but
-- it seems to be about as error-prone as one can imagine to code, probably not anywhere
-- near performant, will never handle trailing nil values properly, and is a very rare use-
-- case anyway.
function Suite:TestAbsurdArrayLengthWithPrimedLengthTable()
	local inconsistencies = {};
	-- Changing the max intended length to 16 or lower will yield a failing test, meaning
	-- this strategy seems to work. Of course, this is only testing one nil value.
	for intendedLength=1, 100 do
		for removalIndex=1, intendedLength-1 do
			-- Creates a list that seems to be primed such that its length is more consistent
			-- than one created by table.insert alone.
			local code = ("return { %s }"):format(("true, "):rep(intendedLength));
			local list = assert(loadstring(code))();
			list[removalIndex] = nil;
			if #list ~= intendedLength then
				table.insert(inconsistencies, {insertions, removalIndex, #list});
			end;
		end;
	end;
	assert(#inconsistencies > 0, "Array length is still not consistent");
end;

function Suite:TestMetatableIsNotCalledOnTableInsertion()
	local t = {};
	local f = Tests.Flag();
	setmetatable(t, {
		__newindex = function(self, k, v)
			f:Raise();
		end
	});
	table.insert(t, "notime");
	f.AssertFalse("Metatable is not used for insertion");
	Assert.Equals(1, #t, "Value is inserted into table");
end;

function Suite:TestCountdown()
	local t = {1,2,3,4};
	local c = {};
	for i=#t,1,-1 do
		table.insert(c, t[i]);
	end;
	Assert.Equals({4,3,2,1},c);
end;

do
    local g1, g2, g3;
    Suite:AddListener(Metatables.Noop({
        TestStarted = function(self, suite)
            g1 = __g1;
            g2 = __g2;
            g3 = __g3;
        end,
        TestFinished = function(self, suite)
            __g1 = g1;
            __g2 = g2;
            __g3 = g3;
        end
    }));
end;

function Suite:TestSetfenvHidesTrueGlobals()
    local g = {};

    local trueGlobal = _G;
    local assert = assert;
    local function Test()
        __g1 = 42;
        assert(_G ~= trueGlobal, "_G must not refer to the true global table");
        assert(_G == nil, "_G must be nil unless otherwise specified");
    end;

    setfenv(Test, g);
    Test();
    Assert.Equals(42, g.__g1);
    Assert.Nil(__g1);
end;

function Suite:TestNestedFunctionsIgnoreSetfenv()
    local grandchild = {};
    local function Grandchild()
        __g2 = "grandchild";
    end;
    -- I use setfenv here to ensure we don't pollute the global namespace, but
    -- the test is still valid if we omit this safety mechanism.
    --
    -- Specifically, functions invoked from a setfenv'd function will use their
    -- own environment; they will not inherit.
    setfenv(Grandchild, grandchild);

    local child = {};
    local function Child()
        __g1 = "child";
        Grandchild();
    end;
    setfenv(Child, child);

    Child();
    Assert.Equals("child", child.__g1);
    Assert.Nil(child.__g2);
    Assert.Equals("grandchild", grandchild.__g2);
end;

function Suite:TestNewFunctionsInheritSetfenvTable()
    local child = {};

    local function Child()
        local function GrandChild()
            __g2 = "grandchild";
        end;
        __g1 = "child";
        GrandChild();
    end;
    setfenv(Child, child);
    Child();

    Assert.Nil(__g1);
    Assert.Equals("child", child.__g1);
    Assert.Nil(__g2);
    Assert.Equals("grandchild", child.__g2);
end;


text:
Open a browser, navigate to a SharePoint site and create a new list. Then add a few items to the list.

Next, open Fiddler and use the existing authenticated session to demonstrate how to do simple HTTP GET's, both getting all, filtering and getting one item. Also highlight the following OData operators:

- $select
- $filter
- $orderby

Demonstrate the differences in the payloads (XML vs. JSON).

Demonstrate the `$metadata` endpoint.

Demonstrate how responses show relationships between other entities.

## Demo Completed Lab Solutions

Use the **Completed Solution** from the lab exercise 1 & 2 in this demo: **RestClientSide** & **RestServerSide**.

Show the client-side & server-side code required for querying data from SharePoint lists using the REST API.


text:
namespace TheDarkness
{
	class GLSLProgram
	{
	public:
		GLSLProgram();
		~GLSLProgram();

		GLint GetUniformLoca(const std::string& name);
		void CompileShaders(
			const std::string& vfp,
			const std::string& ffp);
		// -----------------------------------
		void CompileAndLinkShaders(
			const std::vector<std::string>& vsps,
			const std::vector<std::string>& fsps);
		void LinkShaders();
		// -----------------------------
		// Use these three in conjunction if not the previous two in conjunction
		// ------------------------------
		void Init();
		GLuint CompileFromString(GLenum type, const char*);
		void Link(const std::vector<GLuint>&);
		// --------------------------------
		void AddAttribute(const std::string& attrib_name)
		{
			glBindAttribLocation(_progID, numAttributes++, attrib_name.c_str());
		}

		void Bind() {
			glUseProgram(_progID);
			for(int i = 0; i < numAttributes; i++)
				glEnableVertexAttribArray(i);
		}
		void Unbind() {
			glUseProgram(0);
			for(int i = 0; i < numAttributes; i++)
				glDisableVertexAttribArray(i);
		}

		// Delete current program and create a new one
		void Reset();
	private:
		int numAttributes = 0;
		void compileShader(const std::string&, GLuint id);
		GLuint _progID = 0;
		GLuint _vertShaderID = 0;
		GLuint _fragShaderID = 0;
	};
}


text:
Symfony-MooTools-NoobSlide-Wrapper-Plugin
=========================================

This sfMooNoobSlidePlugin is for Symfony 1.4 and Mootools 1.3
This plugin is a wrapper for [MooTools noobSlide](http://www.efectorelativo.net/laboratory/noobSlide/).

How to use
----------

There is two mode used in this plugin:

*	picasa album and
*	javascript files that hold photo array.
    sample javascript included in /media/user/js/

For each mode you can put title and subtitle.
Here is sample for picasa mode in template:

	use_helper('sfMooNoobSlide');
	plgContentNoobSlideActivate();
	plgContentNoobSlide(array(
		'title' => 'AlumniBook Screenshot',
		'subtitle' => 'Any related AlumniBook ports.',
		'lightbox_type' => 3,
		// picasa mode
		'picasa_user'	=> 'epsi.rns',
		'picasa_album'	=> 'AlumniBook'
	));

You might want to choose lightbox from plugin parameter.

1.	Slimbox
2.	Mediabox Advance
3.	Diabox

This lightbox plugin come as external plugin with no dependencies.
Don't forget to manually activate lightbox plugin in template before activating noobslide.

	use_helper('sfMooDiaBox');
	plgContentDiaBoxActivate();

License
-------

[MIT License](http://www.opensource.org/licenses/mit-license.php)


text:
#include "src/core/support/file.h"

#include <errno.h>
#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>

#include "src/core/support/string.h"

gpr_slice gpr_load_file(const char *filename, int add_null_terminator,
                        int *success) {
  unsigned char *contents = NULL;
  size_t contents_size = 0;
  char *error_msg = NULL;
  gpr_slice result = gpr_empty_slice();
  FILE *file = fopen(filename, "rb");
  size_t bytes_read = 0;

  if (file == NULL) {
    gpr_asprintf(&error_msg, "Could not open file %s (error = %s).", filename,
                 strerror(errno));
    GPR_ASSERT(error_msg != NULL);
    goto end;
  }
  fseek(file, 0, SEEK_END);
  /* Converting to size_t on the assumption that it will not fail */
  contents_size = (size_t)ftell(file);
  fseek(file, 0, SEEK_SET);
  contents = gpr_malloc(contents_size + (add_null_terminator ? 1 : 0));
  bytes_read = fread(contents, 1, contents_size, file);
  if (bytes_read < contents_size) {
    GPR_ASSERT(ferror(file));
    gpr_asprintf(&error_msg, "Error %s occured while reading file %s.",
                 strerror(errno), filename);
    GPR_ASSERT(error_msg != NULL);
    goto end;
  }
  if (success != NULL) *success = 1;
  if (add_null_terminator) {
    contents[contents_size++] = 0;
  }
  result = gpr_slice_new(contents, contents_size, gpr_free);

end:
  if (error_msg != NULL) {
    gpr_log(GPR_ERROR, "%s", error_msg);
    gpr_free(error_msg);
    if (success != NULL) *success = 0;
  }
  if (file != NULL) fclose(file);
  return result;
}


text:
var
	utils     = require('./../Utils.js'),
	ACLPlugin = require('./ACL.js');

function CustomCommandsPlugin() {
	this.bot       = null;
	this.db        = null;
	this.acl       = null;
	this.aclPlugin = null;
	this.log       = null;
	this.listener  = null;
	this.prefix    = null;
	this.data      = {};
	this.table     = 'custom_commands';
}

CustomCommandsPlugin.prototype = {
	setup: function(kabukibot, eventDispatcher) {
		var i, plugins;

		this.bot      = kabukibot;
		this.db       = kabukibot.getDatabase();
		this.acl      = kabukibot.getACL();
		this.log      = kabukibot.getLog();
		this.listener = this.onCommand.bind(this);
		this.prefix   = kabukibot.getCommandPrefix();

		plugins = kabukibot.getPluginManager().getPlugins();

		for (i in plugins) {
			if (plugins[i] instanceof ACLPlugin) {
				this.aclPlugin = plugins[i];
				break;
			}
		}

		if (this.bot.getConfig().database.driver === 'sqlite') {
			this.db.query('CREATE TABLE IF NOT EXISTS ' + this.table + ' (channel VARCHAR(200), command VARCHAR(200), message VARCHAR(1024), PRIMARY KEY (channel, command))');
		}
		else {
			this.db.query('CREATE TABLE IF NOT EXISTS ' + this.table + ' (channel VARCHAR(200), command VARCHAR(200), message VARCHAR(1024), PRIMARY KEY (channel, command)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
		}
	},

	getKey: function() {
		return 'custom_commands';
	},

	getACLTokens: function(channel) {
		var commands = this.getCommands(channel), tokens = ['configure_custom_commands', 'configure_custom_commands_acl', 'list_custom_commands'], cmd;

		for (cmd in commands) {
			tokens.push(this.getACLTokenForCustomCommand(cmd));
		}

		return tokens;
	},

	load: function(channel, kabukibot, eventDispatcher) {
		var self = this, chan = channel.getName(), ircName = channel.getIrcName();

		eventDispatcher.onCommand(ircName, this.listener);

		this.data[chan] = {};

		this.db.select(this.table, '*', { channel: chan }, function(err, rows) {
			var i, len;

			if (err) {
				self.log.error('Could not query custom commands: ' + err.message);
				return;
			}

			self.log.debug('Loaded ' + rows.length + ' custom commands for ' + ircName + '.');

			for (i = 0, len = rows.length; i < len; ++i) {
				self.data[chan][rows[i].command] = rows[i].message;
			}
		});
	},

	unload: function(channel, kabukibot, eventDispatcher) {
		var chan = channel.getName();

		eventDispatcher.removeCommandListener(channel.getIrcName(), this.listener);

		if (chan in this.data) {
			delete this.data[chan];
		}
	},

	onCommand: function(command, args, message) {
		if (message.isProcessed()) return;

		var chan = message.getChannel().getName(), commands = this.getCommands(message.getChannel());

		// not for us
		if (!this.isPluginCommand(command) && !(command in commands)) {
			return;
		}

		// if this is a command that has already been responded to, do nothing
		if (message.isProcessed()) {
			return;
		}

		// check permissions
		if (!this.acl.isAllowed(message.getUser(), this.getRequiredACLToken(command))) {
			return;
		}

		switch (command) {
			case 'cc_list':  return this.respondList(commands, message);
			case 'cc_allow': return this.respondAllowDeny('allow', args, commands, message);
			case 'cc_deny':  return this.respondAllowDeny('deny', args, commands, message);
			case 'cc_get':   return this.respondGet(args, commands, message);
			case 'cc_set':   return this.respondSet(chan, args, commands, message);
			case 'cc_del':   return this.respondDel(chan, args, commands, message);
			default:         return this.sendResponse(command, commands, message);
		}
	},

	respondList: function(commands, message) {
		var result = [], cmd;

		for (cmd in commands) {
			result.push('!' + cmd);
		}

		if (result.length === 0) {
			message.respond('no custom commands have been defined yet.');
		}
		else {
			message.respond('custom commands are: ' + utils.humanJoin(result));
		}
	},

	respondAllowDeny: function(action, args, commands, message) {
		var command, token;

		if (args.length < 1) {
			message.respond(this.bot.getErrorResponse() + 'no command name given');
			return;
		}

		command = this.normalizeCommand(args[0]);

		if (command.length === 0) {
			message.respond(this.bot.getErrorResponse() + 'command name may only consist of letters, numbers and underscores (_).');
			return;
		}

		if (!(command in commands)) {
			message.respond(this.bot.getErrorResponse() + 'command !' + command + ' is undefined.');
			return;
		}

		token = this.getACLTokenForCustomCommand(command);
		args  = args.slice(1);

		this.aclPlugin.handleAllowDeny(message.getChannel(), this.prefix + action, token, args, message);
	},

	respondGet: function(args, commands, message) {
		var command;

		if (args.length < 1) {
			message.respond(this.bot.getErrorResponse() + 'no command name given');
			return;
		}

		command = this.normalizeCommand(args[0]);

		if (command.length === 0) {
			message.respond(this.bot.getErrorResponse() + 'command name may only consist of letters, numbers and underscores (_).');
			return;
		}

		if (command in commands) {
			message.respond('"!' + command + '" = ' + commands[command]);
		}
		else {
			message.respond(this.bot.getErrorResponse() + 'command !' + command + ' is undefined.');
		}
	},

	respondSet: function(chan, args, commands, message) {
		var command, text, exists;

		if (args.length < 1) {
			message.respond(this.bot.getErrorResponse() + 'no command name and no response text given.');
			return;
		}

		if (args.length < 2) {
			message.respond(this.bot.getErrorResponse() + 'no response text given.');
			return;
		}

		command = this.normalizeCommand(args[0]);

		if (command.length === 0) {
			message.respond(this.bot.getErrorResponse() + 'command name may only consist of letters, numbers and underscores (_).');
			return;
		}

		if (this.isPluginCommand(command)) {
			message.respond(this.bot.getErrorResponse() + 'you cannot override plugin commands.');
			return;
		}

		text   = args.slice(1).join(' ');
		exists = command in commands;

		this.data[chan][command] = text;

		if (exists) {
			this.db.update(this.table, { message: text }, { channel: chan, command: command });
			message.respond('command !' + command + ' has been updated.');
		}
		else {
			this.db.insert(this.table, { channel: chan, command: command, message: text });
			message.respond('command !' + command + ' has been created.');
		}
	},

	respondDel: function(chan, args, commands, message) {
		var command;

		if (args.length < 1) {
			message.respond(this.bot.getErrorResponse() + 'no command name given.');
			return;
		}

		command = this.normalizeCommand(args[0]);

		if (command.length === 0) {
			message.respond(this.bot.getErrorResponse() + 'command name may only consist of letters, numbers and underscores (_).');
			return;
		}

		if (!(command in commands)) {
			message.respond(this.bot.getErrorResponse() + 'command !' + command + ' is undefined.');
			return;
		}

		this.db.del(this.table, { channel: chan, command: command });
		this.acl.deletePermission(chan, this.getACLTokenForCustomCommand(command));
		delete this.data[chan][command];

		message.respond('command !' + command + ' has been deleted.');
	},

	sendResponse: function(command, commands, message) {
		message.respondToAll(commands[command]);
	},

	getCommands: function(channel) {
		var chan = (typeof channel === 'string') ? channel : channel.getName();

		return (chan in this.data) ? this.data[chan] : {};
	},

	isPluginCommand: function(cmd) {
		return cmd === 'cc_set' || cmd === 'cc_get' || cmd === 'cc_del' || cmd === 'cc_list' || cmd === 'cc_allow' || cmd === 'cc_deny';
	},

	getACLTokenForCustomCommand: function(cmd) {
		return 'use_' + cmd + '_cmd';
	},

	getRequiredACLToken: function(cmd) {
		if (cmd === 'cc_allow' || cmd === 'cc_deny') {
			return 'configure_custom_commands_acl';
		}
		else if (cmd === 'cc_list') {
			return 'list_custom_commands';
		}
		else if (this.isPluginCommand(cmd)) {
			return 'configure_custom_commands';
		}
		else {
			return this.getACLTokenForCustomCommand(cmd);
		}
	},

	normalizeCommand: function(cmd) {
		return cmd.replace(/[^a-z0-9_]/ig, '').toLowerCase();
	}
};

module.exports = CustomCommandsPlugin;


text:
baldwex
=======

This project is a fork of lwdba on SourceForge.org, originally developed by qing_wang.

Project Name

The name of this project 'baldwex' is derived from the rearrangement of the letters 'lwdba' and 'ex'tend. :)

Description

The purpose of baldwex is to provide simple and clean common database access by collecting SQLs in centralized class with uses of Facade pattern or properties file, also has easy-to-setup configurations with mulitple purposes support. As a result, no more SQL fragment strings all over the whole project thus producing cleaner code.

Extension of lwdba

lwdba is a great project for providing easy CURD db operations, but there are more improvements which can be added to make it better. The following lists the major changes and improvements of this extension project.

...TODO

Source

Forked from tags 0.8.1.

...TODO


text:
const path = require('path');
const HtmlWP = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: {
        app: './src/index.js',
    },
    output: {
        path: path.resolve('./dist'),
        filename: '[name].js',
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loaders: ['babel-loader', 'eslint-loader', ],
                exclude: /node_modules/,
            },
            {
                test: /\.css|\.scss/,
                loaders: ExtractTextPlugin.extract('css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!sass-loader'),
                exclude: /node_modules/,
            },
        ]
    },
    plugins: [
        new HtmlWP({
            template: './src/index.html',
            filename: 'index.html',
            inject: 'body',
        }),
        new ExtractTextPlugin('styles.css'),
    ],
    watchOptions: {
        poll: true,
    },
};


text:
(async function() {
  TestRunner.addResult(`Tests that changing a property is undone properly.\n`);
  await TestRunner.loadLegacyModule('elements'); await TestRunner.loadTestModule('elements_test_runner');
  await TestRunner.showPanel('elements');
  await TestRunner.loadHTML(`

    `);

  ElementsTestRunner.selectNodeAndWaitForStyles('container', step1);

  async function step1() {
    TestRunner.addResult('Initial value');
    await ElementsTestRunner.dumpSelectedElementStyles(true);

    var treeItem = ElementsTestRunner.getMatchedStylePropertyTreeItem('font-weight');
    treeItem.applyStyleText('font-weight: normal', false);
    ElementsTestRunner.waitForStyles('container', step2);
  }

  async function step2() {
    TestRunner.addResult('After changing property');
    await ElementsTestRunner.dumpSelectedElementStyles(true);

    SDK.domModelUndoStack.undo();
    ElementsTestRunner.selectNodeAndWaitForStyles('other', step3);
  }

  async function step3() {
    TestRunner.addResult('After undo');
    await ElementsTestRunner.dumpSelectedElementStyles(true);

    SDK.domModelUndoStack.redo();
    ElementsTestRunner.selectNodeAndWaitForStyles('container', step4);
  }

  async function step4() {
    TestRunner.addResult('After redo');
    await ElementsTestRunner.dumpSelectedElementStyles(true);
    TestRunner.completeTest();
  }
})();


text:
class MegaeyesRequestSerialize
{
public:

	MegaeyesRequestSerialize()
	{

	}
	virtual ~MegaeyesRequestSerialize()
	{

	}

public:
	//ÐòÁл¯
	virtual  std::string Serialize()=0;
	//·´ÐòÁл¯
	virtual void UnSerialize(const std::string& strMessage)=0;
public:
	MegaeyesRequestHead m_cmdHead;
	CMarkup m_xml;
};
#endif


text:
layout: attachment
title: app3-logo
date: 2014-11-07 16:51:24.000000000 -05:00
categories: []
tags: []
status: inherit
type: attachment
published: false
meta: {}
author:
  login: willmitchell777
  email: will.mitchell@gmail.com
  display_name: Will Mitchell
  first_name: ''
  last_name: ''
excerpt: !ruby/object:Hpricot::Doc
  options: {}
---


text:
<?php

namespace frontend\modules\student\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\TrainingClassSubjectTrainerEvaluation;

/**
 * TrainingClassSubjectTrainerEvaluationSearch represents the model behind the search form about `frontend\models\TrainingClassSubjectTrainerEvaluation`.
 */
class TrainingClassSubjectTrainerEvaluationSearch extends TrainingClassSubjectTrainerEvaluation
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'training_class_subject_id', 'trainer_id', 'student_id', 'status', 'created_by', 'modified_by'], 'integer'],
            [['value', 'comment', 'created', 'modified'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = TrainingClassSubjectTrainerEvaluation::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'training_class_subject_id' => $this->training_class_subject_id,
            'trainer_id' => $this->trainer_id,
            'student_id' => $this->student_id,
            'status' => $this->status,
            'created' => $this->created,
            'created_by' => $this->created_by,
            'modified' => $this->modified,
            'modified_by' => $this->modified_by,
        ]);

        $query->andFilterWhere(['like', 'value', $this->value])
            ->andFilterWhere(['like', 'comment', $this->comment]);

        return $dataProvider;
    }
}


text:
require "rails_helper"

describe UserInvitationsController, type: :controller do
  let(:acme) { organizations(:acme) }
  let(:foo_inc) { organizations(:foo_inc) }

  let(:root) { users(:root) }
  let(:acme_root) { users(:acme_root) }
  let(:acme_normal) { users(:acme_normal) }
  let(:foo_inc_root) { users(:foo_inc_root) }

  let(:acme_invite) { user_invitations(:acme_invite) }
  let(:acme_admin_invite) { user_invitations(:acme_admin_invite) }
  let(:expired_acme_invite) { user_invitations(:expired_acme_invite) }
  let(:foo_inc_invite) { user_invitations(:foo_inc_invite) }
  let(:foo_inc_admin_invite) { user_invitations(:foo_inc_admin_invite) }

  describe "GET new" do
    it "is not allowed for normal users" do
      expect do
        signed_in_user :acme_normal
        get :new
      end.to raise_error(PermissionError)
    end

    it "is allowed for admin users" do
      signed_in_user :acme_root
      get :new
      expect(response).to have_http_status(:success)
    end

    it "is allowed for super admin users" do
      signed_in_user :root
      get :new
      expect(response).to have_http_status(:success)
    end
  end

  describe "GET index" do
    it "is not allowed for normal users" do
      expect do
        signed_in_user :acme_normal
        get :index
      end.to raise_error(PermissionError)
    end

    it "shows all invites for super admin" do
      signed_in_user :root
      get :index
      expect(assigns(:invites)).to include(acme_invite, acme_admin_invite, foo_inc_invite, foo_inc_admin_invite)
    end

    it "shows invites that the user can invite to" do
      signed_in_user :acme_root
      get :index
      expect(assigns(:invites)).to include(acme_invite, acme_admin_invite)
      expect(assigns(:invites)).to_not include(foo_inc_invite, foo_inc_admin_invite)
    end
  end

  describe "POST create" do
    it "is not allowed for normal users" do
      expect do
        signed_in_user :acme_normal

        post :create, user: {
          organization_id: acme.id.to_s,
          name: "Foo Bar",
          email: "foobar@email.com",
          role: "none"
        }
      end.to raise_error(PermissionError)
    end

    it "is not allowed for admin users of another company" do
      expect do
        signed_in_user :foo_inc_root

        post :create, user: {
          organization_id: acme.id.to_s,
          name: "Foo Bar",
          email: "foobar@email.com",
          role: "none"
        }
      end.to raise_error(PermissionError)
    end

    it "creates an invite for admin user" do
      signed_in_user :acme_root
      expect(SecureRandom).to receive(:urlsafe_base64).and_return("secure_auth_key")

      post :create, user: {
        organization_id: acme.id.to_s,
        name: "Foo Bar",
        email: "foobar@email.com",
        role: "none"
      }

      invitation = UserInvitation.find_by_email("foobar@email.com")
      expect(invitation).to be
      expect(invitation.invited_by).to eq(acme_root)
      expect(invitation.organization).to eq(acme)
      expect(invitation.name).to eq("Foo Bar")
      expect(invitation.email).to eq("foobar@email.com")
      expect(invitation.role).to eq("none")
      expect(invitation.auth_token).to eq("secure_auth_key")
    end

    it "creates an invite for super admin user" do
      signed_in_user :root
      expect(SecureRandom).to receive(:urlsafe_base64).and_return("secure_auth_key")

      post :create, user: {
        organization_id: acme.id.to_s,
        name: "Foo Bar",
        email: "foobar@email.com",
        role: "admin"
      }

      invitation = UserInvitation.find_by_email("foobar@email.com")
      expect(invitation).to be
      expect(invitation.invited_by).to eq(root)
      expect(invitation.organization).to eq(acme)
      expect(invitation.name).to eq("Foo Bar")
      expect(invitation.email).to eq("foobar@email.com")
      expect(invitation.role).to eq("admin")
      expect(invitation.auth_token).to eq("secure_auth_key")
    end

    it "normalizes the email address like devise is configured to do" do
      signed_in_user :acme_root
      expect(SecureRandom).to receive(:urlsafe_base64).and_return("secure_auth_key")

      post :create, user: {
        organization_id: acme.id.to_s,
        name: "Foo Bar",
        email: "  FooBar@email.com   \t \n ",
        role: "admin"
      }

      invitation = UserInvitation.find_by_email("foobar@email.com")
      expect(invitation).to be
      expect(invitation.invited_by).to eq(acme_root)
      expect(invitation.organization).to eq(acme)
      expect(invitation.name).to eq("Foo Bar")
      expect(invitation.email).to eq("foobar@email.com")
      expect(invitation.role).to eq("admin")
      expect(invitation.auth_token).to eq("secure_auth_key")
    end

    it "sends an email invite" do
      signed_in_user :acme_root
      expect(SecureRandom).to receive(:urlsafe_base64).and_return("secure_auth_key")

      expect do
        post :create, user: {
          organization_id: acme.id.to_s,
          name: "Foo Bar",
          email: "foobar@email.com",
          role: "none"
        }
      end.to change { ActionMailer::Base.deliveries.count }.by(1)

      invitation = UserInvitation.find_by_email("foobar@email.com")
      expect(ActionMailer::Base.deliveries.last.to).to match_array("foobar@email.com")
      expect(ActionMailer::Base.deliveries.last.body.parts.last.to_s).to include("Foo Bar")
      expect(ActionMailer::Base.deliveries.last.body.parts.last.to_s).to include(acme_root.name)
      expect(ActionMailer::Base.deliveries.last.body.parts.last.to_s).to include(acme.name)
      expected_url = user_invitation_url(invitation, email: "foobar@email.com", auth_token: "secure_auth_key")
      expect(ActionMailer::Base.deliveries.last.body.parts.last.to_s).to include(ERB::Util.html_escape(expected_url))
    end

    it "immediately adds the user if they already exist" do
      expect(acme_normal.role_at(foo_inc)).to be_nil
      signed_in_user :foo_inc_root

      post :create, user: {
        organization_id: foo_inc.id.to_s,
        name: "Foo Bar",
        email: acme_normal.email,
        role: "none"
      }

      expect(UserInvitation.find_by_email(acme_normal.email)).to be_nil
      acme_normal.reload
      expect(acme_normal.name).to eq("Acme Normal") # It shouldn't change their name
      expect(acme_normal.role_at(foo_inc)).to eq("none")
    end

    it "sends an email notification when the user already exists" do
      expect(acme_normal.role_at(foo_inc)).to be_nil
      signed_in_user :foo_inc_root

      expect do
        post :create, user: {
          organization_id: foo_inc.id.to_s,
          name: "Foo Bar",
          email: acme_normal.email,
          role: "none"
        }
      end.to change { ActionMailer::Base.deliveries.count }.by(1)

      expect(ActionMailer::Base.deliveries.last.to).to match_array(acme_normal.email)
      expect(ActionMailer::Base.deliveries.last.body.parts.last.to_s).to include(acme_normal.name)
      expect(ActionMailer::Base.deliveries.last.body.parts.last.to_s).to include(foo_inc_root.name)
      expect(ActionMailer::Base.deliveries.last.body.parts.last.to_s).to include(foo_inc.name)
    end
  end

  describe "GET show" do
    it "fails with the wrong email" do
      no_user_signed_in
      invite = acme_invite

      expect do
        get :show,
            id: invite.id.to_s,
            auth_token: invite.auth_token,
            email: "faker-wrong@email.com"
      end.to raise_error(PermissionError)
    end

    it "fails with the wrong auth code" do
      no_user_signed_in
      invite = acme_invite

      expect do
        get :show,
            id: invite.id.to_s,
            auth_token: "fakerwrong123",
            email: invite.email
      end.to raise_error(PermissionError)
    end

    describe "with an expired invitation" do
      render_views

      it "gives a failure message without the form" do
        no_user_signed_in
        invite = expired_acme_invite

        get :show,
            id: invite.id.to_s,
            auth_token: invite.auth_token,
            email: invite.email

        expect(response.body).to include("invitation has expired")
        expect(response.body).to_not include("<form")
      end
    end
  end

  describe "PUT update" do
    it "fails with the wrong email" do
      no_user_signed_in
      invite = acme_invite

      expect do
        put :update,
            id: invite.id.to_s,
            auth_token: invite.auth_token,
            email: "faker-wrong@email.com",
            name: "Acme Invited",
            primary_number: "(408) 555-5123",
            password: "password123",
            password_confirmation: "password123"
      end.to raise_error(PermissionError)
    end

    it "fails with the wrong auth code" do
      no_user_signed_in
      invite = acme_invite

      expect do
        put :update,
            id: invite.id.to_s,
            auth_token: "fakerwrong123",
            email: invite.email,
            name: "Acme Invited",
            primary_number: "(408) 555-5123",
            password: "password123",
            password_confirmation: "password123"
      end.to raise_error(PermissionError)
    end

    it "fails with an expired invitation" do
      no_user_signed_in
      invite = expired_acme_invite

      expect do
        put :update,
            id: invite.id.to_s,
            auth_token: invite.auth_token,
            email: invite.email,
            name: "Acme Invited",
            primary_number: "(408) 555-5123",
            password: "password123",
            password_confirmation: "password123"
      end.to raise_error(PermissionError)
    end

    it "creates the user from the invite" do
      no_user_signed_in
      invite = acme_invite

      put :update,
          id: invite.id.to_s,
          auth_token: invite.auth_token,
          email: invite.email,
          name: "Acme Invited",
          primary_number: "(408) 555-5123",
          password: "password123",
          password_confirmation: "password123"

      user = User.find_by_email(invite.email)
      expect(user).to be
      expect(user.name).to eq("Acme Invited")
      expect(user.email).to eq(invite.email)
      expect(user.primary_number).to eq("(408) 555-5123")
      expect(user.role).to eq("none")
    end

    it "grants the user access to the desired organization" do
      no_user_signed_in
      invite = acme_invite

      put :update,
          id: invite.id.to_s,
          auth_token: invite.auth_token,
          email: invite.email,
          name: "Acme Invited",
          primary_number: "(408) 555-5123",
          password: "password123",
          password_confirmation: "password123"

      user = User.find_by_email(invite.email)
      expect(user.role_at(acme)).to eq("none")
      expect(user.role_at(foo_inc)).to be_nil
    end

    it "grants the user admin access to the desired organization if the desired role was as an admin" do
      no_user_signed_in
      invite = acme_admin_invite

      put :update,
          id: invite.id.to_s,
          auth_token: invite.auth_token,
          email: invite.email,
          name: "Acme Invited",
          primary_number: "(408) 555-5123",
          password: "password123",
          password_confirmation: "password123"

      user = User.find_by_email(invite.email)
      expect(user.role_at(acme)).to eq("admin")
      expect(user.role_at(foo_inc)).to be_nil
    end

    it "invalidates all outstanding invitations to the same organization if successful" do
      no_user_signed_in
      invite = acme_invite
      expect(UserInvitation.with_email(invite.email).not_expired.size > 1).to be_truthy

      put :update,
          id: invite.id.to_s,
          auth_token: invite.auth_token,
          email: invite.email,
          name: "Acme Invited",
          primary_number: "(408) 555-5123",
          password: "password123",
          password_confirmation: "password123"

      expect(UserInvitation.with_email(invite.email).all?(&:expired?)).to be_truthy
    end

    it "automatically adds access to invitations from other organizations if successful" do
      no_user_signed_in
      invite = acme_invite
      foo_inc_root.user_invitations.create! name: acme_invite.name,
                                            email: acme_invite.email,
                                            role: "admin",
                                            organization: foo_inc

      put :update,
          id: invite.id.to_s,
          auth_token: invite.auth_token,
          email: invite.email,
          name: "Acme Invited",
          primary_number: "(408) 555-5123",
          password: "password123",
          password_confirmation: "password123"

      expect(UserInvitation.with_email(invite.email).all?(&:expired?)).to be_truthy
      user = User.find_by_email(invite.email)
      expect(user.role_at(acme)).to eq("none")
      expect(user.role_at(foo_inc)).to eq("admin")
      expect(user.organization_users.size).to eq(2)
    end
  end
end


text:
=======================
Removing a compute host
=======================

The `openstack-ansible-ops <https://git.openstack.org/cgit/openstack/openstack-ansible-ops>`_
repository contains a playbook for removing a compute host from an
OpenStack-Ansible (OSA) environment.
To remove a compute host, follow the below procedure.

.. note::

   This guide describes how to remove a compute node from an OSA environment
   completely. Perform these steps with caution, as the compute node will no
   longer be in service after the steps have been completed. This guide assumes
   that all data and instances have been properly migrated.

#. Disable all OpenStack services running on the compute node.
   This can include, but is not limited to, the ``nova-compute`` service
   and the neutron agent service.

   .. note::

     Ensure this step is performed first

  .. code-block:: console

     # Run these commands on the compute node to be removed
     # stop nova-compute
     # stop neutron-linuxbridge-agent

#. Clone the ``openstack-ansible-ops`` repository to your deployment host:

  .. code-block:: console

     $ git clone https://git.openstack.org/openstack/openstack-ansible-ops \
       /opt/openstack-ansible-ops

#. Run the ``remove_compute_node.yml`` Ansible playbook with the
   ``host_to_be_removed`` user variable set:

  .. code-block:: console

     $ cd /opt/openstack-ansible-ops/ansible_tools/playbooks
     openstack-ansible remove_compute_node.yml \
     -e host_to_be_removed="<name-of-compute-host>"

#. After the playbook completes, remove the compute node from the
   OpenStack-Ansible configuration file in
   ``/etc/openstack_deploy/openstack_user_config.yml``.


text:
package com.tazine.io.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.io.IOException;

/**
 * Created on 2017/11/19.
 * @author Frank
 */
public class TimeServer {

    public static void main(String[] args) {

    }

    private void bind(int port) throws IOException{

        // 配置服务端的 NIO 线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024);

            // 绑定端口,同步等待成功
            ChannelFuture channelFuture = bootstrap.bind(port).sync();

            // 等待服务端监听端口关闭
            channelFuture.channel().close().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

}


text:
package model.basetype;

import model.Item;

/**
 * Created by Kang on 7/7/2017.
 */
public class TwoHandMace extends Item {
}


text:
package com.orientechnologies.orient.distributed.impl.metadata;

import com.orientechnologies.orient.core.db.config.ONodeIdentity;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.distributed.OrientDBDistributed;
import com.orientechnologies.orient.distributed.impl.OClusterPositionAllocatorDatabase;
import com.orientechnologies.orient.distributed.impl.coordinator.OCoordinateMessagesFactory;
import com.orientechnologies.orient.distributed.impl.coordinator.ODistributedCoordinator;
import com.orientechnologies.orient.distributed.impl.coordinator.ODistributedExecutor;
import com.orientechnologies.orient.distributed.impl.coordinator.OSubmitContext;
import com.orientechnologies.orient.distributed.impl.coordinator.OSubmitContextImpl;
import com.orientechnologies.orient.distributed.impl.coordinator.lock.ODistributedLockManagerImpl;
import com.orientechnologies.orient.distributed.impl.log.OLogId;
import com.orientechnologies.orient.distributed.impl.log.OOperationLog;
import com.orientechnologies.orient.distributed.impl.log.OPersistentOperationalLogV1;
import java.util.Set;
import java.util.concurrent.Executors;

public class ODistributedContext {

  private ODistributedExecutor executor;
  private OSubmitContext submitContext;
  private ODistributedCoordinator coordinator;
  private OClusterPositionAllocatorDatabase allocator;
  private OrientDBDistributed context;
  private String databaseName;
  private OOperationLog opLog;

  public ODistributedContext(OStorage storage, OrientDBDistributed context) {
    this.context = context;
    this.databaseName = storage.getName();
    initOpLog();
    executor =
        new ODistributedExecutor(
            Executors.newSingleThreadExecutor(),
            opLog,
            context,
            context.getNetworkManager(),
            storage.getName());
    submitContext = new OSubmitContextImpl(context, storage.getName());
    coordinator = null;
  }

  private void initOpLog() {
    this.opLog =
        OPersistentOperationalLogV1.newInstance(
            databaseName, context, (x) -> OCoordinateMessagesFactory.createOperationRequest(x));
  }

  public ODistributedExecutor getExecutor() {
    return executor;
  }

  public OSubmitContext getSubmitContext() {
    return submitContext;
  }

  public synchronized ODistributedCoordinator getCoordinator() {
    return coordinator;
  }

  public synchronized void makeCoordinator(
      ONodeIdentity leader,
      String database,
      OLogId leaderLastValid,
      Set<ONodeIdentity> activeNodes) {
    if (coordinator == null) {
      // TODO: Make sure that this leader kind of sync with the leader valid oplog id
      allocator = new OClusterPositionAllocatorDatabase(context.getSharedContext(database));
      coordinator =
          new ODistributedCoordinator(
              Executors.newSingleThreadExecutor(),
              opLog,
              new ODistributedLockManagerImpl(),
              allocator,
              context.getNetworkManager(),
              databaseName);
      for (ONodeIdentity node : activeNodes) {
        coordinator.join(node);
      }
      submitContext.setCoordinator(context.getNodeIdentity());
    }
  }

  public synchronized void setExternalCoordinator(
      ONodeIdentity lockManager, OLogId leaderLastValid) {
    if (coordinator != null) {
      coordinator.close();
      coordinator = null;
      allocator = null;
    }
    submitContext.setCoordinator(lockManager);
    executor.notifyLastValidLog(lockManager, leaderLastValid);
  }

  public synchronized void close() {
    if (coordinator != null) {
      coordinator.close();
    }
    executor.close();
  }

  public synchronized void reload() {
    if (allocator != null) {
      allocator.reload();
    }
  }

  public synchronized void connected(ONodeIdentity nodeIdentity) {
    if (coordinator != null) {
      coordinator.join(nodeIdentity);
    }
  }

  public synchronized void disconnected(ONodeIdentity nodeIdentity) {
    if (coordinator != null) {
      coordinator.leave(nodeIdentity);
    }
  }

  public OOperationLog getOpLog() {
    return opLog;
  }
}


text:
<?php

namespace Page\Model;

use Application\Model\EntityModel as EntityModel;
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Role\GenericRole as Role;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;

class PageModel extends EntityModel
{
    protected $_title;

    protected $_alias;

    protected $_description;

    protected $_keywords;

    protected $_text;

    public function setAlias($alias)
    {
        $this->_alias = $alias;
        return $this;
    }

    public function getAlias()
    {
        return $this->_alias;
    }

    public function setDescription($description)
    {
        $this->_description = $description;
        return $this;
    }

    public function getDescription()
    {
        return $this->_description;
    }

    public function setKeywords($keywords)
    {
        $this->_keywords = $keywords;
        return $this;
    }

    public function getKeywords()
    {
        return $this->_keywords;
    }

    public function setText($text)
    {
        $this->_text = $text;
        return $this;
    }

    public function getText()
    {
        return $this->_text;
    }

    public function setTitle($title)
    {
        $this->_title = $title;
        return $this;
    }

    public function getTitle()
    {
        return $this->_title;
    }

    public function getInputFilter()
    {
        if (!$this->_inputFilter) {
            $inputFilter = new \Zend\InputFilter\InputFilter();
            $factory     = new \Zend\InputFilter\Factory();

            $inputFilter->add($factory->createInput(array(
                'name'     => 'id',
                'required' => false,
                'filters'  => array(
                ),
            )));

            $inputFilter->add($factory->createInput(array(
                'name'     => 'title',
                'required' => true,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                ),
            )));

            $inputFilter->add($factory->createInput(array(
                'name'     => 'alias',
                'required' => true,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                ),
            )));

            $inputFilter->add($factory->createInput(array(
                'name'     => 'description',
                'required' => false,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                ),
            )));

            $inputFilter->add($factory->createInput(array(
                'name'     => 'keywords',
                'required' => false,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                ),
            )));

            $inputFilter->add($factory->createInput(array(
                'name'     => 'text',
                'required' => true,
                'filters'  => array(
                ),
                'validators' => array(
                ),
            )));

            $this->_inputFilter = $inputFilter;
        }

        return $this->_inputFilter;
    }
}