text:
package com.google.android.exoplayer2.upstream;

import android.net.Uri;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.upstream.Loader.Loadable;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Util;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * A {@link Loadable} for objects that can be parsed from binary data using a {@link Parser}.
 *
 * @param <T> The type of the object being loaded.
 */
public final class ParsingLoadable<T> implements Loadable {

  /**
   * Parses an object from loaded data.
   */
  public interface Parser<T> {

    /**
     * Parses an object from a response.
     *
     * @param uri The source {@link Uri} of the response, after any redirection.
     * @param inputStream An {@link InputStream} from which the response data can be read.
     * @return The parsed object.
     * @throws ParserException If an error occurs parsing the data.
     * @throws IOException If an error occurs reading data from the stream.
     */
    T parse(Uri uri, InputStream inputStream) throws IOException;

  }

  /**
   * Loads a single parsable object.
   *
   * @param dataSource The {@link DataSource} through which the object should be read.
   * @param parser The {@link Parser} to parse the object from the response.
   * @param uri The {@link Uri} of the object to read.
   * @param type The type of the data. One of the {@link C}{@code DATA_TYPE_*} constants.
   * @return The parsed object
   * @throws IOException Thrown if there is an error while loading or parsing.
   */
  public static <T> T load(DataSource dataSource, Parser<? extends T> parser, Uri uri, int type)
      throws IOException {
    ParsingLoadable<T> loadable = new ParsingLoadable<>(dataSource, uri, type, parser);
    loadable.load();
    return Assertions.checkNotNull(loadable.getResult());
  }

  /**
   * Loads a single parsable object.
   *
   * @param dataSource The {@link DataSource} through which the object should be read.
   * @param parser The {@link Parser} to parse the object from the response.
   * @param dataSpec The {@link DataSpec} of the object to read.
   * @param type The type of the data. One of the {@link C}{@code DATA_TYPE_*} constants.
   * @return The parsed object
   * @throws IOException Thrown if there is an error while loading or parsing.
   */
  public static <T> T load(
      DataSource dataSource, Parser<? extends T> parser, DataSpec dataSpec, int type)
      throws IOException {
    ParsingLoadable<T> loadable = new ParsingLoadable<>(dataSource, dataSpec, type, parser);
    loadable.load();
    return Assertions.checkNotNull(loadable.getResult());
  }

  /**
   * The {@link DataSpec} that defines the data to be loaded.
   */
  public final DataSpec dataSpec;
  /**
   * The type of the data. One of the {@code DATA_TYPE_*} constants defined in {@link C}. For
   * reporting only.
   */
  public final int type;

  private final StatsDataSource dataSource;
  private final Parser<? extends T> parser;

  private volatile @Nullable T result;

  /**
   * @param dataSource A {@link DataSource} to use when loading the data.
   * @param uri The {@link Uri} from which the object should be loaded.
   * @param type See {@link #type}.
   * @param parser Parses the object from the response.
   */
  public ParsingLoadable(DataSource dataSource, Uri uri, int type, Parser<? extends T> parser) {
    this(dataSource, new DataSpec(uri, DataSpec.FLAG_ALLOW_GZIP), type, parser);
  }

  /**
   * @param dataSource A {@link DataSource} to use when loading the data.
   * @param dataSpec The {@link DataSpec} from which the object should be loaded.
   * @param type See {@link #type}.
   * @param parser Parses the object from the response.
   */
  public ParsingLoadable(DataSource dataSource, DataSpec dataSpec, int type,
      Parser<? extends T> parser) {
    this.dataSource = new StatsDataSource(dataSource);
    this.dataSpec = dataSpec;
    this.type = type;
    this.parser = parser;
  }

  /** Returns the loaded object, or null if an object has not been loaded. */
  public final @Nullable T getResult() {
    return result;
  }

  /**
   * Returns the number of bytes loaded. In the case that the network response was compressed, the
   * value returned is the size of the data after decompression. Must only be called after
   * the load completed, failed, or was canceled.
   */
  public long bytesLoaded() {
    return dataSource.getBytesRead();
  }

  /**
   * Returns the {@link Uri} from which data was read. If redirection occurred, this is the
   * redirected uri. Must only be called after the load completed, failed, or was canceled.
   */
  public Uri getUri() {
    return dataSource.getLastOpenedUri();
  }

  /**
   * Returns the response headers associated with the load. Must only be called after the load
   * completed, failed, or was canceled.
   */
  public Map<String, List<String>> getResponseHeaders() {
    return dataSource.getLastResponseHeaders();
  }

  @Override
  public final void cancelLoad() {
    // Do nothing.
  }

  @Override
  public final void load() throws IOException {
    // We always load from the beginning, so reset bytesRead to 0.
    dataSource.resetBytesRead();
    DataSourceInputStream inputStream = new DataSourceInputStream(dataSource, dataSpec);
    try {
      inputStream.open();
      Uri dataSourceUri = Assertions.checkNotNull(dataSource.getUri());
      result = parser.parse(dataSourceUri, inputStream);
    } finally {
      Util.closeQuietly(inputStream);
    }
  }
}


text:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User

class RegisterForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['email', 'first_name', 'last_name']

    def save(self, commit=True):
        user = super().save(False)

        # username and email are the same in this scheme. Enforce it!
        user.username = user.email

        if commit:
            user.save()
        return user

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8" ?>
<languages>

  <language name="Italiano" id="it">

    <groups>
      <basicelements>Elementi Base</basicelements>
    </groups>

    <enums>
      <episerver>
        <forms>
          <samples>
            <criteria>
              <submissionstatus>
                <hassubmitted>Ha inviato</hassubmitted>
                <hasnotsubmitted>Non ha inviato</hasnotsubmitted>
              </submissionstatus>

              <fieldvaluecomparecondition>
                <equals>uguale a</equals>
                <notequals>non uguale a</notequals>
                <contains>contiene</contains>
                <notcontains>non contiene</notcontains>
              </fieldvaluecomparecondition>
            </criteria>
          </samples>
        </forms>
      </episerver>
    </enums>

    <episerver>
      <forms>
        <samples>
          <criteria>
            <formcriterion>
              <category>Moduli Episerver</category>
              <displayname>Modulo inviato</displayname>
              <description>Verifiche per l'invio del modulo da parte del visitatore.</description>
              <submissionstatus>Stato di invio</submissionstatus>
              <selectedform>Modulo selezionato</selectedform>
            </formcriterion>

            <submittedvaluecriterion>
              <category>Moduli Episerver</category>
              <displayname>Valore modulo inviato</displayname>
              <description>Verifiche per l'invio valore del modulo da parte del visitatore.</description>
              <selectedform>Modulo selezionato</selectedform>
              <selectedfield>Campo selezionato</selectedfield>
              <condition>Condizione</condition>
              <value>Valore</value>
            </submittedvaluecriterion>
          </criteria>

          <datetimepickertype>
            <datepicker>Selezione data</datepicker>
            <timepicker>Selezione ora</timepicker>
            <datetimepicker>Selezione data/ora</datetimepicker>
          </datetimepickertype>

          <confirmationdialog>
            <title>Sommario</title>
            <buttons>
              <ok>OK</ok>
              <cancel>Annulla</cancel>
            </buttons>
          </confirmationdialog>

          <editview>
            <requirejs>Per visualizzare reCAPTCHA è necessario JavaScript.</requirejs>
          </editview>
          <messages>
            <imagesubmitbutton>
              <initializationmessage>Questo è un pulsante di invio immagine. Seleziona un'immagine per questo.</initializationmessage>
            </imagesubmitbutton>
          </messages>
        </samples>
        <viewmode>
          <addresselement>
            <addresslabel>Indirizzo</addresslabel>
            <streetlabel>Via</streetlabel>
            <citylabel>Città</citylabel>
            <statelabel>Stato</statelabel>
            <postallabel>Codice postale</postallabel>
            <countrylabel>Paese</countrylabel>
          </addresselement>
        </viewmode>
        <validators>
          <episerver.forms.samples.implementation.validation.datetimevalidator>
            <displayname>Validatore data/ora</displayname>
            <message>Inserisce una data/ora corretta nel {0} formato hh:mm.</message>
          </episerver.forms.samples.implementation.validation.datetimevalidator>
          <episerver.forms.samples.implementation.validation.datevalidator>
            <displayname>Validatore data</displayname>
            <message>Inserisci una data corretta nel formato {0}.</message>
          </episerver.forms.samples.implementation.validation.datevalidator>
          <episerver.forms.samples.implementation.validation.timevalidator>
            <displayname>Validatore ora</displayname>
            <message>Inserisci un'ora corretta, ad es. 10:20 AM.</message>
          </episerver.forms.samples.implementation.validation.timevalidator>
          <episerver.forms.samples.implementation.validation.recaptchavalidator>
            <displayname>Validatore Recaptcha</displayname>
            <message>Valore captcha non valido.</message>
          </episerver.forms.samples.implementation.validation.recaptchavalidator>
          <episerver.forms.implementation.validation.datetimerangevalidator>
            <displayname>Intervallo di date</displayname>
            <message>Inserisci un intervallo di date valido.</message>
          </episerver.forms.implementation.validation.datetimerangevalidator>
          <episerver.forms.implementation.validation.addressvalidator>
            <displayname>Indirizzo</displayname>
            <message>Inserisci un indirizzo valido.</message>
          </episerver.forms.implementation.validation.addressvalidator>
        </validators>
      </forms>
    </episerver>
    <contenttypes>
      <datetimeelementblock>
        <name>Data/ora</name>
        <description></description>
        <newitemdefaultname>Nuova data/ora</newitemdefaultname>
        <properties>

          <description>

Suggerimento

            <help>Visualizza come suggerimento o testo di aiuto di un elemento.</help>
          </description>

          <pickertype>

Tipo di raccoglitore

            <help>Seleziona il tipo di selettore  per la proprietà.</help>
          </pickertype>
        </properties>
      </datetimeelementblock>
      <recaptchaelementblock>
        <name>reCAPTCHA</name>
        <description></description>
        <newitemdefaultname>Nuovo reCAPTCHA</newitemdefaultname>
        <properties>
          <sitekey>

Chiave sito

            <help>Inserisci la chiave per reCAPTCHA.</help>
          </sitekey>
          <secretkey>

Chiave segreta

            <help>La chiave condivisa tra il tuo sito e reCAPTCHA.</help>
          </secretkey>
        </properties>
      </recaptchaelementblock>
      <datetimerangeelementblock>
        <name>Intervallo di date</name>
        <description></description>
        <newitemdefaultname>Nuovo intervallo di date</newitemdefaultname>
        <start>Avvia</start>
        <end>Finisci</end>
        <properties>

          <description>

