text:
<?php

namespace I18n;

use \Locale;
use \NumberFormatter;
use \IntlDateFormatter;
use \DateTime;
use \Patterns\Abstracts\AbstractSingleton;
use \Patterns\Interfaces\TranslatableInterface;

/**
 * Internationalization class
 *
 * For more information, see:
 * -   <http://www.unicode.org/reports/tr35/>
 * -   <http://userguide.icu-project.org/locale>
 * -   <http://userguide.icu-project.org/formatparse/datetime>
 * -   <http://www.php.net/manual/en/book.intl.php>
 *
 * @author  piwi <me@e-piwi.fr>
 */
class I18n
    extends AbstractSingleton
    implements TranslatableInterface
{

    /**
     * @var \I18n\LoaderInterface The loader object
     */
    protected $loader;

    /**
     * @var string The current language code
     */
    protected $lang;

    /**
     * @var string The current timezone code
     */
    protected $timezone;

    /**
     * @var array The translated strings in the current language code
     */
    protected $language_strings;

    /**
     * An array to cache translated strings once they are loaded in a language
     * to avoid parsing the same db file more than once
     * @var array
     */
    private $language_strings_cache = array();

// --------------------
// Construct / Destruct / Clone
// --------------------

    /**
     * Initialization : the true constructor
     *
     * @param   \I18n\LoaderInterface  $loader
     * @param   string $lang A language code to use by default
     * @param   string $timezone A timezone code to use by default
     * @return  self
     * @throws  \I18n\I18nException if no default locale is defined and the `$lang` argument
     *          is empty, and if no default timezone is defined and the `$timezone` argument
     *          is empty
     */
    protected function init(LoaderInterface $loader, $lang = null, $timezone = null)
    {
        $this->setLoader($loader);
        if (is_null($lang)) {
            $lang = substr(Locale::getDefault(), 0, 2);
            if (empty($lang)) {
                throw new I18nException(
                    'No default locale defined in your system, please define the second argument of method "I18n::getInstance()"!'
                );
            }
        }

        $this->setLanguage($lang, false, $this->getLoader()->getOption('force_rebuild'));
        if (is_null($timezone)) {
            $timezone = @date_default_timezone_get();
            if (empty($timezone)) {
                throw new I18nException(
                    'No default timezone defined in your system, please define the third argument of method "I18n::getInstance()"!'
                );
            }
        }
        $this->setTimezone($timezone);

        if (empty($this->language_strings)) {
            $this->setLanguage(
                $this->getLoader()->getOption('default_language', 'en'),
                false,
                $this->getLoader()->getOption('force_rebuild')
            );
        }

        return $this;
    }

    /**
     * Load the current language strings
     *
     * This will parse the current language db files, or take it from the cache if so and load
     * the strings table in `$this->language_strings`.
     *
     * @param   bool $throw_errors Throw errors while re-creating the databases (default is `false`)
     * @param   bool $force_rebuild Force the system to rebuild the databases using `I18n\Generator` if it does not exist (default is `false`)
     * @param   bool $force_rebuild_on_update Force the system to rebuild the databases using `I18n\Generator` if it's more recent than language strings files (default is `false`)
     * @return  self
     * @throws  \I18n\I18nException if the database file seems to be malformed, and a
     * @throws  \I18n\I18nInvalidArgumentException it the file can't be found
     */
    protected function _loadLanguageStrings($throw_errors = true, $force_rebuild = false, $force_rebuild_on_update = false)
    {
        $_fn = $this->getLoader()->buildLanguageFileName($this->lang);
        $_f = $this->getLoader()->buildLanguageFilePath($this->lang);

        if (
            isset($this->language_strings_cache[$_f]) &&
            isset($this->language_strings_cache[$this->lang])
        ) {
            $this->language_strings = $this->language_strings_cache[$this->lang];
            return $this;
        }

        $db_f = $this->getLoader()->buildLanguageDBFilePath();
        if (@file_exists($_f)) {
            if ($force_rebuild_on_update && filemtime($db_f)>filemtime($_f)) {
                return $this
                    ->_rebuildLanguageStringsFiles()
                    ->_loadLanguageStrings();
            } else {
                $_v = $this->getLoader()->buildLanguageVarname($this->lang);
                include $_f;
                if (isset($$_v)) {
                    if (!isset($this->language_strings_cache[$this->lang])) {
                        $this->language_strings_cache[$this->lang] = array();
                    }
                    $this->language_strings_cache[$this->lang] =
                        array_merge($this->language_strings_cache[$this->lang], $$_v);
                    $this->language_strings_cache[$_f] = array(
                        'language'  => $this->lang,
                        'strings'   => $$_v
                    );
                    return $this->_loadLanguageStrings();
                } else {
                    throw new I18nException(
                        sprintf('Language strings seems to be malformed in file "%s" (must be a classic array like "string_index"=>"string in the language")!', $_fn)
                    );
                }
            }
        } elseif ($force_rebuild) {
            return $this
                ->_rebuildLanguageStringsFiles()
                ->_loadLanguageStrings();
        } elseif ($throw_errors) {
            throw new I18nInvalidArgumentException(
                sprintf('Language strings file for language code "%s" not found (searched in "%s")!', $this->lang, $_f)
            );
        }

        return $this;
    }

    /**
     * Rebuild the language strings databases with `I18n\Generator`
     *
     * @return self
     */
    protected function _rebuildLanguageStringsFiles()
    {
        $db_filepath = $this->getLoader()->buildLanguageDBFilePath();
        $generator = new Generator($db_filepath);
        $generator->generate();
        return $this;
    }

// --------------------
// Getters / Setters / Checkers / Builders
// --------------------

    /**
     * Store the loader
     *
     * @param   \I18n\LoaderInterface $loader
     * @return  self
     */
    public function setLoader(LoaderInterface $loader)
    {
        $this->loader = $loader;
        return $this;
    }

    /**
     * Gets the loader
     *
     * @return \I18n\LoaderInterface
     */
    public function getLoader()
    {
        return $this->loader;
    }

    /**
     * Load a new language file
     * @param   string          $file_name
     * @param   null|string     $dir_name
     * @throws  \I18n\I18nException
     * @throws  \Exception
     */
    public function loadFile($file_name, $dir_name = null)
    {
        try {
            $loader = $this->getLoader();
            $file_path = $loader->findLanguageDBFile(
                !empty($file_name) ? basename($file_name) : $file_name,
                !empty($dir_name) ? $dir_name : (
                    !empty($file_name) ? dirname($file_name) : $dir_name
                )
            );
            if ($file_path && file_exists($file_path)) {
                $loader
                    ->setOption('language_strings_db_directory', dirname($file_path))
                    ->setOption('language_strings_db_filename', basename($file_path))
                ;

                $this->_loadLanguageStrings(true, true, true);
            } else {
                throw new I18nInvalidArgumentException(
                    sprintf('Language file "%s" not found!', $file_name)
                );
            }
        } catch (I18nException $e) {
            throw $e;
        }
    }

    /**
     * Loads a new language
     *
     * This will actually define a new default Locale and load the language strings database.
     *
     * @param   string $lang A language code to use by default
     * @param   bool $throw_errors Throw errors while re-creating the databases (default is `false`)
     * @param   bool $force_rebuild Force the system to rebuild the databases using `I18n\Generator` (default is `false`)
     * @return  self Returns `$this` for method chaining
     * @throws  \I18n\I18nInvalidArgumentException it the language is not available
     */
    public function setLanguage($lang, $throw_errors = true, $force_rebuild = false)
    {
        if ($this->isAvailableLanguage($lang)) {
            $this->lang = $lang;
            $this->setLocale($this->getAvailableLocale($lang));
            $this->_loadLanguageStrings($throw_errors, $force_rebuild);
        } else {
            throw new I18nInvalidArgumentException(
                sprintf('Language "%s" is not available in the application (available languages are %s)!',
                    $lang, join(', ', $this->getLoader()->getOption('available_languages')))
            );
        }
        return $this;
    }

    /**
     * Get the current language code used
     *
     * @return string The current language code in use
     */
    public function getLanguage()
    {
        return $this->lang;
    }

    /**
     * Try to get the browser default locale and use it
     *
     * @return self
     */
    public function setDefaultFromHttp()
    {
        $http_locale = $this->getHttpHeaderLocale();
        if (!empty($http_locale) && $this->isAvailableLanguage($http_locale)) {
            $this->setLanguage($http_locale);
        }
        return $this;
    }

    /**
     * Check if a language code is available in the Loader
     *
     * @param string $lang A language code to use by default
     * @return bool Returns `true` if the language code exists, `false` otherwise
     */
    public function isAvailableLanguage($lang)
    {
        return array_key_exists($lang, $this->getLoader()->getOption('available_languages')) ||
            in_array($lang, $this->getLoader()->getOption('available_languages'));
    }

    /**
     * Get the full locale info for a language code
     *
     * This will look in the `Loader::available_languages` option to retrieve the full
     * locale string corresponding to a language code.
     *
     * @param string $lang A language code to use by default
     * @return null|string The full locale string if found
     */
    public function getAvailableLocale($lang)
    {
        $langs = $this->getLoader()->getOption('available_languages');
        if (array_key_exists($lang, $langs)) {
            return $langs[$lang];
        } elseif (in_array($lang, $langs)) {
            return $langs[array_search($lang, $langs)];
        }
        return null;
    }

    /**
     * Get the list of `Loader::available_languages`
     *
     * @return array The array defined in the Loader
     */
    public function getAvailableLanguages()
    {
        return $this->getLoader()->getOption(
            'available_languages',
            array($this->getLoader()->getOption('default_language', 'en'))
        );
    }

    /**
     * Define a new locale for the system
     *
     * @param string $locale The full locale string to define
     * @return self Returns `$this` for method chaining
     */
    public function setLocale($locale)
    {
        Locale::setDefault($locale);
        return $this;
    }

    /**
     * Get the current locale used by the system
     *
     * @return string The full locale string currently in use
     */
    public function getLocale()
    {
        return Locale::getDefault();
    }

    /**
     * Define a new timezone for the system
     *
     * @param string $timezone The full timezone string to define
     * @return self
     */
    public function setTimezone($timezone)
    {
        $this->timezone = $timezone;
        date_default_timezone_set($this->timezone);
        return $this;
    }

    /**
     * Get the current timezone used by the system
     *
     * @return string The full timezone string currently in use
     */
    public function getTimezone()
    {
        return $this->timezone;
    }

    /**
     * Check if a translation exists for an index
     *
     * @param string $index The original string or index to find translation of
     * @return bool Returns `true` if the translation exists, `false` otherwise
     */
    public function hasLocalizedString($index)
    {
        return isset($this->language_strings[$index]);
    }

    /**
     * Get the translation of an index
     *
     * @param string $index The original string or index to find translation of
     * @return string The translation found if so, `$index` otherwise
     */
    public function getLocalizedString($index)
    {
        return isset($this->language_strings[$index]) ?  $this->language_strings[$index] : $index;
    }

    /**
     * Parse a translated string making some parameters replacements
     *
     * @param string $str The original string to work on
     * @param array $arguments A table of arguments to replace, like `var=>val` pairs for
     *          the replacement of `%var%` by `val` in the final string (by default)
     * @return string The string with replacements
     */
    public function parseString($str, array $arguments = null)
    {
        if (empty($arguments)) {
            return $str;
        }
        $arg_mask = $this->getLoader()->getOption('arg_wrapper_mask');
        foreach ($arguments as $name=>$value) {
            if (is_string($name)) {
                $str = strtr($str, array( sprintf($arg_mask, $name) => $value));
            } else {
                $str = sprintf($str, self::translate($value));
            }
        }
        return $str;
    }

    /**
     * Get the meta-data of a language string
     *
     * @param   string  $str
     * @return  array   array( (string) $str , (array) $info )
     */
    public function parseStringMetadata($str)
    {
        $info = array();
        if (0!==preg_match('~^\[([^\]]+)\]~i', $str, $matches)) {
            $str = str_replace($matches[0], '', $str);
            $types = $matches[1];
            $types_items = explode(';', $types);
            foreach ($types_items as $item) {
                $parts = explode(':', $item);
                if (count($parts)>1) {
                    $info[$parts[0]] = $parts[1];
                } else {
                    $info[] = $parts[0];
                }
            }
        }
        return array($str, $info);
    }

    /**
     * Special function to show a string when its translation doesn't exist
     *
     * This will return the original string with its arguments if so.
     *
     * @param string $str The original string to work on
     * @param array $args A table of arguments to replace
     * @return string The string dumped to identify untranslated strings
     */
    protected function _showUntranslated($str = '', array $args = null)
    {
        $arguments = '';
        if (!empty($args)) {
            foreach ($args as $var=>$val) {
                $arguments .= '"'.$var.'" => '.str_replace(array("\n", "\t"), '', var_export($val, 1)).', ';
            }
        }
        return sprintf($this->getLoader()->getOption('show_untranslated_wrapper', '%s'), $str, $arguments);
    }

// --------------------
// Names, currencies and codes getters
// --------------------

    /**
     * Get the currency of the current locale
     *
     * @param string $lang The language to use
     * @return string The currency code for the current locale
     */
    public function getCurrency($lang = null)
    {
        if (!is_null($lang)) {
            $original_lang = $this->getLanguage();
            $this->setLanguage($lang);
        }
        $formatter = new NumberFormatter($this->getLocale(), NumberFormatter::CURRENCY);
        $currency = $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);
        if (!empty($original_lang)) {
            $this->setLanguage($original_lang);
        }
        return $currency;
    }

    /**
     * Get the browser requested locale if so
     *
     * @return string The browser prefered locale
     */
    public function getHttpHeaderLocale()
    {
        return Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
    }

    /**
     * Get the full list of `Loader::available_languages` option like human readable names
     *
     * @param string $lang The language to use
     * @return array The available languages table with the value as the human readable description
     *          of the corresponding locale
     */
    public function getAvailableLanguagesNames($lang = null)
    {
        if (!is_null($lang)) {
            $original_lang = $this->getLanguage();
            $this->setLanguage($lang);
        }
        $db = $this->getLoader()->getOption('available_languages');
        $full_locales = array();
        if (!empty($db)) {
            foreach ($db as $ln=>$locale) {
                $full_locales[$ln] = Locale::getDisplayName($locale);
            }
        }
        if (!empty($original_lang)) {
            $this->setLanguage($original_lang);
        }
        return $full_locales;
    }

    /**
     * Get the language code of the current locale
     *
     * @param string $lang The language to use
     * @return string The language code for the current locale
     */
    public function getLanguageCode($lang = null)
    {
        $parts = $this->_callInternalLocale('parseLocale', null, $lang, false);
        return isset($parts['language']) ? $parts['language'] : null;
    }

    /**
     * Get the region code of the current locale
     *
     * @param string $lang The language to use
     * @return string The region code for the current locale
     */
    public function getRegionCode($lang = null)
    {
        return $this->_callInternalLocale('getRegion', null, $lang, false);
    }

    /**
     * Get the script code of the current locale
     *
     * @param string $lang The language to use
     * @return string The script code for the current locale
     */
    public function getScriptCode($lang = null)
    {
        return $this->_callInternalLocale('getScript', null, $lang, false);
    }

    /**
     * Get the keywords of the current locale
     *
     * @param string $lang The language to use
     * @return array The keywords for the current locale
     */
    public function getKeywords($lang = null)
    {
        return $this->_callInternalLocale('getKeywords', null, $lang, false);
    }

    /**
     * Get one keyword value of the current locale
     *
     * @param string $keyword The keyword to search
     * @param string $lang The language to use
     * @return null|string The keyword value for the current locale if found
     */
    public function getKeyword($keyword, $lang = null)
    {
        $parts = $this->_callInternalLocale('getKeywords', null, $lang, false);
        return isset($parts[$keyword]) ? $parts[$keyword] : null;
    }

    /**
     * Get the primary language of a locale
     *
     * @param string $for_locale The locale to work on, by default this will be the current locale
     * @param string $lang The language to use, by default this will be the current locale
     * @return string The primary language for the locale in the requested language
     */
    public function getPrimaryLanguage($for_locale = null, $lang = null)
    {
        return $this->_callInternalLocale('getPrimaryLanguage', $for_locale, $lang);
    }

    /**
     * Get the language name of a locale
     *
     * @param string $for_locale The locale to work on, by default this will be the current locale
     * @param string $lang The language to use, by default this will be the current locale
     * @return string The language name for the locale in the requested language
     */
    public function getLanguageName($for_locale = null, $lang = null)
    {
        return $this->_callInternalLocale('getDisplayLanguage', $for_locale, $lang);
    }

    /**
     * Get the country name of a locale
     *
     * @param string $for_locale The locale to work on, by default this will be the current locale
     * @param string $lang The language to use, by default this will be the current locale
     * @return string The country name for the locale in the requested language
     */
    public function getCountryName($for_locale = null, $lang = null)
    {
        return $this->_callInternalLocale('getDisplayRegion', $for_locale, $lang);
    }

    /**
     * Get the script name of a locale
     *
     * @param string $for_locale The locale to work on, by default this will be the current locale
     * @param string $lang The language to use, by default this will be the current locale
     * @return string The script name for the locale in the requested language
     */
    public function getLocaleScript($for_locale = null, $lang = null)
    {
        return $this->_callInternalLocale('getDisplayScript', $for_locale, $lang);
    }

    /**
     * Get the variant name of a locale
     *
     * @param string $for_locale The locale to work on, by default this will be the current locale
     * @param string $lang The language to use, by default this will be the current locale
     * @return string The variant name for the locale in the requested language
     */
    public function getLocaleVariant($for_locale = null, $lang = null)
    {
        return $this->_callInternalLocale('getDisplayVariant', $for_locale, $lang);
    }

    /**
     * Internally factorize the Locale methods
     *
     * @param   string $fct_name The name of the method to execute on `Locale`
     * @param   string $for_locale The locale to work on, by default this will be the current locale
     * @param   string $lang The language to use, by default this will be the current locale
     * @param   bool $do_array Do we have to pass both `$for_locale` and `$lang` arguments (default is `true`)
     * @return  mixed The result of `Locale:: $fct_name ( $for_locale , $lang )`
     */
    protected function _callInternalLocale($fct_name, $for_locale = null, $lang = null, $do_array = true)
    {
        if (!is_null($lang)) {
            $original_lang = $this->getLanguage();
            $this->setLanguage($lang);
        }
        $locale = !is_null($for_locale) ? $this->getAvailableLocale($for_locale) : $this->getLocale();
        $arguments = $do_array ? array($locale, $this->getLocale()) : array($locale);
        $str = call_user_func_array(array('Locale', $fct_name), $arguments);
        if (!empty($original_lang)) {
            $this->setLanguage($original_lang);
        }
        return $str;
    }