Suggerimento

            <help>Visualizza come suggerimento o testo di aiuto di un elemento.</help>
          </description>

          <pickertype>

Tipo di raccoglitore

            <help>Seleziona il tipo di raccoglitore per la proprietà.</help>
          </pickertype>
        </properties>
      </datetimerangeelementblock>
      <addresseselementblock>
        <name>Indirizzo</name>
        <description></description>
        <newitemdefaultname>Nuovo indirizzo</newitemdefaultname>
        <properties>

          <description>

Suggerimento

            <help>Visualizza come suggerimento o testo di aiuto di un elemento.</help>
          </description>

          <mapwidth>

Ampiezza della mappa

            <help>Ampiezza della mappa associata all'elemento.</help>
          </mapwidth>
          <mapheight>

Altezza della mappa

            <help>Altezza della mappa associata all'elemento.</help>
          </mapheight>
          <addresslabel>

Dettagli dell'indirizzo

            <help></help>
          </addresslabel>
          <streetlabel>

Etichetta della via

            <help></help>
          </streetlabel>
          <citylabel>

Etichetta della città

            <help></help>
          </citylabel>
          <statelabel>

Etichetta dello stato

            <help></help>
          </statelabel>
          <postalLabel>

Etichetta del codice postale

            <help></help>
          </postalLabel>
          <countrylabel>

Etichetta del paese

            <help></help>
          </countrylabel>
        </properties>
      </addresseselementblock>
    </contenttypes>
  </language>
</languages>


text:
<?php

class TestOfArrayFirst extends UnitTestCase {

	function test_first_by_index () {
		$this->assertTrue(array_first(array('foo', 'bar')) === 'foo');
	}

	function test_first_by_numeric_key () {
		$this->assertTrue(array_first(array(2 => 'foo', 90 => 'bar')) === 'foo');
	}

	function test_first_by_string_key () {
		$this->assertTrue(array_first(array('pfft' => 'foo', 'esa' => 'bar')) === 'foo');
	}

}

?>


text:
<?php

namespace Spl;

/**
 * HashingMediator enforces that a specific instance of a listener can only be
 * attached to the same event once, minus an edge case or two that are not
 * worth fussing over.
 */
class HashingMediator implements Mediator {

    protected $events = array();

    /**
     * @param string $event
     * @param callable $callable
     *
     * @throws TypeException if $callable is not callable.
     * @return void
     */
    public function addListener($event, $callable) {
        if (!is_callable($callable)) {
            throw new TypeException();
        }
        $this->events[$event][$this->hash($callable)] = $callable;
    }

    /**
     * @param string $event
     * @param callable $callable
     *
     * @return void
     */
    public function removeListener($event, $callable) {
        if (!is_callable($callable)) {
            return; // no harm in removing something that does not exist
        }
        unset($this->events[$event][$this->hash($callable)]);
    }

    protected function hash($callable) {
        if (is_string($callable)) {
            return $callable;
        }
        if (is_array($callable)) {
            if (is_object($callable[0])) {
                return spl_object_hash($callable[0]) . $callable[1];
            }
            return "{$callable[0]}::{$callable[1]}";
        }
        return spl_object_hash($callable);
    }

    /**
     * @param string $event
     *
     * @return void
     */
    public function removeListenersForEvent($event) {
        $this->events[$event] = array();
    }

    /**
     * @return void
     */
    public function removeAllListeners() {
        $this->events = array();
    }

    /**
     * @param $event
     *
     * @return void
     */
    public function notify($event) {
        if (empty($this->events[$event])) {
            return;
        }

        $args = func_get_args();
        array_shift($args);

        foreach ($this->events[$event] as $listener) {
            call_user_func_array($listener, $args);
        }
    }

}


text:
#include "CCControlSwitchTest.h"

CCControlSwitchTest::~CCControlSwitchTest()
{
    CC_SAFE_RELEASE(m_pDisplayValueLabel);
}

bool CCControlSwitchTest::init()
{
    if (CCControlScene::init())
    {
        CCSize screenSize = CCDirector::sharedDirector()->getWinSize();

        CCNode *layer = CCNode::create();
        layer->setPosition(ccp (screenSize.width / 2, screenSize.height / 2));
        addChild(layer, 1);

        double layer_width = 0;

        // Add the black background for the text
        CCScale9Sprite *background = CCScale9Sprite::create("extensions/buttonBackground.png");
        background->setContentSize(CCSizeMake(80, 50));
        background->setPosition(ccp(layer_width + background->getContentSize().width / 2.0f, 0));
        layer->addChild(background);

        layer_width += background->getContentSize().width;

        m_pDisplayValueLabel  = CCLabelTTF::create("#color" ,"Marker Felt" ,30);
        m_pDisplayValueLabel->retain();

        m_pDisplayValueLabel->setPosition(background->getPosition());
        layer->addChild(m_pDisplayValueLabel);

        // Create the switch
        CCControlSwitch *switchControl = CCControlSwitch::create
            (
                CCSprite::create("extensions/switch-mask.png"),
                CCSprite::create("extensions/switch-on.png"),
                CCSprite::create("extensions/switch-off.png"),
                CCSprite::create("extensions/switch-thumb.png"),
                CCLabelTTF::create("On", "Arial-BoldMT", 16),
                CCLabelTTF::create("Off", "Arial-BoldMT", 16)
            );
        switchControl->setPosition(ccp (layer_width + 10 + switchControl->getContentSize().width / 2, 0));
        layer->addChild(switchControl);

        switchControl->addTargetWithActionForControlEvents(this, cccontrol_selector(CCControlSwitchTest::valueChanged), CCControlEventValueChanged);

        // Set the layer size
        layer->setContentSize(CCSizeMake(layer_width, 0));
        layer->setAnchorPoint(ccp (0.5f, 0.5f));

        // Update the value label
        valueChanged(switchControl, CCControlEventValueChanged);
        return true;
    }
    return false;
}

void CCControlSwitchTest::valueChanged(CCObject* sender, CCControlEvent controlEvent)
{
    CCControlSwitch* pSwitch = (CCControlSwitch*)sender;
    if (pSwitch->isOn())
    {
        m_pDisplayValueLabel->setString("On");
    }
    else
    {
        m_pDisplayValueLabel->setString("Off");
    }
}


text:
package Clownfish::CFC::Binding::Perl::Method;
use Clownfish::CFC;
our $VERSION = '0.005000';
$VERSION = eval $VERSION;

1;


text:
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0" android:toXDelta="20"
    android:duration="1000"
    android:interpolator="@anim/cycle_interpolator" />


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Fusisporium atrovirens Berk., 1836

### Remarks
null


text:
---
id: solid
title: SolidJS
---

[SolidJS](https://www.solidjs.com/) is a framework to build user interfaces with simple and performant reactivity. You can test SolidJS components directly in a real browser using WebdriverIO and its [browser runner](/docs/runner#browser-runner).

## Setup

To setup WebdriverIO within your SolidJS project, follow the [instructions](/docs/component-testing#set-up) in our component testing docs. Make sure to select `solid` as preset within your runner options, e.g.:

```js
// wdio.conf.js
export const config = {
    // ...
    runner: ['browser', {
        preset: 'solid'
    }],
    // ...
}
```

:::info

If you are already using [Vite](https://vitejs.dev/) as development server you can also just re-use your configuration in `vite.config.ts` within your WebdriverIO config. For more information, see `viteConfig` in [runner options](/docs/runner#runner-options).

:::

The SolidJS preset requires `vite-plugin-solid` to be installed:

```sh npm2yarn
npm install --save-dev vite-plugin-solid
```

You can then start the tests by running:

```sh
npx wdio run ./wdio.conf.js
```

## Writing Tests

Given you have the following SolidJS component:

```html title="./components/Component.tsx"
import { createSignal } from 'solid-js'

function App() {
    const [theme, setTheme] = createSignal('light')

    const toggleTheme = () => {
        const nextTheme = theme() === 'light' ? 'dark' : 'light'
        setTheme(nextTheme)
    }

    return <button onClick={toggleTheme}>
        Current theme: {theme()}
    </button>
}

export default App
```

In your test use the `render` method from `solid-js/web` to attach the component to the test page. To interact with the component we recommend to use WebdriverIO commands as they behave more close to actual user interactions, e.g.:

```ts title="app.test.tsx"
import { expect } from '@wdio/globals'
import { render } from 'solid-js/web'

import App from './components/Component.jsx'

describe('React Component Testing', () => {
    /**
     * ensure we render the component for every test in a
     * new root container
     */
    let root: Element
    beforeEach(() => {
        if (root) {
            root.remove()
        }

        root = document.createElement('div')
        document.body.appendChild(root)
    })

    it('Test theme button toggle', async () => {
        render(<App />, root)
        const buttonEl = await $('button')

        await buttonEl.click()
        expect(buttonEl).toContainHTML('dark')
    })
})
```

You can find a full example of a WebdriverIO component test suite for SolidJS in our [example repository](https://github.com/webdriverio/component-testing-examples/tree/main/solidjs-typescript-vite).


text:
<?php

    /**
     * Class SModel
     * Модель
     *
     * @property-read string|null $default_name Дефолтное имя
     * @property-read string|null $default_url  Дефолтная ссылка
     * @property      array       $attributes
     */
    abstract class SModel {
        const HAS_MANY = 0;
        const BELONGS_TO = 1;
        const MANY_TO_MANY = 2;

        protected $_scenario;

        protected $_errors = [];

        /**
         * @var SModel[][] $_relations Коллекция реляционных объектов для этого конкретного объекта
         */
        protected $_relations = [];

        /**
         * @var string[][]|integer[][] Коллекция примарных ключей для реляционных объектов для этого конкретного объекта
         */
        protected $_is_relations_static = [];

        /**
         * @var SModel[][] Коллекция реляционных объектов для статики
         */
        protected static $_relations_static_collection = [];

        /**
         * @var string[] Список релляций, которые были загружены для этого объекта
         */
        protected $_relations_loaded = [];

        /**
         * @var array $_attributes
         */
        protected $_attributes = [];

        function __construct($scenario = 'default') {
            $this->setScenario($scenario);
            foreach (array_keys(static::relations()) as $relation_name) {
                $this->_is_relations_static[$relation_name] = [];
            }
        }

        /**
         * @param string $new_scenario
         */
        function setScenario($new_scenario) {
            $this->_scenario = $new_scenario;
        }

        /**
         * @return string
         */
        function getScenario() {
            return $this->_scenario;
        }

        /**
         * Метод со список атрибутов для переопределения через IOC
         *
         * @return array[]
         */
        static function get_attributes_list_overload() {
            return [];
        }

        /**
         * Получаем список атрибутов, их имён и типов
         *
         * @return array[]
         */
        static function get_attributes_list() {
            return static::get_attributes_list_overload();
        }

        /**
         * Примарный ключ
         *
         * @return string|string[]|null
         */
        static function getPrimary_key() {
            return 'id';
        }

        /**
         * Получаем тип атрибута из общего списка атрибутов, но не из правил
         *
         * @param string $name
         *
         * @return string
         */
        static function get_attribute_type($name) {
            $list = static::get_attributes_list();
            if (isset($list[$name]) and array_key_exists('type', $list[$name])) {
                return strtolower($list[$name]['type']);
            }

            return 'mixed';
        }

        /**
         * Получаем тип атрибута из общего списка атрибутов, но не из правил
         *
         * @param string $name
         *
         * @return string|null
         */
        static function get_attribute_additional_type($name) {
            $list = static::get_attributes_list();
            if (array_key_exists($name, $list) and
                array_key_exists('additional_type', $list[$name]) and ($list[$name]['additional_type'] != null)
            ) {
                return strtolower($list[$name]['additional_type']);
            }

            return null;
        }

        /**
         * Название поля
         *
         * @param string $name
         *
         * @return string|null
         */
        static function get_attribute_name($name) {
            $list = static::get_attributes_list();
            if (isset($list[$name], $list[$name]['name'])) {
                return $list[$name]['name'];
            }

            return self::get_default_name($name);
        }

        /**
         * @param string $name
         *
         * @return string
         */
        static function get_default_name($name) {
            $raw_list = explode("_", $name);
            foreach ($raw_list as &$item) {
                $item = mb_strtoupper(mb_substr($item, 0, 1)).mb_strtolower(mb_substr($item, 1));
            }

            return implode(' ', $raw_list);
        }

        /**
         * Настройки поля
         *
         * @param string $name
         *
         * @return array|null
         */
        static function get_attribute_setting($name) {
            $list = static::get_attributes_list();

            return array_key_exists($name, $list) ? $list[$name] : null;
        }

        /**
         * Санируем значение через описания поля. Для записи в поля или при чтении из полей
         *
         * @param string $name
         * @param mixed  $value
         *
         * @return mixed
         */
        static function sanation_value_type($name, $value) {
            /**
             * Санация значений
             */
            $need_type = static::get_attribute_type($name);
            $need_type_additional = static::get_attribute_additional_type($name);
            $value = self::convert_value_to_type($value, $need_type, $need_type_additional);

            return $value;
        }

        /**
         * @param mixed       $value
         * @param string      $need_type
         * @param string|null $additional_type
         *
         * @return mixed
         */
        static function convert_value_to_type($value, $need_type, $additional_type = null) {
            if ($need_type == 'mixed') {
                // Ничего не надо
            } elseif (preg_match('_^(.+?)(\\|null)_', $need_type, $a)) {
                $need_type = $a[1];
                if ($need_type == 'integer') {
                    $value = ($value !== null) ? (is_object($value) ? 0 : (int) $value) : null;
                } elseif ($need_type == 'string') {
                    $value = ($value !== null) ? self::valueToString($value) : null;
                    if ($additional_type != null) {
                        $value = self::stringToAdditionalType($value, $additional_type, true);
                    }
                } elseif ($need_type == 'double') {
                    $value = ($value !== null) ? (is_object($value) ? 0 : (double) $value) : null;
                } elseif ($need_type == 'boolean') {
                    $value = ($value !== null) ? ($value ? true : false) : null;
                } elseif ($need_type == 'array') {
                    if (is_object($value)) {
                        $value = (array) $value;
                    }
                } elseif ($need_type == 'object') {
                    if (is_array($value)) {
                        $value = (object) $value;
                    }
                }
            } elseif ($need_type == 'integer') {
                $value = is_object($value) ? 0 : (int) $value;
            } elseif ($need_type == 'string') {
                $value = self::valueToString($value);
                if ($additional_type != null) {
                    $value = self::stringToAdditionalType($value, $additional_type, false);
                }
            } elseif ($need_type == 'double') {
                $value = is_object($value) ? 0 : (double) $value;
            } elseif ($need_type == 'boolean') {
                $value = ($value ? true : false);
            } elseif ($need_type == 'array') {
                if (is_object($value)) {
                    $value = (array) $value;
                }
            } elseif ($need_type == 'object') {
                if (is_array($value)) {
                    $value = (object) $value;
                }
            }

            return $value;
        }

        /**
         * Берём значение функции или атрибута, санируя его
         *
         * @param string $name
         *
         * @return mixed
         * @throws SModelException
         */
        function __get($name) {
            $getter_function = 'get'.$name;
            $value = null;
            if (method_exists($this, $getter_function)) {
                $value = $this->$getter_function();
            } elseif (array_key_exists($name, $this->get_attributes_list())) {
                return $this->get_attribute($name);
            } elseif (preg_match('|^_relation_([0-9a-z_]+)$|i', $name, $a) and isset(static::relations()[$a[1]])) {
                return static::get_relation($a[1]);
            } elseif (method_exists($this, 'set'.$name)) {
                throw new SModelException('Cannot read write-only property '.get_class($this).'::'.$name, E_ERROR);
            }

            return self::sanation_value_type($name, $value);
        }

        /**
         * Выставляем значение функции, без санации данных
         *
         * @param string $name
         * @param mixed  $value
         *
         * @throws SModelException
         */
        function __set($name, $value) {
            if (!$this->is_attribute_writable($name)) {
                return;
            }

            $setter_function = 'set'.$name;
            if (method_exists($this, $setter_function)) {
                $this->$setter_function($value);
            } elseif (array_key_exists($name, $this->get_attributes_list())) {
                $this->set_attribute($name, $value);
            } elseif (method_exists($this, 'get'.$name)) {
                throw new SModelException('Cannot write read-only property '.get_class($this).'::'.$name, E_ERROR);
            }
        }

        /**
         * Isset для полей
         *
         * @param string $name
         *
         * @return boolean
         */
        function __isset($name) {
            if (method_exists($this, 'get'.$name)) {
                return true;
            } elseif (array_key_exists($name, $this->get_attributes_list())) {
                return true;
            } elseif (preg_match('|^_relation_([0-9a-z_]+)$|i', $name, $a) and isset(static::relations()[$a[1]])) {
                return true;
            }

            return false;
        }

        /**
         * Получаем значение атрибута
         *
         * @param string  $name
         * @param boolean $need_sanation Нужно санировать значение
         *
         * @return mixed
         */
        function get_attribute($name, $need_sanation = true) {
            if (!array_key_exists($name, $this->_attributes)) {
                return null;
            }

            return $need_sanation ? static::sanation_value_type($name, $this->_attributes[$name]) : $this->_attributes[$name];
        }

        /**
         * @param string  $name
         * @param mixed   $value
         * @param boolean $force         Пишем, не взирая на запрет записи
         * @param boolean $need_sanation Нужно санировать значение
         */
        function set_attribute($name, $value, $force = false, $need_sanation = true) {
            if (!$force and !$this->is_attribute_writable($name)) {
                return;
            }
            $this->_attributes[$name] = $need_sanation ? static::sanation_value_type($name, $value) : $value;
        }

        /**
         * @param string $name
         *
         * @return boolean
         */
        function has_attribute($name) {
            return array_key_exists($name, static::get_attributes_list());
        }

        /**
         * @param string $name
         *
         * @return boolean
         */
        function attribute_has_been_set($name) {
            return array_key_exists($name, $this->_attributes);
        }

        /**
         * Удаляем атрибут
         *
         * @param string $name
         */
        function unset_attribute($name) {
            if (array_key_exists($name, $this->_attributes)) {
                unset($this->_attributes[$name]);
            }
        }

        /**
         * @brief Дефолтное приведение к строке
         *
         * @return string|null
         */
        function getDefault_name() {
            return null;
        }

        /**
         * @brief Дефолтный URL для этого объекта
         *
         * @return string|null
         */
        function getDefault_url() {
            return null;
        }

        /**
         * @return string
         */
        function __toString() {
            return ''.$this->default_name;
        }

        /**
         * Получаем значения всех атрибутов
         *
         * @param string|null $origin
         *
         * @return mixed[]
         */
        function getAttributes($origin = null) {
            $list = static::get_attributes_list();
            $data = [];
            foreach ($list as $key => $value) {
                if (($origin !== null) and (!isset($value['origin']) or ($value['origin'] != $origin))) {
                    continue;
                }
                $data[$key] = $this->get_attribute($key);
            }

            return $data;
        }

        /**
         * Получаем названия всех атрибутов
         *
         * @param string|null $origin
         *
         * @return string[]
         */
        static function getAttributesKeys($origin = null) {
            $list = static::get_attributes_list();
            $keys = [];
            foreach ($list as $key => $value) {
                if (($origin !== null) and (!isset($value['origin']) or ($value['origin'] != $origin))) {
                    continue;
                }
                $keys[] = $key;
            }

            return $keys;
        }

        /**
         * Задаём значения всех атрибутов, которые были переданы
         *
         * @param mixed[] $values
         */
        function setAttributes($values) {
            $list = $this->getWritable_attributes();
            foreach ($values as $key => $value) {
                if (strtolower($key) === 'attributes') {
                    continue;
                }
                if (($list !== null) and !in_array($key, $list)) {
                    continue;
                }
                $this->__set($key, $value);
            }
        }

        /**
         * @return string[][]
         */
        function getErrors() {
            return $this->_errors;
        }

        /**
         * @return string
         */
        function getErrors_as_string() {
            $b = [];
            foreach ($this->_errors as $a) {
                $b[] = $a[1];
            }

            return implode('; ', $b);
        }

        /**
         * @param string $property
         * @param string $string
         */
        function addError($property, $string) {
            $this->_errors[] = [$property, $string];
        }

        /**
         * @brief Есть ли ошибки
         *
         * @return boolean
         */
        function hasErrors() {
            return count($this->_errors) > 0;
        }

        /**
         * Правила санации параметров при их SET
         *
         * @return array[]
         */
        static function sanation_rules() {
            return [];
        }

        /**
         * Список атрибутов, доступных для записи
         *
         * @return string[]|null
         */
        function getWritable_attributes() {
            if ($this->_scenario == 'default') {
                return null;
            }

            $raw_writable = [];
            $raw_non_writable = [];
            foreach (static::sanation_rules() as $rule) {
                $attributes = self::string_to_array($rule[0]);
                $scenarios = isset($rule['on']) ? self::string_to_array($rule['on']) : null;
                if (($scenarios !== null) and !in_array($this->_scenario, $scenarios)) {
                    continue;
                }
                $rule[1] = strtolower($rule[1]);

                if ($rule[1] == 'unsafe') {
                    foreach ($attributes as &$attribute_name) {
                        if (!in_array($attribute_name, $raw_writable) and !in_array($attribute_name, $raw_non_writable)) {
                            $raw_non_writable[] = $attribute_name;
                        }
                    }
                } else {
                    foreach ($attributes as &$attribute_name) {
                        if (!in_array($attribute_name, $raw_writable) and !in_array($attribute_name, $raw_non_writable)) {
                            $raw_writable[] = $attribute_name;
                        }
                    }
                }
            }
            $real_raw_writable = $raw_writable;
            foreach (array_keys(static::get_attributes_list()) as $key) {
                if (!in_array($key, $raw_non_writable)) {
                    $real_raw_writable[] = $key;
                }
            }

            return $real_raw_writable;
        }

        /**
         * @param string $name
         *
         * @return boolean
         */
        function is_attribute_writable($name) {
            if (in_array($name, ['attributes'])) {
                return true;
            }

            $writable_attribute_list = $this->getWritable_attributes();
            if (is_null($writable_attribute_list)) {
                return true;
            }
            foreach ($writable_attribute_list as &$key) {
                $key = strtolower($key);
            }

            return in_array(strtolower($name), $writable_attribute_list);
        }

        /**
         * @param string[]|string $value
         *
         * @return string[]
         */
        static function string_to_array($value) {
            if (is_array($value)) {
                return $value;
            } elseif (is_string($value)) {
                return preg_split('|[,\s]+|', trim($value));
            } else {
                return [];
            }
        }

        /**
         * Валидируем через правила санации
         *
         * @param string[]|null $need_test_attribute_list
         *
         * @return boolean
         */
        function validate($need_test_attribute_list = null) {
            $can_be_null_list = [];
            foreach (static::sanation_rules() as $rule) {
                if (isset($rule['on']) and !in_array($this->_scenario, self::string_to_array($rule['on']))) {
                    continue;
                }
                $rule[1] = strtolower($rule[1]);
                if (in_array($rule[1], ['can be null', 'can_be_null'])) {
                    $attributes = self::string_to_array($rule[0]);
                    foreach ($attributes as $attribute_name) {
                        $can_be_null_list[] = $attribute_name;
                    }
                }
            }
            $can_be_null_list = array_unique($can_be_null_list);
            $self_reflection = new ReflectionClass(static::class);

            foreach (static::sanation_rules() as $rule) {
                $attributes = self::string_to_array($rule[0]);
                if (isset($rule['on']) and !in_array($this->_scenario, self::string_to_array($rule['on']))) {
                    continue;
                }
                $rule[1] = strtolower($rule[1]);

                if ($rule[1] == 'required') {
                    foreach ($attributes as $attribute_name) {
                        if (!property_exists($this, $attribute_name) and !array_key_exists($attribute_name, $this->_attributes)) {
                            $this->addError($attribute_name,
                                'Property "'.self::get_attribute_name($attribute_name).'" has not been set');
                        }
                    }
                    continue;
                } elseif (in_array($rule[1], ['safe', 'unsafe'])) {
                    continue;
                }

                foreach ($attributes as $attribute_name) {
                    if (($need_test_attribute_list !== null) and !in_array($attribute_name, $need_test_attribute_list)) {
                        continue;
                    }
                    if ($this->validate_attribute_can_be_skip($attribute_name, $can_be_null_list)) {
                        continue;
                    }
                    $value = $this->{$attribute_name};
                    $errors = self::test_attribute_with_rule($rule, $attribute_name, $value, $self_reflection);
                    foreach ($errors as &$error) {
                        $this->addError($attribute_name, $error[1]);
                    }
                }
            }

            return !$this->hasErrors();
        }

        /**
         * @param array           $rule
         * @param string          $attribute_name
         * @param mixed           $value
         * @param ReflectionClass $reflection
         *
         * @return string[][]
         */
        protected static function test_attribute_with_rule($rule, $attribute_name, $value, $reflection) {
            $resolved_attribute_name = $reflection->getMethod('get_attribute_name')->invoke(null, $attribute_name);

            $return = [];
            if ($rule[1] == 'min') {
                if ($value < $rule['value']) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" is less than the minimum'];
                }
            } elseif ($rule[1] == 'max') {
                if ($value > $rule['value']) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" is more than the maximum'];
                }
            } elseif ($rule[1] == 'min_length') {
                if (mb_strlen($value) < $rule['value']) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" is shorter than the minimum length'];
                }
            } elseif ($rule[1] == 'max_length') {
                if (mb_strlen($value) > $rule['value']) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" is longer than the maximum length'];
                }
            } elseif (preg_match('_^\\s*(>|>=|=>|<|<=|=<|<>|!=|=|==)\\s*([0-9]+)\\s*$_', $rule[1], $a)) {
                switch ($a[1]) {
                    case '>=':
                    case '=>':
                        if ($value < $a[2]) {
                            $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" is less than the minimum'];
                        }
                        break;
                    case '<=':
                    case '=<':
                        if ($value > $a[2]) {
                            $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" is more than the maximum'];
                        }
                        break;
                    case '==':
                    case '=':
                        if ($value != $a[2]) {
                            $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" is not equal to constant'];
                        }
                        break;
                    case '<>':
                    case '!=':
                        if ($value == $a[2]) {
                            $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" is equal to illegal constant'];
                        }
                        break;
                    case '>':
                        if ($value <= $a[2]) {
                            $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" is less than the minimum'];
                        }
                        break;
                    case '<':
                        if ($value >= $a[2]) {
                            $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" is more than the maximum'];
                        }
                        break;
                }
            } elseif (in_array($rule[1], ['in dictionary', 'in_dictionary'])) {
                $values = array_key_exists('values', $rule)
                    ? $rule['values']
                    : array_keys($reflection->getStaticPropertyValue($attribute_name.'_dictionary'));

                if (!in_array($value, $values)) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" does not contain legal value'];
                }
            } elseif ($rule[1] == 'in') {
                if (!in_array($value, $rule['value'])) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" does not contain legal value'];
                }
            } elseif (in_array($rule[1], ['not in', 'not_in'])) {
                if (in_array($value, $rule['value'])) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" contains illegal value'];
                }
            } elseif ($rule[1] == 'regexp') {
                if (!preg_match($rule['value'], $value)) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" does not match with the mask'];
                }
            } elseif (in_array($rule[1], ['not regexp', 'not_regexp'])) {
                if (preg_match($rule['value'], $value)) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" matches with illegal mask'];
                }
            } elseif ($rule[1] == 'between') {
                if (($value < $rule['value'][0]) or ($value > $rule['value'][1])) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" out of range'];
                }
            } elseif (in_array($rule[1], ['not between', 'not_between'])) {
                if (($value >= $rule['value'][0]) and ($value <= $rule['value'][1])) {
                    $return[] = [$rule[1], 'Property "'.$resolved_attribute_name.'" out of range'];
                }
            }

            // @todo Дописать. email, url

            return $return;
        }

        /**
         * Валидируем через правила санации
         *
         * @param string[]|null $need_test_attribute_list
         *
         * @return boolean
         */
        function full_validate($need_test_attribute_list = null) {
            if (!$this->before_validate()) {
                return false;
            } elseif (!$this->validate($need_test_attribute_list)) {
                return false;
            } elseif (!$this->after_validate()) {
                return false;
            } else {
                return true;
            }
        }

        /**
         * @param string   $attribute_name
         * @param string[] $can_be_null_list
         *
         * @return boolean
         */
        protected function validate_attribute_can_be_skip($attribute_name, $can_be_null_list) {
            $value = $this->{$attribute_name};
            if (($value === null) and in_array($attribute_name, $can_be_null_list)) {
                return true;
            }

            return false;
        }

        /**
         * Выставляем все property и атрибуты
         */
        function sanation_set_default_and_empty() {
            foreach (static::sanation_rules() as $rule) {
                $attributes = self::string_to_array($rule[0]);
                if (isset($rule['on']) and !in_array($this->_scenario, self::string_to_array($rule['on']))) {
                    continue;
                }
                $rule[1] = strtolower($rule[1]);

                if ($rule[1] == 'default') {
                    foreach ($attributes as $attribute_name) {
                        $value = $this->{$attribute_name};
                        if (is_object($value) and (get_class($value) == 'SDBExpression')) {
                            continue;
                        }
                        // @hint Здесь специально не is_empty
                        if (isset($rule['setOnEmpty']) and (($value === null) or ($value === ''))) {
                            $this->{$attribute_name} = $rule['value'];
                        } elseif (isset($rule['setOnZero']) and ($value === 0)) {
                            $this->{$attribute_name} = $rule['value'];
                        }
                    }
                    continue;
                }
            }
        }

        /**
         * Правильное название типа
         *
         * @param string $type
         *
         * @return string
         */
        static function get_real_type_name($type) {
            switch (strtolower($type)) {
                case 'int':
                case 'integer':
                case 'number':
                case 'numeric':
                case 'numerical':
                    return 'integer';

                case 'float':
                case 'double':
                    return 'double';

                case 'string':
                case 'text':
                    return 'string';

                default:
                    return strtolower($type);
            }
        }

        /**
         * Функция-заглушка, вызывающаяся перед validate
         *
         * @return boolean
         */
        function before_validate() {
            $this->sanation_set_default_and_empty();

            return true;
        }

        /**
         * Функция-заглушка, вызывающаяся после validate
         *
         * @return boolean
         */
        function after_validate() {
            return true;
        }

        /**
         * Значение любого типа превращаем в строку
         *
         * @param mixed $instance
         *
         * @return string|null
         */
        static function valueToString($instance) {
            if (is_object($instance)) {
                return method_exists($instance, '__toString') ? $instance->__toString() : get_class($instance);
            } elseif (is_bool($instance)) {
                return $instance ? 'true' : 'false';
            } elseif (is_array($instance)) {
                return 'array['.count($instance).']';
            } elseif ($instance === null) {
                return '';
            } else {
                return strval($instance);
            }
        }

        /**
         * Дефолтные значения для разных типов
         *
         * @param string $additional_type
         *
         * @return string
         */
        static function get_default_value_for_additional_type($additional_type) {
            switch ($additional_type) {
                case 'date':
                    return '0000-00-00';
                case 'datetime':
                    return '0000-00-00 00:00:00';
                default:
                    return '';
            }
        }

        /**
         * @param string  $string
         * @param string  $additional_type
         * @param boolean $can_be_null
         *
         * @return string
         */
        static function stringToAdditionalType($string, $additional_type, $can_be_null = true) {
            switch ($additional_type) {
                case 'date':
                    if ($string == '') {
                        return $can_be_null ? null : self::get_default_value_for_additional_type('date');
                    } elseif ($string == '0000-00-00') {
                        return '0000-00-00';
                    }
                    try {
                        $date = new DateTime($string);
                    } catch (Exception $e) {
                        return $can_be_null ? null : self::get_default_value_for_additional_type('date');
                    }

                    return $date->format('Y-m-d');
                case 'datetime':
                    if ($string == '') {
                        return $can_be_null ? null : self::get_default_value_for_additional_type('date');
                    } elseif ($string == '0000-00-00 00:00:00') {
                        return '0000-00-00 00:00:00';
                    }
                    try {
                        $date = new DateTime($string);
                    } catch (Exception $e) {
                        return $can_be_null ? null : self::get_default_value_for_additional_type('datetime');
                    }

                    return $date->format('Y-m-d H:i:s');
            }

            return $string;
        }

        /**
         * @param mixed[]     $fields
         * @param string      $key_prefix
         * @param string|null $scenario
         * @param boolean     $need_trim
         */
        function set_values_from_raw_fields($fields, $key_prefix = '', $scenario = null, $need_trim = false) {
            if ($scenario !== null) {
                $old_scenario = $this->getScenario();
                $this->setScenario($scenario);
            }
            $prefix_length = mb_strlen($key_prefix);
            foreach ($fields as $key => $value) {
                if (mb_substr($key, 0, $prefix_length) == $key_prefix) {
                    $real_key = mb_substr($key, $prefix_length);
                    if (!$this->is_attribute_writable($real_key)) {
                        continue;
                    }
                    $this->set_attribute($real_key, $need_trim ? trim($value) : $value);
                }
            }

            if ($scenario !== null) {
                /** @noinspection PhpUndefinedVariableInspection */
                $this->setScenario($old_scenario);
            }
        }

        /**
         * @var object[]
         */
        protected $_date_input_list = [];
        /**
         * @var integer
         */
        protected $_search_offset = null;
        /**
         * @var integer|null $_search_limit
         */
        protected $_search_limit = null;
        /**
         * @var string|null $_search_order
         */
        protected $_search_order = null;

        /**
         * Установка полей для поиска
         *
         * @param mixed[]           $fields
         * @param string            $key_prefix
         * @param DateTimeZone|null $timezone
         */
        function set_search($fields, $key_prefix, $timezone = null) {
            $old_scenario = $this->getScenario();
            $this->setScenario('search');
            if ($timezone === null) {
                $timezone = new DateTimeZone(date_default_timezone_get());
            }

            $prefix_length = mb_strlen($key_prefix);
            $page_size = null;
            $page_number = null;
            foreach ($fields as $key => $value) {
                if (mb_substr($key, 0, $prefix_length) != $key_prefix) {
                    continue;
                }
                if (mb_substr($key, $prefix_length, 6) == 'value_') {
                    $value_type = 1;
                    $real_key = mb_substr($key, $prefix_length + 6);
                } elseif (mb_substr($key, $prefix_length, 4) == 'min_') {
                    $value_type = 2;
                    $real_key = mb_substr($key, $prefix_length + 4);
                } elseif (mb_substr($key, $prefix_length, 4) == 'max_') {
                    $value_type = 3;
                    $real_key = mb_substr($key, $prefix_length + 4);
                } elseif (mb_substr($key, $prefix_length, 5) == 'limit') {
                    $this->set_search_limit($value);
                    continue;
                } elseif (mb_substr($key, $prefix_length, 6) == 'offset') {
                    $this->set_search_offset($value);
                    continue;
                } elseif (mb_substr($key, $prefix_length, 5) == 'order') {
                    $this->set_search_order($value);
                    continue;
                } else {
                    continue;
                }

                if (!$this->is_attribute_writable($real_key) or ($value === '')) {
                    continue;
                }
                // @todo Проверяем, что это виртуальное поле, сделанное для поиска
                switch ($value_type) {
                    case 1:
                        $this->set_attribute($real_key, $value, false, false);
                        break;
                    case 2:
                    case 3:
                        $attribute_setting = static::get_attributes_list()[$real_key];
                        if (!in_array($attribute_setting['additional_type'], ['date', 'datetime', 'timestamp'])
                            and ($attribute_setting['type'] != 'integer')
                        ) {
                            // Так быть не должно
                            continue;
                        }

                        if (!array_key_exists($real_key, $this->_date_input_list)) {
                            $this->_date_input_list[$real_key] = (object) [
                                'min' => null,
                                'max' => null,
                            ];
                        }
                        if (($value === '') || ($value === null)) {
                            $this->_date_input_list[$real_key]->{($value_type == 2) ? 'min' : 'max'} = null;
                        } else {
                            $this->_date_input_list[$real_key]->{($value_type == 2) ? 'min' : 'max'} =
                                new DateTime($value, $timezone);
                        }
                        break;
                }
            }
            if (!is_null($page_size) or !is_null($page_number)) {
                if (is_null($page_size)) {
                    $page_size = 50;
                }
                if (is_null($page_number)) {
                    $page_number = 0;
                }
                $this->set_search_limit($page_size);
                $this->set_search_offset($page_size * $page_number);
            }

            $this->setScenario($old_scenario);
        }

        /**
         * @param string|null $value
         */
        function set_search_offset($value) {
            $this->_search_offset = ($value == '') ? null : (int) $value;
        }

        /**
         * @return integer|null
         */
        function get_search_offset() {
            return $this->_search_offset;
        }

        /**
         * @param string|null $value
         */
        function set_search_limit($value) {
            $this->_search_limit = ($value == '') ? null : (int) $value;
        }

        /**
         * @return integer|null
         */
        function get_search_limit() {
            return $this->_search_limit;
        }

        /**
         * @param string|null $value
         */
        function set_search_order($value) {
            $this->_search_order = ($value == '') ? null : $value;
        }

        /**
         * @param string|null $value
         *
         * @throws SModelException
         */
        function set_smart_search_order($value) {
            if ($value == '') {
                $this->_search_order = null;

                return;
            }
            /**
             * @var string[][] $orders_parsed
             */
            $orders_parsed = [];
            foreach (explode(',', $value) as &$order) {
                if (preg_match('_^(.+?)\\s+(asc|desc)$_ui', trim($order), $a)) {
                    $orders_parsed[] = [$a[1], strtolower($a[2])];
                } else {
                    $orders_parsed[] = [$a[1], 'asc'];
                }
            }
            // @todo магия волшебных виртуальных сортировок

            if (count($orders_parsed) == 0) {
                $this->_search_order = null;

                return;
            }
            $this->_search_order = '';
            foreach ($orders_parsed as &$order) {
                $this->_search_order .= ','.$order[0].' '.$order[1];
            }
            $this->_search_order = substr($this->_search_order, 1);
        }

        /**
         * @return string|null
         */
        function get_search_order() {
            return $this->_search_order;
        }

        /**
         * @return array
         */
        function get_date_input_list() {
            return $this->_date_input_list;
        }

        /**
         * @param array $value
         */
        function set_date_input_list($value) {
            $this->_date_input_list = $value;
        }

        /**
         * Low level метод для санации всех существующих атрибутов в переданных объекта
         *
         * Эта функция используется, например, в find_all
         *
         * @param SModel[] $objects
         * @param boolean  $force_all_attributes Форсированно санировать все атрибуты, даже те, которых нет
         */
        protected static function sanify_many_objects($objects, $force_all_attributes = false) {
            $chunks = [];
            foreach ($objects as &$object) {
                if (isset($chunks[get_class($object)])) {
                    $chunks[get_class($object)][] = $object;
                } else {
                    $chunks[get_class($object)] = [$object];
                }
            }
            unset($objects, $object);

            foreach ($chunks as $class_name => &$objects) {
                self::sanify_many_objects_one_class($class_name, $objects, $force_all_attributes);
            }
        }

        /**
         * @param string   $class_name
         * @param SModel[] $objects
         * @param boolean  $force_all_attributes Форсированно санировать все атрибуты, даже те, которых нет
         */
        protected static function sanify_many_objects_one_class($class_name, $objects, $force_all_attributes = false) {
            /**
             * @var SModel $class_name
             */
            $attributes = array_keys($class_name::get_attributes_list());
            foreach ($attributes as &$name) {
                $type = $class_name::get_attribute_type($name);
                $additional_type = $class_name::get_attribute_additional_type($name);
                foreach ($objects as &$object) {
                    if (!array_key_exists($name, $object->_attributes) and !$force_all_attributes) {
                        continue;
                    } elseif ($type == 'integer') {
                        $object->_attributes[$name] = (integer) $object->_attributes[$name];
                    } elseif ($type == 'double') {
                        $object->_attributes[$name] = (double) $object->_attributes[$name];
                    } else {
                        $object->_attributes[$name] =
                            self::convert_value_to_type($object->_attributes[$name], $type, $additional_type);
                    }
                }
            }
        }

        /**
         * Описание реляций
         *
         * Реляции должны быть в виде [RELATION_TYPE, CLASS_NAME]
         *
         * @return array[]
         */
        static function relations() {
            return [];
        }

        /**
         * @param string $relation_name
         *
         * @return boolean
         */
        function is_relations_static($relation_name) {
            return isset($this->_is_relations_static[$relation_name]);
        }

        /**
         * @param string  $relation_name
         * @param boolean $is_static
         *
         * @throws SModelException
         */
        function set_relations_static($relation_name, $is_static) {
            if (!isset(static::relations()[$relation_name])) {
                throw new SModelException(sprintf('Relation "%s" does not exist in class "%s"', $relation_name, static::class));
            } elseif ($is_static) {
                $this->_is_relations_static[$relation_name] = [];
            } else {
                unset($this->_is_relations_static[$relation_name]);
            }
        }

        /**
         * @param string $relation_name
         */
        protected function lazy_relation_load($relation_name) { }

        /**
         * Получаем конкретную реляцию
         *
         * @param string $relation_name
         *
         * @return null|SModel|SModel[]
         * @throws SModelException
         */
        function get_relation($relation_name) {
            if (!isset(static::relations()[$relation_name])) {
                return null;
            }
            $this->lazy_relation_load($relation_name);
            if ($this->is_relations_static($relation_name)) {
                $relation = static::relations()[$relation_name];
                if (in_array($relation[0], [self::HAS_MANY, self::MANY_TO_MANY])) {
                    if (!isset(self::$_relations_static_collection[$relation[1]])) {
                        return [];
                    } else {
                        $ret = [];
                        foreach ($this->_is_relations_static[$relation_name] as $primary_key) {
                            $ret[] = self::$_relations_static_collection[$relation[1]][$primary_key];
                        }

                        return $ret;
                    }
                } elseif ($relation[0] == self::BELONGS_TO) {
                    $keys = $this->_is_relations_static[$relation_name];
                    if (count($keys) == 0) {
                        return null;
                    }
                    $primary_key = $keys[0];

                    return self::$_relations_static_collection[$relation[1]][$primary_key];
                } else {
                    throw new SModelException(sprintf('Relation #%d isn\'t implemented', $relation[0]));
                }
            } elseif (isset($this->_relations[$relation_name])) {
                return $this->_relations[$relation_name];
            } else {
                return null;
            }
        }

        /**
         * Устанавливаем конкретную реляцию
         *
         * @param string          $relation_name
         * @param SModel[]|SModel $value
         *
         * @throws SModelException
         */
        function set_relation($relation_name, $value) {
            if (!isset(static::relations()[$relation_name])) {
                throw new SModelException('Relation does not exist');
            }
            $relation = static::relations()[$relation_name];
            if (($relation[0] == self::HAS_MANY) and !is_array($value)) {
                throw new SModelException('Has-many relation must be array');
            } elseif (($relation[0] == self::MANY_TO_MANY) and !is_array($value)) {
                throw new SModelException('Many-to-many relation must be array');
            } elseif (($relation[0] == self::BELONGS_TO) and is_array($value) and (count($value) == 1)) {
                $value = $value[0];
            } elseif (($relation[0] == self::BELONGS_TO) and is_array($value) and (count($value) == 0)) {
                $value = null;
            } elseif (($relation[0] == self::BELONGS_TO) and !is_object($value) and !is_null($value)) {
                throw new SModelException('Belong-to relation must be object or null');
            }
            if ($this->is_relations_static($relation_name)) {
                /**
                 * @var string|string[] $primary_key_name
                 */
                $primary_key_name = $relation[1]::getPrimary_key();
                if (is_array($primary_key_name)) {
                    throw new SModelException('Composite primary key isn\'t implemented');
                }
                if (is_array($value)) {
                    foreach ($value as &$item) {
                        $this->add_object_to_static_relation_collection($relation[1],
                            $item->get_attribute($primary_key_name), $item);
                        if (!in_array($item->get_attribute($primary_key_name), $this->_is_relations_static[$relation_name])) {
                            $this->_is_relations_static[$relation_name][] = $item->get_attribute($primary_key_name);
                        }
                    }
                } elseif (is_null($value)) {
                    $this->_is_relations_static[$relation_name] = [];
                } else {
                    $this->add_object_to_static_relation_collection($relation[1],
                        $value->get_attribute($primary_key_name), $value);
                    $this->_is_relations_static[$relation_name] = [$value->get_attribute($primary_key_name)];
                }
            } else {
                $this->_relations[$relation_name] = $value;
            }
        }

        /**
         * @param string         $class_name
         * @param string|integer $primary_key
         * @param SModel         $model
         */
        static function add_object_to_static_relation_collection($class_name, $primary_key, $model) {
            if (!isset(self::$_relations_static_collection[$class_name])) {
                self::$_relations_static_collection[$class_name] = [$primary_key => $model];
            } elseif (!isset(self::$_relations_static_collection[$class_name][$primary_key])) {
                self::$_relations_static_collection[$class_name][$primary_key] = $model;
            }
        }

        /**
         * @return SModel[][]
         */
        static function get_relations_static_collections() {
            return self::$_relations_static_collection;
        }

        /**
         * @return string[][]|integer[][]
         */
        function get_relations_static_primaries() {
            return $this->_is_relations_static;
        }

        /**
         * @param DateTime|integer|string|null $value
         *
         * @return DateTime|null
         */
        static function get_datetime_from_mixed($value) {
            if (is_null($value)) {
                return null;
            } elseif (is_object($value) and (get_class($value) == 'DateTime')) {
                return new $value;
            } elseif (is_integer($value)) {
                $d = new DateTime();
                $d->setTimestamp($value);

                return $d;
            } elseif (is_string($value)) {
                return new DateTime($value);
            } else {
                return null;
            }
        }

        /**
         * Берём время из атрибута
         *
         * @param string  $attribute_name
         * @param integer $type (0-DateTime,1-string full,2-string date,3-integer)
         *
         * @return DateTime|integer|string|null
         * @throws SModelException
         */
        final function get_attribute_time($attribute_name, $type = 0) {
            $d = self::get_datetime_from_mixed($this->{$attribute_name});
            if (is_null($d)) {
                return null;
            }

            switch ($type) {
                case 0:
                    return $d;
                case 1:
                    return $d->format('Y-m-d H:i:s');
                case 2:
                    return $d->format('Y-m-d');
                case 3:
                    return $d->getTimestamp();
                default:
                    throw new SModelException('Code flow exception');
            }
        }

        /**
         * @param string                  $attribute_name
         * @param DateTime|string|integer $value
         *
         * @throws SModelException
         */
        final function set_attribute_time($attribute_name, $value) {
            if (is_null($value)) {
                $this->{$attribute_name} = null;

                return;
            } elseif (is_object($value) and (get_class($value) == 'DateTime')) {
                $d = clone $value;
            } elseif (is_integer($value)) {
                $d = new DateTime();
                $d->setTimestamp($value);
            } elseif (is_string($value)) {
                $d = new DateTime($value);
            } else {
                $this->{$attribute_name} = null;

                return;
            }

            $type = self::get_attribute_type($attribute_name);

            if (!preg_match('_^(integer|string)(\\|null)?_', $type, $a)) {
                $this->{$attribute_name} = null;
            } elseif ($a[1] == 'integer') {
                $this->{$attribute_name} = $d->getTimestamp();
            } elseif ($a[1] == 'string') {
                $additional_type = self::get_attribute_additional_type($attribute_name);
                if ($additional_type == 'date') {
                    $this->{$attribute_name} = $d->format('Y-m-d');
                } elseif ($additional_type == 'datetime') {
                    $this->{$attribute_name} = $d->format('Y-m-d H:i:s');
                } else {
                    $this->{$attribute_name} = null;
                }
            } else {
                $this->{$attribute_name} = null;

                return;
            }
        }
    }

    class SModelException extends Exception {
    }