// --------------------
// Utilities formatter
// --------------------

    /**
     * Get a localized number value
     *
     * This is called by aliases `_N` and `numberify`.
     *
     * @param   int $number The number value to parse
     * @param   string $lang The language to use, by default this will be the current locale
     * @return  string The number value written in the locale
     * @see     _N()
     * @see     numberify()
     */
    public static function getLocalizedNumberString($number, $lang = null)
    {
        $_this = self::getInstance();
        if (!is_null($lang)) {
            $original_lang = $_this->getLanguage();
            $_this->setLanguage($lang);
        }
        $formatter = new NumberFormatter($_this->getLocale(), NumberFormatter::DEFAULT_STYLE);
        $str =  $formatter->format($number);
        if (!empty($original_lang)) {
            $_this->setLanguage($original_lang);
        }
        return $str;
    }

    /**
     * Get a localized price value
     *
     * This is called by aliases `_C` and `currencify`.
     *
     * @param   int $number The price value to parse
     * @param   string $lang The language to use, by default this will be the current locale
     * @return  string The price value written in the locale with a currency sign
     * @see     _C()
     * @see     currencify()
     */
    public static function getLocalizedPriceString($number, $lang = null)
    {
        $_this = self::getInstance();
        if (!is_null($lang)) {
            $original_lang = $_this->getLanguage();
            $_this->setLanguage($lang);
        }
        $formatter = new NumberFormatter($_this->getLocale(), NumberFormatter::CURRENCY);
        $str = $formatter->format($number);
        if (!empty($original_lang)) {
            $_this->setLanguage($original_lang);
        }
        return $str;
    }

    /**
     * Get a localized date value
     *
     * This is called by aliases `_D` and `datify`.
     *
     * @param   \DateTime $date The date value to parse as a `DateTime` object
     * @param   string $mask    A mask to use for date writing (by default, the `datetime_mask_icu` translation
     *                          string will be used, or no mask at all if it is not defined)
     * @param   string $charset The charset to use (default is `utf-8`)
     * @param   string $lang The language to use, by default this will be the current locale
     * @return  string The date value written in the locale
     * @see     _D()
     * @see     datify()
     */
    public static function getLocalizedDateString(DateTime $date, $mask = null, $charset = 'UTF-8', $lang = null)
    {
        $_this = self::getInstance();
        if (!is_null($lang)) {
            $original_lang = $_this->getLanguage();
            $_this->setLanguage($lang);
        }

        if (is_null($mask)) {
            $mask = $_this->getLocalizedString('datetime_mask_icu');
        }
        if (!empty($mask)) {
            $fmt = new IntlDateFormatter($_this->getLocale(), IntlDateFormatter::FULL, IntlDateFormatter::FULL,
                $_this->getTimezone(), IntlDateFormatter::GREGORIAN, $mask);
        } else {
            $fmt = new IntlDateFormatter($_this->getLocale(), IntlDateFormatter::FULL, IntlDateFormatter::FULL,
                $_this->getTimezone(), IntlDateFormatter::GREGORIAN);
        }
        $str = $fmt->format($date);

/*
        if (is_null($mask)) $mask = $_this->getLocalizedString('datetime_mask');
        if (empty($mask)) $mask = '%a %e %m %Y %H:%M:%S';
        setlocale(LC_TIME, $_this->getLocale().'.'.strtoupper($charset));
        $str = strftime($mask , strtotime($date->format('Y-m-d H:i:s')));
*/
        if (!empty($original_lang)) {
            $_this->setLanguage($original_lang);
        }
        return $str;
    }