?>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/srl_news_list_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_news_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </android.support.v4.widget.SwipeRefreshLayout>

    <ProgressBar
    android:id="@+id/pb_news_fragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"/>
</RelativeLayout>


text:
require 'erb'
require 'cgi'
require 'fileutils'
require 'digest/sha1'
require 'time'

# Ensure we are using a compatible version of SimpleCov
if Gem::Version.new(SimpleCov::VERSION) < Gem::Version.new("0.7.1")
  raise RuntimeError, "The version of SimpleCov you are using is too old. Please update with `gem install simplecov` or `bundle update simplecov`"
end

class SimpleCov::Formatter::HTMLFormatter
  def format(result)
    Dir[File.join(File.dirname(__FILE__), '../public/*')].each do |path|
      FileUtils.cp_r(path, asset_output_path)
    end

    File.open(File.join(output_path, "index.html"), "w+") do |file|
      file.puts template('layout').result(binding)
    end
    puts output_message(result)
  end

  def output_message(result)
    "Coverage report generated for #{result.command_name} to #{output_path}. #{result.covered_lines} / #{result.total_lines} LOC (#{result.covered_percent.round(2)}%) covered."
  end

  private

  # Returns the an erb instance for the template of given name
  def template(name)
    ERB.new(File.read(File.join(File.dirname(__FILE__), '../views/', "#{name}.erb")))
  end

  def output_path
    SimpleCov.coverage_path
  end

  def asset_output_path
    return @asset_output_path if defined? @asset_output_path and @asset_output_path
    @asset_output_path = File.join(output_path, 'assets', SimpleCov::Formatter::HTMLFormatter::VERSION)
    FileUtils.mkdir_p(@asset_output_path)
    @asset_output_path
  end

  def assets_path(name)
    File.join('./assets', SimpleCov::Formatter::HTMLFormatter::VERSION, name)
  end

  # Returns the html for the given source_file
  def formatted_source_file(source_file)
    template('source_file').result(binding)
  end

  # Returns a table containing the given source files
  def formatted_file_list(title, source_files)
    title_id = title.gsub(/^[^a-zA-Z]+/, '').gsub(/[^a-zA-Z0-9\-\_]/, '')
    template('file_list').result(binding)
  end

  def coverage_css_class(covered_percent)
    if covered_percent > 90
      'green'
    elsif covered_percent > 80
      'yellow'
    else
      'red'
    end
  end

  def strength_css_class(covered_strength)
    if covered_strength > 1
      'green'
    elsif covered_strength == 1
      'yellow'
    else
      'red'
    end
  end

  # Return a (kind of) unique id for the source file given. Uses SHA1 on path for the id
  def id(source_file)
    Digest::SHA1.hexdigest(source_file.filename)
  end

  def timeago(time)
    "#{time.iso8601}"
  end

  def shortened_filename(source_file)
    source_file.filename.gsub(SimpleCov.root, '.').gsub(/^\.\//, '')
  end

  def link_to_source_file(source_file)
    %Q(#{shortened_filename source_file})
  end
end

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__)))
require 'simplecov-html/version'


text:
FROM    ubuntu:14.10

RUN     apt-get update -y && \
        apt-get install -y software-properties-common && \
        apt-add-repository ppa:chris-lea/node.js  && \
        apt-add-repository ppa:nilarimogard/webupd8 && \
        apt-add-repository ppa:kirillshkrogalev/ffmpeg-next && \
        apt-get update -y && \
        apt-get install -y nodejs ffmpeg youtube-dl

COPY    package.json /tmp/package.json
RUN     cd /tmp && \
        npm install --production && \
        mkdir -p /src && \
        cp -a /tmp/node_modules /src/

WORKDIR /src
COPY    . /src

EXPOSE  3000

CMD     ["node", "server"]


text:
package at.salzburgresearch.vgi.vgianalyticsframework.osm.vgi.service;

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

import org.junit.Assert;
import org.junit.Test;

import at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.model.osm.impl.Way;
import at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.model.vgi.IVgiModelFactory;
import at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.model.vgi.IVgiOperation;
import at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.model.vgi.impl.VgiModelFactoryImpl;
import at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.model.vgi.impl.VgiOperationType;
import at.salzburgresearch.vgi.vgianalyticsframework.osm.vgi.service.impl.VgiOperationGeneratorOsmWayImpl;

public class TestVgiOperationGeneratorOsmWay {