// --------------------
// Translator
// --------------------

    /**
     * Process a translation with arguments
     *
     * This is the core method of the class: it searches the translation of `$index` in the
     * current language, rebuilds it replacing the keys of `$args` by their values and returns
     * the corresponding localized translated string.
     *
     * This is called by aliases `_T` and `translate`.
     *
     * @param   string $index The index of the translation
     * @param   array $args The optional array of arguments for the final string replacements
     * @param   string $lang The language code to load translation from
     * @return  string Returns the translated string if it exists in the current language, with variables replacements
     * @see     _T()
     * @see     translate()
     */
    public static function translate($index, array $args = null, $lang = null)
    {
        $_this = self::getInstance();
        if (!is_null($lang)) {
            $original_lang = $_this->getLanguage();
            $_this->setLanguage($lang);
        }
        if ($_this->hasLocalizedString($index)) {
            $str = $_this->getLocalizedString($index);
            list($str_tmp, $meta) = $_this->parseStringMetadata($str);
            if (!empty($meta)) {
                $str = $str_tmp;
//                var_export($meta);
            }
            $str = $_this->parseString($str, $args);
        } elseif ($_this->loader->getOption('show_untranslated', false)) {
            $str = $_this->_showUntranslated($index, $args);
        } else {
            $str = $index;
        }
        if (!empty($original_lang)) {
            $_this->setLanguage($original_lang);
        }
        return $str;
    }

    /**
     * Process a translation with arguments depending on a counter
     *
     * This will first choose in `$indexes` the corresponding value for the counter `$number`
     * and then process the translation of the chosen string with arguments.
     *
     * This is called by aliases `_P` and `pluralize`.
     *
     * @param   array $indexes An array of translation strings indexes to choose in considering the counter value
     * @param   int $number The value of the counter to consider
     * @param   array $args The optional array of arguments for the final string replacements
     * @param   string $lang The language code to load translation from
     * @return  string Returns the translated string fot the counter value if it exists, in the current language and with variables replacements
     * @see     _P()
     * @see     pluralize()
     */
    public static function pluralize(array $indexes = array(), $number = 0, array $args = null, $lang = null)
    {
        $_this = self::getInstance();
        $args['nb'] = $number;
        if (isset($indexes[$number])) {
            return self::translate($indexes[$number], $args, $lang);
        }
        $str = ($number<=1) ? array_shift($indexes) : end($indexes);
        return self::translate($str, $args, $lang);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.js4ms.jsdk</groupId>
    <artifactId>js4ms-jsdk</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>org.js4ms.jsdk</groupId>
  <artifactId>http</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>http</name>
  <description>HTTP protocol classes.</description>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.js4ms.jsdk</groupId>
      <artifactId>common</artifactId>
      <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>org.js4ms.jsdk</groupId>
      <artifactId>server</artifactId>
      <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>org.js4ms.jsdk</groupId>
      <artifactId>rest</artifactId>
      <version>0.0.1-SNAPSHOT</version>
    </dependency>
  </dependencies>
</project>


text:
package com.hpcloud.mon.resource.exception;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.hpcloud.mon.resource.exception.Exceptions.FaultType;

/**
 * Adapted from Dropwizard's JsonMappingExceptionManager.
 */
@Provider
public class JsonMappingExceptionManager implements ExceptionMapper<JsonMappingException> {
  @Override
  public Response toResponse(JsonMappingException exception) {
    return Response.status(FaultType.BAD_REQUEST.statusCode)
        .type(MediaType.APPLICATION_JSON)
        .entity(
            Exceptions.buildLoggedErrorMessage(FaultType.BAD_REQUEST,
                "Unable to process the provided JSON",
                Exceptions.stripLocationFromStacktrace(exception.getMessage()), null))
        .build();
  }
}


text:
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)

using System;
using System.IO;
using ICSharpCode.Core;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.Dom;
using ICSharpCode.SharpDevelop.Project;

namespace ICSharpCode.FSharpFormsDesigner
{
	public class FSharpParser : IParser
	{
		string[] lexerTags = new string[0];

		public string[] LexerTags {
			get { return lexerTags; }
			set { lexerTags = value; }
		}

		public LanguageProperties Language {
			get { return LanguageProperties.None; }
		}

		public IExpressionFinder CreateExpressionFinder(string fileName)
		{
			return null;
		}

		public bool CanParse(string fileName)
		{
			string extension = Path.GetExtension(fileName);
			if (extension != null) {
				return extension.ToLower() == ".fs";
			}
			return false;
		}

		public bool CanParse(IProject project)
		{
			return true;
		}

		public ICompilationUnit Parse(IProjectContent projectContent, string fileName, ITextBuffer fileContent)
		{
			try {

				var parser = new FSharpClassParser(projectContent, fileName, fileContent.Text);
				return parser.Parse();

			} catch (Exception ex) {
				LoggingService.Error("Parse failed", ex);
				return new DefaultCompilationUnit(projectContent);
			}
		}

		public IResolver CreateResolver()
		{
			return null;
		}
	}
}


text:
<?php

namespace Cake\Cache\Engine;

use Cake\Cache\CacheEngine;

/**
 * Xcache storage engine for cache
 *
 * @link          http://trac.lighttpd.net/xcache/ Xcache
 */
class XcacheEngine extends CacheEngine
{

    /**
     * The default config used unless overridden by runtime configuration
     *
     * - `duration` Specify how long items in this cache configuration last.
     * - `groups` List of groups or 'tags' associated to every key stored in this config.
     *    handy for deleting a complete group from cache.
     * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
     *    with either another cache config or another application.
     * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
     *    cache::gc from ever being called automatically.
     * - `PHP_AUTH_USER` xcache.admin.user
     * - `PHP_AUTH_PW` xcache.admin.password
     *
     * @var array
     */
    protected $_defaultConfig = [
        'duration' => 3600,
        'groups' => [],
        'prefix' => null,
        'probability' => 100,
        'PHP_AUTH_USER' => 'user',
        'PHP_AUTH_PW' => 'password'
    ];

    /**
     * Initialize the Cache Engine
     *
     * Called automatically by the cache frontend
     *
     * @param array $config array of setting for the engine
     * @return bool True if the engine has been successfully initialized, false if not
     */
    public function init(array $config = [])
    {
        if (!extension_loaded('xcache')) {
            return false;
        }

        parent::init($config);
        return true;
    }

    /**
     * Write data for key into cache
     *
     * @param string $key Identifier for the data
     * @param mixed $value Data to be cached
     * @return bool True if the data was successfully cached, false on failure
     */
    public function write($key, $value)
    {
        $key = $this->_key($key);

        if (!is_numeric($value)) {
            $value = serialize($value);
        }

        $duration = $this->_config['duration'];
        $expires = time() + $duration;
        xcache_set($key . '_expires', $expires, $duration);
        return xcache_set($key, $value, $duration);
    }

    /**
     * Read a key from the cache
     *
     * @param string $key Identifier for the data
     * @return mixed The cached data, or false if the data doesn't exist,
     *   has expired, or if there was an error fetching it
     */
    public function read($key)
    {
        $key = $this->_key($key);

        if (xcache_isset($key)) {
            $time = time();
            $cachetime = (int)xcache_get($key . '_expires');
            if ($cachetime < $time || ($time + $this->_config['duration']) < $cachetime) {
                return false;
            }

            $value = xcache_get($key);
            if (is_string($value) && !is_numeric($value)) {
                $value = unserialize($value);
            }
            return $value;
        }
        return false;
    }

    /**
     * Increments the value of an integer cached key
     * If the cache key is not an integer it will be treated as 0
     *
     * @param string $key Identifier for the data
     * @param int $offset How much to increment
     * @return bool|int New incremented value, false otherwise
     */
    public function increment($key, $offset = 1)
    {
        $key = $this->_key($key);

        return xcache_inc($key, $offset);
    }

    /**
     * Decrements the value of an integer cached key.
     * If the cache key is not an integer it will be treated as 0
     *
     * @param string $key Identifier for the data
     * @param int $offset How much to subtract
     * @return bool|int New decremented value, false otherwise
     */
    public function decrement($key, $offset = 1)
    {
        $key = $this->_key($key);

        return xcache_dec($key, $offset);
    }

    /**
     * Delete a key from the cache
     *
     * @param string $key Identifier for the data
     * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
     */
    public function delete($key)
    {
        $key = $this->_key($key);

        return xcache_unset($key);
    }

    /**
     * Delete all keys from the cache
     *
     * @param bool $check If true no deletes will occur and instead CakePHP will rely
     *   on key TTL values.
     *   Unused for Xcache engine.
     * @return bool True if the cache was successfully cleared, false otherwise
     */
    public function clear($check)
    {
        $this->_auth();
        $max = xcache_count(XC_TYPE_VAR);
        for ($i = 0; $i < $max; $i++) {
            xcache_clear_cache(XC_TYPE_VAR, $i);
        }
        $this->_auth(true);
        return true;
    }

    /**
     * Returns the `group value` for each of the configured groups
     * If the group initial value was not found, then it initializes
     * the group accordingly.
     *
     * @return array
     */
    public function groups()
    {
        $result = [];
        foreach ($this->_config['groups'] as $group) {
            $value = xcache_get($this->_config['prefix'] . $group);
            if (!$value) {
                $value = 1;
                xcache_set($this->_config['prefix'] . $group, $value, 0);
            }
            $result[] = $group . $value;
        }
        return $result;
    }

    /**
     * Increments the group value to simulate deletion of all keys under a group
     * old values will remain in storage until they expire.
     *
     * @param string $group The group to clear.
     * @return bool success
     */
    public function clearGroup($group)
    {
        return (bool)xcache_inc($this->_config['prefix'] . $group, 1);
    }

    /**
     * Populates and reverses $_SERVER authentication values
     * Makes necessary changes (and reverting them back) in $_SERVER
     *
     * This has to be done because xcache_clear_cache() needs to pass Basic Http Auth
     * (see xcache.admin configuration config)
     *
     * @param bool $reverse Revert changes
     * @return void
     */
    protected function _auth($reverse = false)
    {
        static $backup = [];
        $keys = ['PHP_AUTH_USER' => 'user', 'PHP_AUTH_PW' => 'password'];
        foreach ($keys as $key => $value) {
            if ($reverse) {
                if (isset($backup[$key])) {
                    $_SERVER[$key] = $backup[$key];
                    unset($backup[$key]);
                } else {
                    unset($_SERVER[$key]);
                }
            } else {
                $value = env($key);
                if (!empty($value)) {
                    $backup[$key] = $value;
                }
                if (!empty($this->_config[$value])) {
                    $_SERVER[$key] = $this->_config[$value];
                } elseif (!empty($this->_config[$key])) {
                    $_SERVER[$key] = $this->_config[$key];
                } else {
                    $_SERVER[$key] = $value;
                }
            }
        }
    }
}