	@Test
	public void testCreateWay() {
		Way w2 = new Way(1);
		List<Long> nodelist2 = new ArrayList<Long>();
		nodelist2.add(1l);
		nodelist2.add(2l);
		nodelist2.add(3l);
		nodelist2.add(4l);
		w2.setWayNodes(nodelist2);

		IVgiModelFactory factory = new VgiModelFactoryImpl();
		VgiOperationGeneratorOsmWayImpl opGenerator = new VgiOperationGeneratorOsmWayImpl(factory);

		List<IVgiOperation> operations = opGenerator.generateWayOperations(w2, null);

		Assert.assertEquals(5, operations.size());

		Assert.assertEquals(VgiOperationType.OP_CREATE_WAY, operations.get(0).getVgiOperationType());
		Assert.assertEquals(VgiOperationType.OP_ADD_NODE, operations.get(1).getVgiOperationType());
		Assert.assertEquals(1, operations.get(1).getRefId());
	}

	@Test
    public void testAddNode() {
		Way w1 = new Way(1);
		List<Long> nodelist1 = new ArrayList<Long>();
		nodelist1.add(1l);
		nodelist1.add(2l);
		nodelist1.add(3l);
		w1.setWayNodes(nodelist1);

		Way w2 = new Way(1);
		List<Long> nodelist2 = new ArrayList<Long>();
		nodelist2.add(1l);
		nodelist2.add(2l);
		nodelist2.add(3l);
		nodelist2.add(4l);
		w2.setWayNodes(nodelist2);

		IVgiModelFactory factory = new VgiModelFactoryImpl();
		VgiOperationGeneratorOsmWayImpl opGenerator = new VgiOperationGeneratorOsmWayImpl(factory);

		List<IVgiOperation> operations = opGenerator.generateWayOperations(w2, w1);

		Assert.assertEquals(1, operations.size());

		Assert.assertEquals(VgiOperationType.OP_ADD_NODE, operations.get(0).getVgiOperationType());
		Assert.assertEquals(4, operations.get(0).getRefId());
	}

	@Test
    public void testRemoveNode() {
		Way w1 = new Way(1);
		List<Long> nodelist1 = new ArrayList<Long>();
		nodelist1.add(1l);
		nodelist1.add(2l);
		nodelist1.add(3l);
		nodelist1.add(4l);
		w1.setWayNodes(nodelist1);

		Way w2 = new Way(1);
		List<Long> nodelist2 = new ArrayList<Long>();
		nodelist2.add(1l);
		nodelist2.add(2l);
		nodelist2.add(3l);
		w2.setWayNodes(nodelist2);

		IVgiModelFactory factory = new VgiModelFactoryImpl();
		VgiOperationGeneratorOsmWayImpl opGenerator = new VgiOperationGeneratorOsmWayImpl(factory);

		List<IVgiOperation> operations = opGenerator.generateWayOperations(w2, w1);

		Assert.assertEquals(1, operations.size());

		Assert.assertEquals(VgiOperationType.OP_REMOVE_NODE, operations.get(0).getVgiOperationType());
		Assert.assertEquals(3, operations.get(0).getPosition());
	}

	@Test
    public void testAddAndRemoveNodes() {
		Way w1 = new Way(1);
		List<Long> nodelist1 = new ArrayList<Long>();
		nodelist1.add(1l);
		nodelist1.add(2l);
		nodelist1.add(3l);
		nodelist1.add(4l);
		w1.setWayNodes(nodelist1);

		Way w2 = new Way(1);
		List<Long> nodelist2 = new ArrayList<Long>();
		nodelist2.add(1l);
		nodelist2.add(5l);
		nodelist2.add(6l);
		nodelist2.add(3l);
		w2.setWayNodes(nodelist2);

		IVgiModelFactory factory = new VgiModelFactoryImpl();
		VgiOperationGeneratorOsmWayImpl opGenerator = new VgiOperationGeneratorOsmWayImpl(factory);

		List<IVgiOperation> operations = opGenerator.generateWayOperations(w2, w1);

		Assert.assertEquals(4, operations.size());

		Assert.assertEquals(VgiOperationType.OP_REMOVE_NODE, operations.get(0).getVgiOperationType());
		Assert.assertEquals(3, operations.get(0).getPosition());
		Assert.assertEquals(VgiOperationType.OP_REMOVE_NODE, operations.get(1).getVgiOperationType());
		Assert.assertEquals(1, operations.get(1).getPosition());
		Assert.assertEquals(VgiOperationType.OP_ADD_NODE, operations.get(2).getVgiOperationType());
		Assert.assertEquals(5, operations.get(2).getRefId());
		Assert.assertEquals(1, operations.get(2).getPosition());
		Assert.assertEquals(VgiOperationType.OP_ADD_NODE, operations.get(3).getVgiOperationType());
		Assert.assertEquals(6, operations.get(3).getRefId());
		Assert.assertEquals(2, operations.get(3).getPosition());
	}

	@Test
    public void testReorderNode() {
		Way w1 = new Way(1);
		List<Long> nodelist1 = new ArrayList<Long>();
		nodelist1.add(1l);
		nodelist1.add(2l);
		nodelist1.add(3l);
		w1.setWayNodes(nodelist1);

		Way w2 = new Way(1);
		List<Long> nodelist2 = new ArrayList<Long>();
		nodelist2.add(1l);
		nodelist2.add(3l);
		nodelist2.add(2l);
		w2.setWayNodes(nodelist2);

		IVgiModelFactory factory = new VgiModelFactoryImpl();
		VgiOperationGeneratorOsmWayImpl opGenerator = new VgiOperationGeneratorOsmWayImpl(factory);

		List<IVgiOperation> operations = opGenerator.generateWayOperations(w2, w1);

		Assert.assertEquals(1, operations.size());

		Assert.assertEquals(VgiOperationType.OP_REORDER_NODE, operations.get(0).getVgiOperationType());
		Assert.assertEquals(1, operations.get(0).getPosition());
		Assert.assertEquals(2, operations.get(0).getRefId());
	}
}


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

<title>oracle.kv.hadoop.table (Oracle NoSQL Database API)</title>
<meta name="date" content="2015-12-03">
<link rel="stylesheet" type="text/css" href="../../../../style.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Oracle NoSQL Database
 version 12cR1.3.5.2

Prev Package

Next Package

Frames

No Frames

All Classes

Package oracle.kv.hadoop.table

Support for running MapReduce jobs against data written to an Oracle NoSQL Database via the Table API.

See: Description

Class Summary

Class
Description

TableInputFormat

A Hadoop InputFormat class for reading data from an Oracle NoSQL Database.

TableInputSplit

Concrete implementation of the InputSplit interface required to perform
 Hadoop MapReduce.

TableRecordReader

Concrete implementation of TableRecordReaderBase that reads table rows
 from an InputSplit using a PrimaryKey.

Package oracle.kv.hadoop.table Description

Support for running MapReduce jobs against data written to an Oracle NoSQL Database via the Table API.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Oracle NoSQL Database
 version 12cR1.3.5.2

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright (c) 2011, 2015 Oracle and/or its affiliates.  All rights reserved.


text:
#include "config.h"

#include "core/html/canvas/EXTTextureFilterAnisotropic.h"

namespace blink {

EXTTextureFilterAnisotropic::EXTTextureFilterAnisotropic(WebGLRenderingContextBase* context)
    : WebGLExtension(context)
{
    context->extensionsUtil()->ensureExtensionEnabled("GL_EXT_texture_filter_anisotropic");
}

EXTTextureFilterAnisotropic::~EXTTextureFilterAnisotropic()
{
}

WebGLExtensionName EXTTextureFilterAnisotropic::name() const
{
    return EXTTextureFilterAnisotropicName;
}

PassRefPtrWillBeRawPtr<EXTTextureFilterAnisotropic> EXTTextureFilterAnisotropic::create(WebGLRenderingContextBase* context)
{
    return adoptRefWillBeNoop(new EXTTextureFilterAnisotropic(context));
}

bool EXTTextureFilterAnisotropic::supported(WebGLRenderingContextBase* context)
{
    return context->extensionsUtil()->supportsExtension("GL_EXT_texture_filter_anisotropic");
}

const char* EXTTextureFilterAnisotropic::extensionName()
{
    return "EXT_texture_filter_anisotropic";
}

} // namespace blink


text:
// @flow

/**
 * Create an action for when dominant speaker changes.
 *
 * {
 *     type: DOMINANT_SPEAKER_CHANGED,
 *     participant: {
 *         conference: JitsiConference,
 *         id: string,
 *         previousSpeakers: Array<string>,
 *         silence: boolean
 *     }
 * }
 */
export const DOMINANT_SPEAKER_CHANGED = 'DOMINANT_SPEAKER_CHANGED';

/**
 * Create an action for granting moderator to a participant.
 *
 * {
 *     type: GRANT_MODERATOR,
 *     id: string
 * }
 */
export const GRANT_MODERATOR = 'GRANT_MODERATOR';

/**
 * Create an action for removing a participant from the conference.
 *
 * {
 *     type: KICK_PARTICIPANT,
 *     id: string
 * }
 */
export const KICK_PARTICIPANT = 'KICK_PARTICIPANT';

/**
 * Create an action for muting a remote participant.
 *
 * {
 *     type: MUTE_REMOTE_PARTICIPANT,
 *     id: string
 * }
 */
export const MUTE_REMOTE_PARTICIPANT = 'MUTE_REMOTE_PARTICIPANT';

/**
 * Create an action for when the local participant's display name is updated.
 *
 * {
 *     type: PARTICIPANT_DISPLAY_NAME_CHANGED,
 *     id: string,
 *     name: string
 * }
 */
export const PARTICIPANT_DISPLAY_NAME_CHANGED
    = 'PARTICIPANT_DISPLAY_NAME_CHANGED';

/**
 * Action to signal that ID of participant has changed. This happens when
 * local participant joins a new conference or quits one.
 *
 * {
 *     type: PARTICIPANT_ID_CHANGED,
 *     conference: JitsiConference
 *     newValue: string,
 *     oldValue: string
 * }
 */
export const PARTICIPANT_ID_CHANGED = 'PARTICIPANT_ID_CHANGED';

/**
 * Action to signal that participant role has changed. e.
 *
 * {
 *     type: PARTICIPANT_ROLE_CHANGED,
 *     participant: {
 *         id: string
 *     }
 *     role: string
 * }
 */
export const PARTICIPANT_ROLE_CHANGED = 'PARTICIPANT_ROLE_CHANGED';

/**
 * Action to signal that a participant has joined.
 *
 * {
 *     type: PARTICIPANT_JOINED,
 *     participant: Participant
 * }
 */
export const PARTICIPANT_JOINED = 'PARTICIPANT_JOINED';