text:
/**
 * $ node build.js
 */
var packager = require('electron-packager');
var config = require('./package.json');
var zipFolder = require('zip-folder');
var rimraf = require('rimraf');

function build( condition, callback ){
	var dir = './';
	var out = './build';
	var name = config.name;

	var platform = condition.platform;
	var arch = condition.arch;

	var isWin = (platform=='win32' ? true : false);
	if (platform == 'win32') {
		console.log('Build Target -> Windows');
	} else if (platform == 'darwin') {
		console.log('Build Target -> Mac');
	} else {
		console.log('Build Target -> Unknown');
	}

	var icon = './resources/app.icns'; //<- アプリアイコン
	if (isWin) {
		icon = './resources/app_for_Windows.ico'; //<- アプリアイコン
	}

	var version = '0.36.1';
	var app_bundle_id = 'jp.pxt.applications.my-todays-all'; //<- 自分のドメインなどを使用してください
	var helper_bundle_id = 'jp.pxt.applications.my-todays-all'; //<- 自分のドメインなどを使用してください

	var zip = function (relativePath, relativeZipPath, cb) {
		zipFolder(
			__dirname + '/' + relativePath + '/',
			__dirname + '/' + relativeZipPath + '.zip',
			function (err) {
				if (err) {
					console.log('zip ERROR!', err);
				} else {
					rimraf('./' + relativePath, function () {
						// Something
						console.log('zip SUCCESS!.');
						cb();
					});

				}
			}
		);
	}
	var npm_ignore = [], ignores;
	for (var key in config.devDependencies) {
		npm_ignore.push(key);
	}
	ignores = npm_ignore.join('|');

	console.time("build-time");
	packager(
		{
			"dir": dir,
			"out": out,
			"name": name,
			"platform": platform,
			"arch": arch,
			"version": version,
			"icon": icon,
			'app-bundle-id': app_bundle_id,
			'app-version': config.version,
			'helper-bundle-id': helper_bundle_id,
			overwrite: true,
			// asar: false,
			asar: true, // aserに固める
			"asar-unpack-dir": "unpacked",
			prune: true,
			ignore: 'node_modules/(' + ignores + '|\.bin)|build|build\.js|tests|src|submodules|materials|gulpfile.js|bower.json|.bowerrc',
			'version-string': {
				CompanyName: 'tomk79',
				FileDescription: config.description,
				OriginalFilename: config.name,
				FileVersion: config.version,
				ProductVersion: config.version,
				ProductName: config.name,
				InternalName: config.name
			}
		}, function done(err, appPath) {
			if (err) {
				throw new Error(err);
			}
			console.log('appPath', appPath);

			var zipPath = './build/'+config.name+'-'+config.version+'-'+platform+'-'+arch;

			zip(appPath, zipPath, function () {
				console.timeEnd("build-time");
				console.log('Done!!');
				callback();
			});
		}
	);
}