/**
 * Action to signal that a participant has been removed from a conference by
 * another participant.
 *
 * {
 *     type: PARTICIPANT_KICKED,
 *     kicked: Object,
 *     kicker: Object
 * }
 */
export const PARTICIPANT_KICKED = 'PARTICIPANT_KICKED';

/**
 * Action to handle case when participant lefts.
 *
 * {
 *     type: PARTICIPANT_LEFT,
 *     participant: {
 *         id: string
 *     }
 * }
 */
export const PARTICIPANT_LEFT = 'PARTICIPANT_LEFT';

/**
 * Action to handle case when info about participant changes.
 *
 * {
 *     type: PARTICIPANT_UPDATED,
 *     participant: Participant
 * }
 */
export const PARTICIPANT_UPDATED = 'PARTICIPANT_UPDATED';

/**
 * The type of the Redux action which pins a conference participant.
 *
 * {
 *     type: PIN_PARTICIPANT,
 *     participant: {
 *         id: string
 *     }
 * }
 */
export const PIN_PARTICIPANT = 'PIN_PARTICIPANT';

/**
 * Action to signal that a hidden participant has joined.
 *
 * {
 *     type: HIDDEN_PARTICIPANT_JOINED,
 *     participant: Participant
 * }
 */
export const HIDDEN_PARTICIPANT_JOINED = 'HIDDEN_PARTICIPANT_JOINED';

/**
 * Action to handle case when hidden participant leaves.
 *
 * {
 *     type: PARTICIPANT_LEFT,
 *     participant: {
 *         id: string
 *     }
 * }
 */
export const HIDDEN_PARTICIPANT_LEFT = 'HIDDEN_PARTICIPANT_LEFT';

/**
 * The type of Redux action which notifies the app that the loadable avatar URL has changed.
 *
 * {
 *     type: SET_LOADABLE_AVATAR_URL,
 *     participant: {
 *         id: string,
           loadableAvatarUrl: string
 *     }
 * }
 */
export const SET_LOADABLE_AVATAR_URL = 'SET_LOADABLE_AVATAR_URL';

/**
 * The type of Redux action which notifies that the screenshare participant's display name has changed.
 *
 * {
 *     type: SCREENSHARE_PARTICIPANT_NAME_CHANGED,
 *     id: string,
 *     name: string
 * }
 */
 export const SCREENSHARE_PARTICIPANT_NAME_CHANGED = 'SCREENSHARE_PARTICIPANT_NAME_CHANGED';

/**
 * Raises hand for the local participant.
 * {
 *     type: LOCAL_PARTICIPANT_RAISE_HAND
 * }
 */
export const LOCAL_PARTICIPANT_RAISE_HAND = 'LOCAL_PARTICIPANT_RAISE_HAND';

/**
 * Updates participant in raise hand queue.
 * {
 *     type: RAISE_HAND_UPDATED,
 *     participant: {
 *         id: string,
 *         raiseHand: boolean
 *     }
 * }
 */
export const RAISE_HAND_UPDATED = 'RAISE_HAND_UPDATED';

/**
 * The type of Redux action which notifies that the local participant has changed the audio levels.
 * {
 *     type: LOCAL_PARTICIPANT_AUDIO_LEVEL_CHANGED
 *     level: number
 * }
 */
export const LOCAL_PARTICIPANT_AUDIO_LEVEL_CHANGED = 'LOCAL_PARTICIPANT_AUDIO_LEVEL_CHANGED'

/**
 * The type of Redux action which overwrites the name of a participant.
 * {
 *     type: OVERWRITE_PARTICIPANT_NAME,
 *     id: string,
 *     name: string
 * }
 */
export const OVERWRITE_PARTICIPANT_NAME = 'OVERWRITE_PARTICIPANT_NAME';

/**
 * The type of Redux action which overwrites the names of multiple participants.
 * {
 *     type: OVERWRITE_PARTICIPANTS_NAMES,
 *     participantsList: Array<Object>,
 * }
 */
export const OVERWRITE_PARTICIPANTS_NAMES = 'OVERWRITE_PARTICIPANTS_NAMES';

/**
 * Updates participants local recording status.
 * {
 *     type: SET_LOCAL_PARTICIPANT_RECORDING_STATUS,
 *     recording: boolean,
 *     onlySelf: boolean
 * }
 */
export const SET_LOCAL_PARTICIPANT_RECORDING_STATUS = 'SET_LOCAL_PARTICIPANT_RECORDING_STATUS';


text:
package com.google.android.libraries.mobiledatadownload.file.openers;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import android.net.Uri;
import com.google.android.libraries.mobiledatadownload.file.SynchronousFileStorage;
import com.google.android.libraries.mobiledatadownload.file.backends.JavaFileBackend;
import com.google.android.libraries.mobiledatadownload.file.common.testing.BufferingMonitor;
import com.google.android.libraries.mobiledatadownload.file.common.testing.FileDescriptorLeakChecker;
import com.google.android.libraries.mobiledatadownload.file.common.testing.NoOpMonitor;
import com.google.android.libraries.mobiledatadownload.file.common.testing.StreamUtils;
import com.google.android.libraries.mobiledatadownload.file.common.testing.TemporaryUri;
import com.google.android.libraries.mobiledatadownload.file.transforms.CompressTransform;
import com.google.android.libraries.mobiledatadownload.file.transforms.TransformProtos;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public final class MappedByteBufferOpenerAndroidTest {

  private SynchronousFileStorage storage;

  @Rule public TemporaryUri tmpUri = new TemporaryUri();
  @Rule public FileDescriptorLeakChecker leakChecker = new FileDescriptorLeakChecker();

  @Before
  public void setUpStorage() throws Exception {
    storage =
        new SynchronousFileStorage(
            ImmutableList.of(new JavaFileBackend()), ImmutableList.of(new CompressTransform()));
  }

  @Test
  public void succeedsWithSimplePath() throws Exception {
    Uri uri = tmpUri.newUri();
    byte[] content = StreamUtils.makeArrayOfBytesContent();
    StreamUtils.createFile(storage, uri, content);

    MappedByteBuffer buffer = storage.open(uri, MappedByteBufferOpener.createForRead());
    assertThat(extractBytes(buffer)).isEqualTo(content);
  }

  @Test
  public void bufferIsReadOnly() throws Exception {
    Uri uri = tmpUri.newUri();
    byte[] content = StreamUtils.makeArrayOfBytesContent();
    StreamUtils.createFile(storage, uri, content);

    MappedByteBuffer buffer = storage.open(uri, MappedByteBufferOpener.createForRead());
    assertThat(buffer.isReadOnly()).isTrue();
  }

  @Test
  public void failsWithTransform() throws Exception {
    Uri uri = tmpUri.newUriBuilder().withTransform(TransformProtos.DEFAULT_COMPRESS_SPEC).build();
    byte[] content = StreamUtils.makeArrayOfBytesContent();
    StreamUtils.createFile(storage, uri, content);

    assertThrows(
        IOException.class, () -> storage.open(uri, MappedByteBufferOpener.createForRead()));
  }

  @Test
  public void failsWithMissingFile() throws Exception {
    Uri uri = Uri.parse("file:/does-not-exist");

    assertThrows(
        IOException.class, () -> storage.open(uri, MappedByteBufferOpener.createForRead()));
  }

  @Test
  public void failsWithActiveMonitor() throws Exception {
    SynchronousFileStorage storageWithMonitor =
        new SynchronousFileStorage(
            ImmutableList.of(new JavaFileBackend()),
            ImmutableList.of(),
            ImmutableList.of(new BufferingMonitor()));

    Uri uri = tmpUri.newUri();
    byte[] content = StreamUtils.makeArrayOfBytesContent();
    StreamUtils.createFile(storageWithMonitor, uri, content);

    assertThrows(
        IOException.class,
        () -> storageWithMonitor.open(uri, MappedByteBufferOpener.createForRead()));
  }

  @Test
  public void succeedsWithInactiveMonitor() throws Exception {
    SynchronousFileStorage storageWithMonitor =
        new SynchronousFileStorage(
            ImmutableList.of(new JavaFileBackend()),
            ImmutableList.of(),
            ImmutableList.of(new NoOpMonitor()));

    Uri uri = tmpUri.newUri();
    byte[] content = StreamUtils.makeArrayOfBytesContent();
    StreamUtils.createFile(storageWithMonitor, uri, content);

    MappedByteBuffer buffer = storageWithMonitor.open(uri, MappedByteBufferOpener.createForRead());
    assertThat(extractBytes(buffer)).isEqualTo(content);
  }

  /**
   * Extracts the byte[] from the ByteBuffer. This method is forked from Guava ByteBuffers, which
   * isn't available on Android.
   */
  private static byte[] extractBytes(ByteBuffer buf) {
    byte[] result = new byte[buf.remaining()];
    buf.get(result);
    buf.position(buf.position() - result.length);
    return result;
  }
}


text:
import { Activity } from '../activity/activity'
import { CheckIn } from './check-in';

export class Pledge {
  pledgeID: number;
  pledgeName: string;
  pledgeMemberActivityId: number;
  pledgeCauseId: number;
  pledgeStartDate: Date;
  pledgeEndDate: Date;
  pledgeUnits: number;
  pledgeComments: string;
  activity: Activity;
  active: boolean;
  causeName: string;
  completedUnits: number;
  earnedValue: number;
  checkInsForPledge: CheckIn[];
}


text:
package edu.uci.ics.asterix.dataflow.data.nontagged.serde;

import java.io.DataInput;
import java.io.DataOutput;

import edu.uci.ics.asterix.om.base.AInt32;
import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer;
import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
import edu.uci.ics.hyracks.dataflow.common.data.marshalling.IntegerSerializerDeserializer;

public class AInt32SerializerDeserializer implements ISerializerDeserializer<AInt32> {

    private static final long serialVersionUID = 1L;

    public static final AInt32SerializerDeserializer INSTANCE = new AInt32SerializerDeserializer();

    private AInt32SerializerDeserializer() {
    }

    @Override
    public AInt32 deserialize(DataInput in) throws HyracksDataException {
        Integer i = IntegerSerializerDeserializer.INSTANCE.deserialize(in);
        return new AInt32(i);
    }

    @Override
    public void serialize(AInt32 instance, DataOutput out) throws HyracksDataException {
        IntegerSerializerDeserializer.INSTANCE.serialize(instance.getIntegerValue(), out);
    }

    public static int getInt(byte[] bytes, int offset) {
        return ((bytes[offset] & 0xff) << 24) + ((bytes[offset + 1] & 0xff) << 16) + ((bytes[offset + 2] & 0xff) << 8)
                + ((bytes[offset + 3] & 0xff) << 0);
    }
}