build({'platform':'darwin','arch':'x64'}, function(){
build({'platform':'win32','arch':'x64'}, function(){
build({'platform':'win32','arch':'ia32'}, function(){
	console.log('ALL DONE!');
});
});
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2016 CMPUT301F16T10
  ~
  ~   Licensed under the Apache License, Version 2.0 (the "License");
  ~   you may not use this file except in compliance with the License.
  ~   You may obtain a copy of the License at
  ~
  ~       http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~   Unless required by applicable law or agreed to in writing, software
  ~   distributed under the License is distributed on an "AS IS" BASIS,
  ~   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~   See the License for the specific language governing permissions and
  ~   limitations under the License.
  -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="ca.ualberta.cs.drivr.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <fragment
            android:id="@+id/place_autocomplete_fragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
            />
            <EditText
                android:id="@+id/main_keyword_edit_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:imeOptions="actionDone"
                android:inputType="text"
                android:hint="Keyword Search"/>

        </LinearLayout>

    </android.support.v7.widget.CardView>
</RelativeLayout>


text:
/**
 * @module query
 */
/** */
/**
 * kind of Filter as defined by corresponding Java object model.
 */
export declare type FilterType = 'boolean' | 'containsString' | 'dateRange' | 'doubleRange' | 'like' | 'logOp' | 'longEnum' | 'longRange' | 'stringEnum' | 'string' | 'stringMap' | 'stringRange' | 'null';
/**
 * all known valid types of filters.
 *
 * @type {string[]} of all known types of filters.
 */
export declare const filterTypes: string[];
/**
 * checks if a given type value is a valid FilterType value.
 *
 * @param type value to check.
 * @return {boolean} whether type value is valid.
 */
export declare function isFilterType(type: any): type is FilterType;
export interface Filter {
    /**
     * kind of Filter as defined by corresponding Java object model.
     */
    type: FilterType;
}
/**
 * checks if an object is a Filter.
 *
 * @param filter object to check.
 * @return {boolean} whether filter is a filter.
 */
export declare function isFilter(filter: any): filter is Filter;
export interface LogOpFilter extends Filter {
    /**
     * kind of Operation as defined by corresponding Java object model.
     *
     * <p>
     *  - and
     *  - or
     *  - nand
     *  - nor
     * </p>
     */
    operation: string;
    /**
     * filters evaluated with logical operation (filter1 LOGOP filter2 LOGOP filter3...).
     */
    filters: Filter[];
}
export interface FieldFilter extends Filter {
    /**
     * field expression identifying left hand side of the filter.
     */
    fieldName: string;
}
/**
 * implementation detail of the library.
 */
export interface ValueFilter<T> extends FieldFilter {
    value: T;
}
/**
 * implementation detail of the library.
 */
export interface RangeFilter<T> extends FieldFilter {
    min?: T;
    max?: T;
}
/**
 * implementation detail of the library.
 */
export interface EnumFilter<T> extends FieldFilter {
    values: T[];
}
export interface BooleanFilter extends ValueFilter<boolean> {
}
export interface ContainsStringFilter extends FieldFilter {
    contains: string;
}
export interface DateRangeFilter extends RangeFilter<Date> {
}
/**
 * implementation detail of the library.
 */
export interface NumberRangeFilter extends RangeFilter<number> {
}
export interface DoubleRangeFilter extends NumberRangeFilter {
}
export interface LongRangeFilter extends NumberRangeFilter {
}
export interface LikeFilter extends FieldFilter {
    like: string;
}
export interface LongEnumFilter extends EnumFilter<number> {
}
export interface StringEnumFilter extends EnumFilter<string> {
}
export interface StringFilter extends ValueFilter<string> {
}
export interface StringMapFilter extends FieldFilter {
    key?: string;
    value?: string;
}
export interface StringRangeFilter extends RangeFilter<string> {
}
export interface NullFilter extends FieldFilter {
    isNull: boolean;
}


text:
[![Greenkeeper badge](https://badges.greenkeeper.io/KlausBenndorf/guide4you.svg)](https://greenkeeper.io/)

[![NPM](https://nodei.co/npm/guide4you.png?mini=true)](https://npmjs.org/package/guide4you)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
[![Continuous Integration](https://travis-ci.org/KlausBenndorf/guide4you.svg?branch=master)](https://travis-ci.org/KlausBenndorf/guide4you)
[![Documentation Coverage](http://klausbenndorf.github.io/guide4you/badge.svg)](http://klausbenndorf.github.io/guide4you/index.html)

**GUIDE4YOU** is a JavaScript Web client application built on [OpenLayers](http://openlayers.org)
that supports both desktop and mobile web browsers and features a responsive design.

![Screenshot of desktop view, 736x467 pixel](https://github.com/KlausBenndorf/guide4you/raw/master/images/screenshots/desktop-736-467.png "Screenshot of desktop view, 736x467 pixel")

For a screenshot of the mobile view [see below](#mobile-screenshot).

## What can GUIDE4YOU do for you?

With the basic system **GUIDE4YOU** can:

* Display maps like [Openstreetmap](https://openstreetmap.org), [OpenTopoMap](https://opentopomap.org), or [OpenCycleMap](http://www.thunderforest.com/maps/opencyclemap/)
* Use OSM, WMS, WFS, KML, GPX (others follow)
* Measure areas and distances
* Display your location
* Print the current view on a single page
* Overlay a base map with points of interest and the like
* Configure a set of base maps and overlays to choose from
* Allow for different languages
* …

With additional modules it can also:

* [URLAPI module](https://github.com/KlausBenndorf/guide4you-module-urlapi): Generate links so you can share a certain view of a map. That view can include a location marker and a description of the location in question.
* [Search module](https://github.com/KlausBenndorf/guide4you-module-search): Search for locations using [Nominatim](https://nominatim.openstreetmap.org/). Alternatively you can customize this module to use other engines.
* Edit GPX data (coming soon)
* …

## Why use GUIDE4YOU?

Compared to alternative software **GUIDE4YOU** provides a couple of interesting features:

* Highly customizable
* Support for new languages can easily be added. English, german, polish and arabic are supported out of the box.
* Icons are vector graphics (SVG) so they can be scaled to whatever size seems suitable
* No separate mobile and desktop versions
* Easily extensible

## Which browsers are supported?

All modern browsers including
* Firefox
* Chrome
* Edge and Internet Explorer 10+
* Safari

## How to setup?

Install guide4you from npm or clone the repository

```
npm install guide4you
```
or
```
git clone https://github.com/KlausBenndorf/guide4you.git
```

To find out what is needed to include GUIDE4YOU intoe a webpage check out the index.html in the dist folder. It contains everything that is needed to get you started.

The crucial part is:
```
  g4u.createMap('#g4u-map')
```
This method creates the map in the given DOM-Element. It accepts a selector or a reference to a DOM-Element. As a second and third argument it accepts a [map configuration](https://klausbenndorf.github.io/guide4you/typedef/index.html#static-typedef-MapConfig) and a [layer configuration](https://klausbenndorf.github.io/guide4you/typedef/index.html#static-typedef-LayerConfig). Both can be provided as paths to JSON-files or as actual JavaScript objects.

## How to build a customized version of GUIDE4YOU?

Switch into the `guide4you` directory and install all dependecies using

```
npm install
```

Then build with a configuration (simple, full) of your choice

```
npm run prod:simple
```
or

```
npm run debug:simple
```
or with a local webserver watching file changes on port 8080

```
npm run dev:simple
```
or on another port:

```
npm run dev:simple -- -p 8081
```

## Documentation

An API-documentation can be found here: [https://klausbenndorf.github.io/guide4you/index.html](https://klausbenndorf.github.io/guide4you/index.html).

Part of the API-documentation is a documentation of the [map configuration](https://klausbenndorf.github.io/guide4you/typedef/index.html#static-typedef-MapConfig)
and [layer configuration](https://klausbenndorf.github.io/guide4you/typedef/index.html#static-typedef-LayerConfig) JSON-objects.

(A german not up-to-date documentation can be found here: [GUIDE4YOU Benutzerhandbuch](https://github.com/KlausBenndorf/guide4you/wiki/GUIDE4YOU-Benutzerhandbuch))

## Support

Please feel free to ask any question on [Stackoverflow](https://stackoverflow.com) with the guide4you tag and file any bugs in the [issue tracker](https://github.com/KlausBenndorf/guide4you/issues).

## Mobile Screenshot

![Screenshot of mobile view, 360x640 pixel](https://github.com/KlausBenndorf/guide4you/raw/master/images/screenshots/mobile-360-640.png "Screenshot of mobile view, 360x640 pixel")


text:
namespace BINARY {
  learner setup(vw& all, std::vector<std::string>&opts, po::variables_map& vm, po::variables_map& vm_file);
}
#endif


text:
<?php

namespace Surfnet\StepupMiddleware\ApiBundle\EventListener;

use Broadway\Repository\AggregateNotFoundException;
use Psr\Log\LoggerInterface;
use Surfnet\Stepup\Exception\DomainException;
use Surfnet\StepupMiddleware\ApiBundle\Exception\BadApiRequestException;
use Surfnet\StepupMiddleware\ApiBundle\Exception\BadCommandRequestException;
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\Exception\InvalidCommandException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Throwable;

/**
 * Converts all exceptions into JSON responses.
 */
class ExceptionListener
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function onKernelException(ExceptionEvent $event)
    {
        $throwable = $event->getThrowable();

        $this->logException($throwable);

        if ($throwable instanceof HttpExceptionInterface && $throwable instanceof Throwable) {
            $statusCode = $throwable->getStatusCode();
            $headers = $throwable->getHeaders();
        } else {
            $statusCode = $throwable instanceof BadApiRequestException
                    || $throwable instanceof BadCommandRequestException
                    || $throwable instanceof DomainException
                    || $throwable instanceof AggregateNotFoundException
                ? 400
                : 500;

            $headers = [];
        }

        $event->setResponse($this->createJsonErrorResponse($throwable, $statusCode, $headers));
    }

    private function logException(Throwable $throwable)
    {
        # As per \Symfony\Component\HttpKernel\EventListener\ExceptionListener#logException().
        $isCritical = !$throwable instanceof HttpExceptionInterface || $throwable->getStatusCode() >= 500;

        if ($isCritical) {
            $this->logger->critical($throwable->getMessage(), ['exception' => $throwable]);
        } else {
            $this->logger->error($throwable->getMessage(), ['exception' => $throwable]);
        }
    }

    /**
     * @param Throwable $exception
     * @param int $statusCode
     * @param array $headers OPTIONAL
     * @return JsonResponse
     */
    private function createJsonErrorResponse(Throwable $throwable, $statusCode, $headers = [])
    {
        if ($throwable instanceof BadApiRequestException
            || $throwable instanceof BadCommandRequestException
            || $throwable instanceof InvalidCommandException
        ) {
            $errors = $throwable->getErrors();
        } else {
            $errors = [sprintf('%s: %s', get_class($throwable), $throwable->getMessage())];
        }

        return new JsonResponse(['errors' => $errors], $statusCode, $headers);
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Redirecting…</title>
  <link rel="canonical" href="https://surveyjs.io/Documentation/LibraryParameter?id=surveymodel&parameter=data">
  <meta http-equiv="refresh" content="0; url=https://surveyjs.io/Documentation/LibraryParameter?id=surveymodel&parameter=data">

Redirecting…

  Click here if you are not redirected.


text:
function ProsperityActions(){

}

ProsperityActions.city=function(user,game){
    console.log("Empty:"+game.countEmptyPiles());
    if(game.countEmptyPiles()==1){
        user.drawCards(1);
    }if(game.countEmptyPiles()==2){
        user.addMoney(1);
        user.addBuy(1);
    }
}

ProsperityActions.countingHouse=function(user,game){
    var coppers=Array();
    user.getDiscard().forEach(function(card){
       if(card.getData()==CardDef.copper){
           coppers.push(card);
           user.removeFromDiscard(card);
       }
    });
    user.addCardsToHand(coppers);
}


text:
// Resultstore converts --build=gs://prefix/JOB/NUMBER from prow's pod-utils to a ResultStore invocation suite, which it optionally will --upload=gcp-project.
package main

import (
	"reflect"
	"testing"

	"k8s.io/test-infra/testgrid/metadata"
	"k8s.io/test-infra/testgrid/util/gcs"
)

func TestInsertLink(t *testing.T) {
	const viewURL = "http://result/store/url"
	cases := []struct {
		name     string
		input    metadata.Metadata
		expected metadata.Metadata
		changed  bool
		err      bool
	}{
		{
			name:  "adds metadata when missing",
			input: metadata.Metadata{},
			expected: metadata.Metadata{
				linksKey: metadata.Metadata{
					resultstoreKey: metadata.Metadata{
						urlKey: viewURL,
					},
				},
				resultstoreKey: viewURL,
			},
			changed: true,
		},
		{
			name: "override resultstore metadata",
			input: metadata.Metadata{
				resultstoreKey: 234342,
			},
			expected: metadata.Metadata{
				linksKey: metadata.Metadata{
					resultstoreKey: metadata.Metadata{
						urlKey: viewURL,
					},
				},
				resultstoreKey: viewURL,
			},
			changed: true,
		},
		{
			name: "do not overwrite links key of wrong type",
			input: metadata.Metadata{
				linksKey: "unexpected type",
			},
			err: true,
		},
		{
			name: "do not overwrite resultstore link of wrong type",
			input: metadata.Metadata{
				linksKey: metadata.Metadata{
					resultstoreKey: "unexpected type",
				},
			},
			err: true,
		},
		{
			name: "do not overwrite resultstore url link of wrong type",
			input: metadata.Metadata{
				linksKey: metadata.Metadata{
					resultstoreKey: metadata.Metadata{
						urlKey: 1234,
					},
				},
			},
			err: true,
		},
		{
			name: "add to existing links",
			input: metadata.Metadata{
				linksKey: metadata.Metadata{
					"random key": 1234,
				},
			},
			expected: metadata.Metadata{
				linksKey: metadata.Metadata{
					resultstoreKey: metadata.Metadata{
						urlKey: viewURL,
					},
					"random key": 1234,
				},
				resultstoreKey: viewURL,
			},
			changed: true,
		},
		{
			name: "update existing resultstore url",
			input: metadata.Metadata{
				linksKey: metadata.Metadata{
					resultstoreKey: metadata.Metadata{
						urlKey:        "random url",
						"extra stuff": "gets preserved",
					},
				},
			},
			expected: metadata.Metadata{
				linksKey: metadata.Metadata{
					resultstoreKey: metadata.Metadata{
						urlKey:        viewURL,
						"extra stuff": "gets preserved",
					},
				},
				resultstoreKey: viewURL,
			},
			changed: true,
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			var start gcs.Started
			start.Metadata = tc.input
			changed, err := insertLink(&start, viewURL)
			switch {
			case err != nil:
				if !tc.err {
					t.Errorf("unexpected error: %v", err)
				}
			case tc.err:
				t.Error("failed to received an error")
			case changed != tc.changed:
				t.Errorf("changed %t != expected %t", changed, tc.changed)
			case !reflect.DeepEqual(tc.expected, tc.input):
				t.Errorf("metadata %#v != expected %#v", tc.input, tc.expected)
			}
		})
	}
}


text:
package com.alfresco.activiti.model;

public class Approval {

    private String comments;

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }
}


text:
import { Common } from "./Common";
export declare namespace Sender {
    export enum EmailType {
        Transactional = "transactional",
        Bulk = "bulk",
        Unknown = "unknown"
    }
    export enum SenderStatus {
        Inactive = "Inactive",
        Active = "Active",
        Deleted = "Deleted"
    }
    export interface ISender {
        ID: number;
        EmailType: EmailType;
        IsDefaultSender: boolean;
        Name: string;
        CreatedAt: string;
        DNSID: number;
        Email: string;
        Filename: string;
        Status: SenderStatus;
    }
    export interface ISenderValidate {
        ValidationMethod: string;
        Errors: string;
        GlobalError: string;
    }
    export interface IPostSenderBody {
        Email: string;
        EmailType?: EmailType;
        IsDefaultSender?: boolean;
        Name?: string;
    }
    export interface IPutSenderBody extends Omit<IPostSenderBody, 'Email'> {
    }
    export interface IGetSenderQueryParams extends Partial<Common.IPagination> {
        DnsID?: number;
        Domain?: string;
        Email?: string;
        IsDomainSender?: boolean;
        LocalPart?: string;
        ShowDeleted?: boolean;
        Status?: SenderStatus;
    }
    type TSenderResponse = Common.IResponse<ISender[]>;
    export type TPostSenderResponse = TSenderResponse;
    export type TPutSenderResponse = TSenderResponse;
    export type TGetSenderResponse = TSenderResponse;
    export type TPostSenderValidateResponse = Common.IResponse<ISenderValidate[]>;
    export {};
}
export declare namespace Metasender {
    export interface IMetaSender {
        ID: number;
        Description: string;
        CreatedAt: string;
        Email: string;
        Filename: string;
        IsEnabled: boolean;
    }
    export interface IPostMetaSenderBody {
        Email: string;
        Description?: string;
    }
    export interface IPutMetaSenderBody extends Omit<IPostMetaSenderBody, 'Email'> {
    }
    export interface IGetMetaSenderQueryParams extends Partial<Common.IPagination> {
        DNS?: number;
    }
    type TMetaSenderResponse = Common.IResponse<IMetaSender[]>;
    export type TPostMetaSenderResponse = TMetaSenderResponse;
    export type TPutMetaSenderResponse = TMetaSenderResponse;
    export type TGetMetaSenderResponse = TMetaSenderResponse;
    export {};
}
export declare namespace DNS {
    enum DKIMConfigurationCheckStatus {
        OK = "OK",
        Error = "Error",
        NotChecked = "Not checked"
    }
    enum DKIMConfigurationStatus {
        OK = "OK",
        Error = "Error"
    }
    enum SPFConfigurationCheckStatus {
        OK = "OK",
        Error = "Error",
        NotChecked = "Not checked",
        NotFound = "Not found"
    }
    enum SPFConfigurationStatus {
        OK = "OK",
        Error = "Error"
    }
    interface IDNS {
        ID: number;
        DKIMRecordName: string;
        DKIMRecordValue: string;
        DKIMStatus: DKIMConfigurationCheckStatus;
        Domain: string;
        IsCheckInProgress: boolean;
        LastCheckAt: string;
        OwnerShipToken: string;
        OwnerShipTokenRecordName: string;
        SPFRecordValue: string;
        SPFStatus: SPFConfigurationCheckStatus;
    }
    interface IDNSCheck {
        DKIMErrors: string;
        DKIMRecordCurrentValue: string;
        DKIMStatus: DKIMConfigurationStatus;
        SPFErrors: string;
        SPFRecordCurrentValue: string;
        SPFStatus: SPFConfigurationStatus;
    }
    interface IGetDNSQueryParams extends Partial<Common.IPagination> {
        IsCheckInProgress?: boolean;
        IsSenderIdentified?: boolean;
        IsYahooFBL?: boolean;
        MaxLastCheckAt?: string;
        MinLastCheckAt?: string;
        SPFStatus?: SPFConfigurationCheckStatus;
    }
    type TGetDNSResponse = Common.IResponse<IDNS[]>;
    type TPostDNSCheckResponse = Common.IResponse<IDNSCheck[]>;
}


text:
	<title>Chat Test</title>

		Chat Example

		This uses the EventSource implementation in django-gevent to provide a
		chat room. It uses an EventSource shim to allow it to run in older
		browsers by falling back to long-polling.

			<button id="send_button">Send</button>

			<textarea id="comment_input"></textarea>


text:
/*
 * File:   NodeType.h
 * Author: peter
 *
 * Created on February 28, 2012, 9:36 PM
 */

#ifndef NODETYPE_H
#define	NODETYPE_H

enum ObjectType {
    TransitionObjectType = 1,
    PlaceObjectType = 2,
    TokenObjectType = 3,
	//GeneratorObjectType = 4,
    UnknownObjectType = 5
};

enum NodeState {
    ActiveState = 1,
    InactiveState = 0
};

enum ProcessingType {
    SingleToken = 1,
    MultiToken = 2
};

#endif	/* NODETYPE_H */


text:
/*jshint camelcase: false */
'use strict';

var AuthInterceptor = function($q, $cookies, $injector) {
	return {
		request: function(config) {
			config.headers = config.headers || {};
			if ($cookies.auth_token) {
				config.headers['x-session-token'] = $cookies.auth_token;
			}
			return config;
		},
		responseError: function(response) {
			if (response.status === 401) {
				$injector.get('$state').go('auth.login');
			}
			return $q.reject(response);
		}
	};
};

AuthInterceptor.$inject = ['$q', '$cookies', '$injector'];
module.exports = AuthInterceptor;


text:
package org.lambda4j.function.to;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class ThrowableToIntFunctionTest {

    @Test
    void of_givenExpression_returnsFunctionalInterface() {
        ThrowableToIntFunction<String, Throwable> function = ThrowableToIntFunction.of(Integer::parseInt);
        Assertions.assertNotNull(function);
    }

    @Test
    void of_givenNull_returnsNull() {
        ThrowableToIntFunction<String, Throwable> function = ThrowableToIntFunction.of(null);
        Assertions.assertNull(function);
    }
}


text:
'use strict';
var express = require('express'),
    nodeHeroku = express(),
    app = express(),
    bodyParser = require('body-parser'),
    config = require('./lib/config'),
    db = require('./lib/db'),
    users = require('./lib/users/routes');

users.routes(nodeHeroku);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(express.static(__dirname + '/public'));
app.set('port', process.env.PORT || config.get('server:port'));
app.set('json spaces', config.get('json:spaces'));

var prefix = config.get('server:prefix') || '/';
app.use(prefix, nodeHeroku);

var server = app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + server.address().port);
});

db.init();
module.exports = app;


text:
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

/*
 * Author : eldawy@google.com (Mohamed Eldawy)
 * ucnvsel.h
 *
 * Purpose: To generate a list of encodings capable of handling
 * a given Unicode text
 *
 * Started 09-April-2008
 */

#ifndef __ICU_UCNV_SEL_H__
#define __ICU_UCNV_SEL_H__

#include "unicode/utypes.h"

#if !UCONFIG_NO_CONVERSION

#include "unicode/uset.h"
#include "unicode/utf16.h"
#include "unicode/uenum.h"
#include "unicode/ucnv.h"
#include "unicode/localpointer.h"

/**
 * \file
 *
 * A converter selector is built with a set of encoding/charset names
 * and given an input string returns the set of names of the
 * corresponding converters which can convert the string.
 *
 * A converter selector can be serialized into a buffer and reopened
 * from the serialized form.
 */

/**
 * @{
 * The selector data structure
 */
struct UConverterSelector;
typedef struct UConverterSelector UConverterSelector;
/** @} */

/**
 * Open a selector.
 * If converterListSize is 0, build for all available converters.
 * If excludedCodePoints is NULL, don't exclude any code points.
 *
 * @param converterList a pointer to encoding names needed to be involved.
 *                      Can be NULL if converterListSize==0.
 *                      The list and the names will be cloned, and the caller
 *                      retains ownership of the original.
 * @param converterListSize number of encodings in above list.
 *                          If 0, builds a selector for all available converters.
 * @param excludedCodePoints a set of code points to be excluded from consideration.
 *                           That is, excluded code points in a string do not change
 *                           the selection result. (They might be handled by a callback.)
 *                           Use NULL to exclude nothing.
 * @param whichSet what converter set to use? Use this to determine whether
 *                 to consider only roundtrip mappings or also fallbacks.
 * @param status an in/out ICU UErrorCode
 * @return the new selector
 *
 * @stable ICU 4.2
 */
U_STABLE UConverterSelector* U_EXPORT2
ucnvsel_open(const char* const*  converterList, int32_t converterListSize,
             const USet* excludedCodePoints,
             const UConverterUnicodeSet whichSet, UErrorCode* status);

/**
 * Closes a selector.
 * If any Enumerations were returned by ucnv_select*, they become invalid.
 * They can be closed before or after calling ucnv_closeSelector,
 * but should never be used after the selector is closed.
 *
 * @see ucnv_selectForString
 * @see ucnv_selectForUTF8
 *
 * @param sel selector to close
 *
 * @stable ICU 4.2
 */
U_STABLE void U_EXPORT2
ucnvsel_close(UConverterSelector *sel);

#if U_SHOW_CPLUSPLUS_API

U_NAMESPACE_BEGIN

/**
 * \class LocalUConverterSelectorPointer
 * "Smart pointer" class, closes a UConverterSelector via ucnvsel_close().
 * For most methods see the LocalPointerBase base class.
 *
 * @see LocalPointerBase
 * @see LocalPointer
 * @stable ICU 4.4
 */
U_DEFINE_LOCAL_OPEN_POINTER(LocalUConverterSelectorPointer, UConverterSelector, ucnvsel_close);

U_NAMESPACE_END

#endif

/**
 * Open a selector from its serialized form.
 * The buffer must remain valid and unchanged for the lifetime of the selector.
 * This is much faster than creating a selector from scratch.
 * Using a serialized form from a different machine (endianness/charset) is supported.
 *
 * @param buffer pointer to the serialized form of a converter selector;
 *               must be 32-bit-aligned
 * @param length the capacity of this buffer (can be equal to or larger than
 *               the actual data length)
 * @param status an in/out ICU UErrorCode
 * @return the new selector
 *
 * @stable ICU 4.2
 */
U_STABLE UConverterSelector* U_EXPORT2
ucnvsel_openFromSerialized(const void* buffer, int32_t length, UErrorCode* status);

/**
 * Serialize a selector into a linear buffer.
 * The serialized form is portable to different machines.
 *
 * @param sel selector to consider
 * @param buffer pointer to 32-bit-aligned memory to be filled with the
 *               serialized form of this converter selector
 * @param bufferCapacity the capacity of this buffer
 * @param status an in/out ICU UErrorCode
 * @return the required buffer capacity to hold serialize data (even if the call fails
 *         with a U_BUFFER_OVERFLOW_ERROR, it will return the required capacity)
 *
 * @stable ICU 4.2
 */
U_STABLE int32_t U_EXPORT2
ucnvsel_serialize(const UConverterSelector* sel,
                  void* buffer, int32_t bufferCapacity, UErrorCode* status);

/**
 * Select converters that can map all characters in a UTF-16 string,
 * ignoring the excluded code points.
 *
 * @param sel a selector
 * @param s UTF-16 string
 * @param length length of the string, or -1 if NUL-terminated
 * @param status an in/out ICU UErrorCode
 * @return an enumeration containing encoding names.
 *         The returned encoding names and their order will be the same as
 *         supplied when building the selector.
 *
 * @stable ICU 4.2
 */
U_STABLE UEnumeration * U_EXPORT2
ucnvsel_selectForString(const UConverterSelector* sel,
                        const UChar *s, int32_t length, UErrorCode *status);

/**
 * Select converters that can map all characters in a UTF-8 string,
 * ignoring the excluded code points.
 *
 * @param sel a selector
 * @param s UTF-8 string
 * @param length length of the string, or -1 if NUL-terminated
 * @param status an in/out ICU UErrorCode
 * @return an enumeration containing encoding names.
 *         The returned encoding names and their order will be the same as
 *         supplied when building the selector.
 *
 * @stable ICU 4.2
 */
U_STABLE UEnumeration * U_EXPORT2
ucnvsel_selectForUTF8(const UConverterSelector* sel,
                      const char *s, int32_t length, UErrorCode *status);

#endif  /* !UCONFIG_NO_CONVERSION */

#endif  /* __ICU_UCNV_SEL_H__ */


text:
package com.cloudera.oryx.app.serving.als.model;

import org.junit.Test;

import com.cloudera.oryx.app.als.MultiRescorerProvider;
import com.cloudera.oryx.app.als.RescorerProvider;
import com.cloudera.oryx.common.OryxTest;

public class ALSServingModelManagerTest extends OryxTest {

  @Test
  public void testLoad() {
    assertNull(ALSServingModelManager.loadRescorerProviders(null));
    RescorerProvider provider = ALSServingModelManager.loadRescorerProviders(
        "com.cloudera.oryx.app.serving.als.model.NullProvider2");
    assertTrue(provider instanceof NullProvider2);
    RescorerProvider multiProvider = ALSServingModelManager.loadRescorerProviders(
        "com.cloudera.oryx.app.serving.als.model.NullProvider2," +
        "com.cloudera.oryx.app.serving.als.model.NullProvider2");
    assertTrue(multiProvider instanceof MultiRescorerProvider);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testNoClass() {
    ALSServingModelManager.loadRescorerProviders("noSuchClass");
  }

  @Test(expected = IllegalArgumentException.class)
  public void testBadInstantiation() {
    ALSServingModelManager.loadRescorerProviders("com.cloudera.oryx.app.als.ErrorProvider");
  }

  @Test(expected = IllegalArgumentException.class)
  public void testWrongClass() {
    ALSServingModelManager.loadRescorerProviders(
        "com.cloudera.oryx.app.als.AbstractRescorerProviderTest");
  }

}


text:
static NSDateComponentsFormatter *SegmentDurationDateComponentsFormatter(void)
{
    static NSDateComponentsFormatter *s_dateComponentsFormatter;
    static dispatch_once_t s_onceToken;
    dispatch_once(&s_onceToken, ^{
        s_dateComponentsFormatter = [[NSDateComponentsFormatter alloc] init];
        s_dateComponentsFormatter.allowedUnits = NSCalendarUnitSecond | NSCalendarUnitMinute;
        s_dateComponentsFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
    });
    return s_dateComponentsFormatter;
}

@interface SegmentCollectionViewCell ()

@property (nonatomic) MediaSegment *segment;
@property (nonatomic, weak) SRGMediaPlayerController *mediaPlayerController;

@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@property (nonatomic, weak) IBOutlet UILabel *titleLabel;
@property (nonatomic, weak) IBOutlet UILabel *timeLabel;
@property (nonatomic, weak) IBOutlet UIProgressView *progressView;

@end

@implementation SegmentCollectionViewCell

#pragma mark Getters and setters

- (void)setSegment:(MediaSegment *)segment mediaPlayerController:(SRGMediaPlayerController *)mediaPlayerController
{
    self.segment = segment;
    self.mediaPlayerController = mediaPlayerController;

    self.titleLabel.text = segment.name;
    self.imageView.image = [UIImage imageNamed:@"artwork"];

    CMTimeRange segmentTimeRange = [self.segment.srg_markRange timeRangeForMediaPlayerController:mediaPlayerController];
    if (SRG_CMTIMERANGE_IS_NOT_EMPTY(segmentTimeRange)) {
        self.timeLabel.hidden = NO;
        self.timeLabel.text = [SegmentDurationDateComponentsFormatter() stringFromTimeInterval:CMTimeGetSeconds(segmentTimeRange.duration)];
    }
    else {
        self.timeLabel.hidden = YES;
    }

    self.alpha = segment.srg_isBlocked ? 0.5f : 1.f;
}

#pragma mark Overrides

- (void)prepareForReuse
{
    [super prepareForReuse];
    self.progressView.progress = 0.f;
}

#pragma mark UI

- (void)updateAppearanceWithTime:(CMTime)time selectedSegment:(MediaSegment *)selectedSegment
{
    CMTimeRange segmentTimeRange = [self.segment.srg_markRange timeRangeForMediaPlayerController:self.mediaPlayerController];

    float progress = (CMTimeGetSeconds(time) - CMTimeGetSeconds(segmentTimeRange.start)) / (CMTimeGetSeconds(segmentTimeRange.duration));
    progress = fminf(1.f, fmaxf(0.f, progress));

    self.progressView.progress = progress;

    UIColor *selectionColor = [UIColor colorWithRed:128.f / 255.f green:0.f / 255.f blue:0.f / 255.f alpha:1.f];
    if (selectedSegment) {
        self.backgroundColor = (self.segment == selectedSegment) ? selectionColor : UIColor.blackColor;
    }
    else {
        self.backgroundColor = (progress != 0.f && progress != 1.f) ? selectionColor : UIColor.blackColor;
    }
}

@end


text:
package utils

func ParseCheckboxBoolean(value string) bool {
	if value == "true" {
		return true
	}
	return false
}


text:
<?php

declare(strict_types=1);

namespace Core\Controller;

use Core\Domain\Common\Command\CommandInterface;
use Core\Domain\Common\Query\QueryInterface;
use Core\Infrastructure\Common\MessengerCommandBus;
use Core\Infrastructure\Common\MessengerQueryBus;
use Core\Infrastructure\Response\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\SerializerInterface;

abstract class AbstractController
{
    private MessengerCommandBus $commandBus;
    private JsonResponse $jsonResponse;
    private SerializerInterface $serializer;
    private MessengerQueryBus $queryBus;

    public function __construct(
        MessengerCommandBus $commandBus,
        JsonResponse $jsonResponse,
        SerializerInterface $serializer,
        MessengerQueryBus $queryBus
    ) {
        $this->commandBus = $commandBus;
        $this->jsonResponse = $jsonResponse;
        $this->serializer = $serializer;
        $this->queryBus = $queryBus;
    }

    protected function serialize(object $object, array $context = [], string $format = 'json'): string
    {
        return $this->serializer->serialize($object, $format, $context);
    }

    protected function deserialize(string $payload, string $type, string $format = 'json'): object
    {
        return $this->serializer->deserialize($payload, $type, $format);
    }

    protected function response(string $bodyResponse, int $statusCode = 201): Response
    {
        return $this->jsonResponse->response($bodyResponse, $statusCode);
    }

    protected function dispatch(CommandInterface $command): void
    {
        $this->commandBus->dispatch($command);
    }

    protected function handle(QueryInterface $command): ?object
    {
        return $this->queryBus->handle($command);
    }
}


text:
package ch.heigvd.amt.guat.selenium.pages;

import org.openqa.selenium.WebDriver;

/**
 * This class is used to test the registration page in the Gary application.
 *
 * @author Jan Purro
 */
public class RegisterAccountPage extends AbstractGaryPage
{

    public RegisterAccountPage(WebDriver driver)
    {
        super(driver);
        if (!"Registration".equals(driver.getTitle()))
        {
            throw new IllegalStateException("This is not the correct page");
        }
    }

}


text:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE Rank2Types #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Database.Persist.Sql.Orphan.PersistStore
  ( withRawQuery
  , BackendKey(..)
  , toSqlKey
  , fromSqlKey
  , getFieldName
  , getTableName
  , tableDBName
  , fieldDBName
  ) where

import Database.Persist
import Database.Persist.Sql.Types
import Database.Persist.Sql.Raw
import Database.Persist.Sql.Util (dbIdColumns, keyAndEntityColumnNames)
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import qualified Data.Text as T
import Data.Text (Text, unpack)
import Data.Monoid (mappend, (<>))
import Control.Monad.IO.Class
import Data.ByteString.Char8 (readInteger)
import Data.Maybe (isJust)
import Data.List (find)
import Control.Monad.Trans.Reader (ReaderT, ask)
import Data.Acquire (with)
import Data.Int (Int64)
import Web.PathPieces (PathPiece)
import Web.HttpApiData (ToHttpApiData, FromHttpApiData)
import Database.Persist.Sql.Class (PersistFieldSql)
import qualified Data.Aeson as A
import Control.Exception.Lifted (throwIO)

withRawQuery :: MonadIO m
             => Text
             -> [PersistValue]
             -> C.Sink [PersistValue] IO a
             -> ReaderT SqlBackend m a
withRawQuery sql vals sink = do
    srcRes <- rawQueryRes sql vals
    liftIO $ with srcRes (C.$$ sink)

toSqlKey :: ToBackendKey SqlBackend record => Int64 -> Key record
toSqlKey = fromBackendKey . SqlBackendKey

fromSqlKey :: ToBackendKey SqlBackend record => Key record -> Int64
fromSqlKey = unSqlBackendKey . toBackendKey

whereStmtForKey :: PersistEntity record => SqlBackend -> Key record -> Text
whereStmtForKey conn k =
    T.intercalate " AND "
  $ map (<> "=? ")
  $ dbIdColumns conn entDef
  where
    entDef = entityDef $ dummyFromKey k

-- | get the SQL string for the table that a PeristEntity represents
-- Useful for raw SQL queries
--
-- Your backend may provide a more convenient tableName function
-- which does not operate in a Monad
getTableName :: forall record m.
             ( PersistEntity record
             , PersistEntityBackend record ~ SqlBackend
             , Monad m
             ) => record -> ReaderT SqlBackend m Text
getTableName rec = do
    conn <- ask
    return $ connEscapeName conn $ tableDBName rec

-- | useful for a backend to implement tableName by adding escaping
tableDBName :: forall record.
            ( PersistEntity record
            , PersistEntityBackend record ~ SqlBackend
            ) => record -> DBName
tableDBName rec = entityDB $ entityDef (Just rec)

-- | get the SQL string for the field that an EntityField represents
-- Useful for raw SQL queries
--
-- Your backend may provide a more convenient fieldName function
-- which does not operate in a Monad
getFieldName :: forall record typ m.
             ( PersistEntity record
             , PersistEntityBackend record ~ SqlBackend
             , Monad m
             )
             => EntityField record typ -> ReaderT SqlBackend m Text
getFieldName rec = do
    conn <- ask
    return $ connEscapeName conn $ fieldDBName rec

-- | useful for a backend to implement fieldName by adding escaping
fieldDBName :: forall record typ. (PersistEntity record) => EntityField record typ -> DBName
fieldDBName = fieldDB . persistFieldDef

instance PersistStore SqlBackend where
    newtype BackendKey SqlBackend = SqlBackendKey { unSqlBackendKey :: Int64 }
        deriving (Show, Read, Eq, Ord, Num, Integral, PersistField, PersistFieldSql, PathPiece, ToHttpApiData, FromHttpApiData, Real, Enum, Bounded, A.ToJSON, A.FromJSON)

    update _ [] = return ()
    update k upds = do
        conn <- ask
        let go'' n Assign = n <> "=?"
            go'' n Add = T.concat [n, "=", n, "+?"]
            go'' n Subtract = T.concat [n, "=", n, "-?"]
            go'' n Multiply = T.concat [n, "=", n, "*?"]
            go'' n Divide = T.concat [n, "=", n, "/?"]
            go'' _ (BackendSpecificUpdate up) = error $ T.unpack $ "BackendSpecificUpdate" `mappend` up `mappend` "not supported"
        let go' (x, pu) = go'' (connEscapeName conn x) pu
        let wher = whereStmtForKey conn k
        let sql = T.concat
                [ "UPDATE "
                , connEscapeName conn $ tableDBName $ recordTypeFromKey k
                , " SET "
                , T.intercalate "," $ map (go' . go) upds
                , " WHERE "
                , wher
                ]
        rawExecute sql $
            map updatePersistValue upds `mappend` keyToValues k
      where
        go x = (fieldDB $ updateFieldDef x, updateUpdate x)

    insert val = do
        conn <- ask
        let esql = connInsertSql conn t vals
        key <-
            case esql of
                ISRSingle sql -> withRawQuery sql vals $ do
                    x <- CL.head
                    case x of
                        Just [PersistInt64 i] -> case keyFromValues [PersistInt64 i] of
                            Left err -> error $ "SQL insert: keyFromValues: PersistInt64 " `mappend` show i `mappend` " " `mappend` unpack err
                            Right k -> return k
                        Nothing -> error $ "SQL insert did not return a result giving the generated ID"
                        Just vals' -> case keyFromValues vals' of
                            Left _ -> error $ "Invalid result from a SQL insert, got: " ++ show vals'
                            Right k -> return k

                ISRInsertGet sql1 sql2 -> do
                    rawExecute sql1 vals
                    withRawQuery sql2 [] $ do
                        mm <- CL.head
                        let m = maybe
                                  (Left $ "No results from ISRInsertGet: " `mappend` tshow (sql1, sql2))
                                  Right mm

                        -- TODO: figure out something better for MySQL
                        let convert x =
                                case x of
                                    [PersistByteString i] -> case readInteger i of -- mssql
                                                            Just (ret,"") -> [PersistInt64 $ fromIntegral ret]
                                                            _ -> x
                                    _ -> x
                            -- Yes, it's just <|>. Older bases don't have the
                            -- instance for Either.
                            onLeft Left{} x = x
                            onLeft x _ = x

                        case m >>= (\x -> keyFromValues x `onLeft` keyFromValues (convert x)) of
                            Right k -> return k
                            Left err -> throw $ "ISRInsertGet: keyFromValues failed: " `mappend` err
                ISRManyKeys sql fs -> do
                    rawExecute sql vals
                    case entityPrimary t of
                       Nothing -> error $ "ISRManyKeys is used when Primary is defined " ++ show sql
                       Just pdef ->
                            let pks = map fieldHaskell $ compositeFields pdef
                                keyvals = map snd $ filter (\(a, _) -> let ret=isJust (find (== a) pks) in ret) $ zip (map fieldHaskell $ entityFields t) fs
                            in  case keyFromValues keyvals of
                                    Right k -> return k
                                    Left e  -> error $ "ISRManyKeys: unexpected keyvals result: " `mappend` unpack e

        return key
      where
        tshow :: Show a => a -> Text
        tshow = T.pack . show
        throw = liftIO . throwIO . userError . T.unpack
        t = entityDef $ Just val
        vals = map toPersistValue $ toPersistFields val

    insertMany [] = return []
    insertMany vals = do
        conn <- ask

        case connInsertManySql conn of
            Nothing -> mapM insert vals
            Just insertManyFn -> do
                case insertManyFn ent valss of
                    ISRSingle sql -> rawSql sql (concat valss)
                    _ -> error "ISRSingle is expected from the connInsertManySql function"
                where
                    ent = entityDef vals
                    valss = map (map toPersistValue . toPersistFields) vals

    insertMany_ [] = return ()
    insertMany_ vals = do
        conn <- ask
        let sql = T.concat
                [ "INSERT INTO "
                , connEscapeName conn (entityDB t)
                , "("
                , T.intercalate "," $ map (connEscapeName conn . fieldDB) $ entityFields t
                , ") VALUES ("
                , T.intercalate "),(" $ replicate (length valss) $ T.intercalate "," $ map (const "?") (entityFields t)
                , ")"
                ]
        rawExecute sql (concat valss)
      where
        t = entityDef vals
        valss = map (map toPersistValue . toPersistFields) vals

    replace k val = do
        conn <- ask
        let t = entityDef $ Just val
        let wher = whereStmtForKey conn k
        let sql = T.concat
                [ "UPDATE "
                , connEscapeName conn (entityDB t)
                , " SET "
                , T.intercalate "," (map (go conn . fieldDB) $ entityFields t)
                , " WHERE "
                , wher
                ]
            vals = map toPersistValue (toPersistFields val) `mappend` keyToValues k
        rawExecute sql vals
      where
        go conn x = connEscapeName conn x `T.append` "=?"

    insertKey = insrepHelper "INSERT"

    repsert key value = do
        mExisting <- get key
        case mExisting of
          Nothing -> insertKey key value
          Just _ -> replace key value

    get k = do
        conn <- ask
        let t = entityDef $ dummyFromKey k
        let cols = T.intercalate ","
                 $ map (connEscapeName conn . fieldDB) $ entityFields t
            noColumns :: Bool
            noColumns = null $ entityFields t
        let wher = whereStmtForKey conn k
        let sql = T.concat
                [ "SELECT "
                , if noColumns then "*" else cols
                , " FROM "
                , connEscapeName conn $ entityDB t
                , " WHERE "
                , wher
                ]
        withRawQuery sql (keyToValues k) $ do
            res <- CL.head
            case res of
                Nothing -> return Nothing
                Just vals ->
                    case fromPersistValues $ if noColumns then [] else vals of
                        Left e -> error $ "get " ++ show k ++ ": " ++ unpack e
                        Right v -> return $ Just v

    delete k = do
        conn <- ask
        rawExecute (sql conn) (keyToValues k)
      where
        wher conn = whereStmtForKey conn k
        sql conn = T.concat
            [ "DELETE FROM "
            , connEscapeName conn $ tableDBName $ recordTypeFromKey k
            , " WHERE "
            , wher conn
            ]

dummyFromKey :: Key record -> Maybe record
dummyFromKey = Just . recordTypeFromKey

recordTypeFromKey :: Key record -> record
recordTypeFromKey _ = error "dummyFromKey"

insrepHelper :: (MonadIO m, PersistEntity val)
             => Text
             -> Key val
             -> val
             -> ReaderT SqlBackend m ()
insrepHelper command k record = do
    conn <- ask
    let columnNames = keyAndEntityColumnNames entDef conn
    rawExecute (sql conn columnNames) vals
  where
    entDef = entityDef $ Just record
    sql conn columnNames = T.concat
        [ command
        , " INTO "
        , connEscapeName conn (entityDB entDef)
        , "("
        , T.intercalate "," columnNames
        , ") VALUES("
        , T.intercalate "," (map (const "?") columnNames)
        , ")"
        ]
    vals = entityValues (Entity k record)

updateFieldDef :: PersistEntity v => Update v -> FieldDef
updateFieldDef (Update f _ _) = persistFieldDef f
updateFieldDef (BackendUpdate {}) = error "updateFieldDef did not expect BackendUpdate"

updatePersistValue :: Update v -> PersistValue
updatePersistValue (Update _ v _) = toPersistValue v
updatePersistValue (BackendUpdate {}) = error "updatePersistValue did not expect BackendUpdate"


text:
package rules

import (
	"github.com/gin-gonic/gin"
	"github.com/nu7hatch/gouuid"
	m "github.com/numeralti/go-bimetrics/model"
	"github.com/spf13/viper"
	l "log"
	"net/http"
)

// Run the rules server
func Run() {

	l.Println("Run")

	var listenOn = viper.GetString("listenOn")
	var serviceName = viper.GetString("serviceName")

	svc := new(SimpleRuleService)

	r := gin.Default()

	//r.Use(gin.Logger())
	//r.Use(gin.Recovery())

	r.GET("/", func(c *gin.Context) {
		urls := gin.H{"health": "/health", "rules": "/v1/rules"}
		c.JSON(http.StatusOK, urls)
	})

	r.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status": "ok",
			"name":   serviceName,
		})
	})

	r.POST("/v1/rules", func(c *gin.Context) {
		//TODO: Move this to a handler func so it can be tested independently
		var request m.RuleAPIRequest
		if c.BindJSON(&request) == nil {

			response, err := svc.Check(request)

			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"status": "error:" + err.Error()})
				return
			}

			//response := new(m.RuleApiResponse)

			u, _ := uuid.NewV4()

			response.ID = u.String()
			response.ClientRequestID = request.ClientRequestID
			response.CorrelationID = request.CorrelationID
			c.JSON(http.StatusOK, response)

		}

		//svc := enrichService{logger}
		//svc.Enrich()

	})

	r.Run(listenOn)

}


text:
// This utility will portably force the volume of the default microphone to max.

#include <stdio.h>

#include "modules/audio_device/include/audio_device.h"

using webrtc::AudioDeviceModule;

#if defined(_WIN32)
#define DEFAULT_INPUT_DEVICE (AudioDeviceModule::kDefaultCommunicationDevice)
#else
#define DEFAULT_INPUT_DEVICE (0)
#endif

int main(int /*argc*/, char* /*argv*/ []) {
  // Create and initialize the ADM.
  rtc::scoped_refptr<AudioDeviceModule> adm(
      AudioDeviceModule::Create(AudioDeviceModule::kPlatformDefaultAudio));
  if (!adm.get()) {
    fprintf(stderr, "Failed to create Audio Device Module.\n");
    return 1;
  }
  if (adm->Init() != 0) {
    fprintf(stderr, "Failed to initialize Audio Device Module.\n");
    return 1;
  }
  if (adm->SetRecordingDevice(DEFAULT_INPUT_DEVICE) != 0) {
    fprintf(stderr, "Failed to set the default input device.\n");
    return 1;
  }
  if (adm->InitMicrophone() != 0) {
    fprintf(stderr, "Failed to to initialize the microphone.\n");
    return 1;
  }

  // Set mic volume to max.
  uint32_t max_vol = 0;
  if (adm->MaxMicrophoneVolume(&max_vol) != 0) {
    fprintf(stderr, "Failed to get max volume.\n");
    return 1;
  }
  if (adm->SetMicrophoneVolume(max_vol) != 0) {
    fprintf(stderr, "Failed to set mic volume.\n");
    return 1;
  }

  return 0;
}


text: New repo for bugzilla2github tool: https://github.com/berestovskyy/bugzilla2github


text:
@interface SkillsTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *skillNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *skillLevelLabel;
@property (weak, nonatomic) IBOutlet UIButton *skillDeleteButton;
@property (weak, nonatomic) IBOutlet UIButton *skillAddButton;
@property (weak, nonatomic) IBOutlet UIButton *skillEditButton;

@end


text:
title: UI for long running requests
disqus_identifier: 2006-01-ui-for-long-running-requests
comments: true
---

We have an application that given certain inputs can take quite a while to run. The previous solution that we had in place to let the user know what was going on was a popup window that went away after the page completed loading.

This solution has been wrought with problems, not the least of which was the numerous different alogrithms that popup blockers use. One of the worst problems with this technique was the popup window not going away if the task encountered an error.

Mark Wagner has a fantastic [piece of code][1] ([demo][2]) that hooks into the onbeforeunload event to overlay a processing message onto the page. The neat thing about this technique is that there is not much more to do, since everything is automatically unloaded when the next page loads.

This is a fantastic technique and I look forward to finding other useful places to use this.

On a side note, dont you find it funny that the Google popup blocker pops up a popup to tell you that popups are being blocked??

[1]:http://blogs.crsw.com/mark/articles/642.aspx
[2]:http://blogs.crsw.com/mark/samples/BusyBoxDemo/Default.aspx


text:
layout: post
title:  "SFPC: Day 56 - Back to NYC"
date:   2016-12-04 20:00:00 -0400
categories: back to NYC, hoboken, selfie, cemetery lunch, picnic
---

Had a great porchside breakfast, packed up and said goodbye to our hosts, zoomed down the Taconic and we were back in NYC by late afternoon. Returned the car in Hoboken and traveled back to Brooklyn to get some sleep.

![lunch](/images/IMG_6746.jpg)

-----

Today

Had a great breakfast, took a short walk, said goodbye to our Airbnb host, Didi... and then we hit the road, headed back to NYC.

Long-ish drive back to NYC from Poughkeepsie. The Taconic State Highway is one curvy beast. Listening to music, eating chocolate crackers, sunlight streaming in.

Driving back into the city. Highways and byways.

*Car selfie. Sad for our getaway weekend to be over.*

![Car selfie](/images/IMG_6748.jpg)

-----

I Love Hoboken(No Jokin'), Part Two

Hoboken is great. It feels like a place where actual people live. After dropping off the car, I walked to the Spa Diner and had a milkshake and did some writing. Then I had some really bad chicken parmigiana with spaghetti. I walked outside and witnessed the end of a bar fight in front of a bar down the street. There was lots of yelling and some pushing and then some more yelling. No one was hurt, I don't think. It was entertaining and kind of scary. Reminds me of Dallas.

-----

**For Breakfast:**

Baked eggs with bacon, caramelized onion, mozzarella, and toast. So good. Should've photo-documented it.

**For Lunch:**

Chicken cutlets on a cemetery sidewalk.

![lunch](/images/IMG_6746.jpg)

**For Dinner:**

Chicken parm with spaghetti at Spa Diner in Hoboken.