text:
package org.hawkular.bus.common.consumer;

import javax.jms.Message;

import org.hawkular.bus.common.BasicMessage;
import org.hawkular.bus.common.BasicMessageWithExtraData;
import org.jboss.logging.Logger;

/**
 * A message listener that expects to receive a JSON-encoded BasicMessage or one of its subclasses. Implementors need
 * not worry about the JSON decoding as it is handled for you
 *
 * Subclasses must override one and only one of the {@link #onBasicMessage(BasicMessageWithExtraData)} or
 * {@link #onBasicMessage(BasicMessage)} methods.
 *
 * This processes fire-and-forget requests - that is, the request message is processed with no response being sent back
 * to the sender.
 *
 * @author John Mazzitelli
 */

public abstract class BasicMessageListener<T extends BasicMessage> extends AbstractBasicMessageListener<T> {
    private static final Logger log = Logger.getLogger(BasicMessageListener.class);

    public BasicMessageListener() {
        super();
    }

    protected BasicMessageListener(Class<T> jsonDecoderRing) {
        super(jsonDecoderRing);
    }

    protected BasicMessageListener(ClassLoader basicMessageClassLoader) {
        super(basicMessageClassLoader);
    }

    @Override
    public void onMessage(Message message) {

        log.debugf("Received raw message [%s]", message);

        BasicMessageWithExtraData<T> msgWithExtraData = parseMessage(message);
        if (msgWithExtraData == null) {
            return; // either we are not to process this message or some error occurred, so we skip it
        }

        onBasicMessage(msgWithExtraData);
        return;
    };

    /**
     * Subclasses implement this method to process the received message.
     *
     * If subclasses would rather just receive the {@link BasicMessage}, it can do so by
     * overriding {@link #onBasicMessage(BasicMessage)} and leaving this method as-is (that is,
     * do NOT override this method).
     *
     * @param msgWithExtraData the basic message received with any extra data that came with it
     */
    protected void onBasicMessage(BasicMessageWithExtraData<T> msgWithExtraData) {
        onBasicMessage(msgWithExtraData.getBasicMessage()); // delegate
    }

    /**
     * Subclasses can implement this method rather than {@link #onBasicMessage(BasicMessageWithExtraData)}
     * if they only expect to receive a {@link BasicMessage} with no additional data.
     *
     * If this method is overridden by subclasses, then the {@link #onBasicMessage(BasicMessageWithExtraData)}
     * should not be.
     *
     * This base implementation is a no-op.
     *
     * @param basicMessage the basic message received
     */
    protected void onBasicMessage(T basicMessage) {
        // no op
    }
}


text:
var shell   = require('shelljs'),
    fs      = require('fs'),
    url     = require('url'),
    underscore = require('underscore'),
    semver = require('semver'),
    PluginInfoProvider = require('../PluginInfoProvider'),
    plugins = require('./util/plugins'),
    CordovaError  = require('../CordovaError'),
    events = require('../events'),
    metadata = require('./util/metadata'),
    path    = require('path'),
    Q       = require('q'),
    registry = require('./registry/registry');
var cordovaUtil = require('../cordova/util');

// Cache of PluginInfo objects for plugins in search path.
var localPlugins = null;

// possible options: link, subdir, git_ref, client, expected_id
// Returns a promise.
module.exports = fetchPlugin;
function fetchPlugin(plugin_src, plugins_dir, options) {
    // Ensure the containing directory exists.
    shell.mkdir('-p', plugins_dir);

    options = options || {};
    options.subdir = options.subdir || '.';
    options.searchpath = options.searchpath || [];
    if ( typeof options.searchpath === 'string' ) {
        options.searchpath = options.searchpath.split(path.delimiter);
    }

    var pluginInfoProvider = options.pluginInfoProvider || new PluginInfoProvider();

    // clone from git repository
    var uri = url.parse(plugin_src);

    // If the hash exists, it has the form from npm: http://foo.com/bar#git-ref[:subdir]
    // NB: No leading or trailing slash on the subdir.
    if (uri.hash) {
        var result = uri.hash.match(/^#([^:]*)(?::\/?(.*?)\/?)?$/);
        if (result) {
            if (result[1])
                options.git_ref = result[1];
            if (result[2])
                options.subdir = result[2];

            // Recurse and exit with the new options and truncated URL.
            var new_dir = plugin_src.substring(0, plugin_src.indexOf('#'));
            return fetchPlugin(new_dir, plugins_dir, options);
        }
    }

    return Q.when().then(function() {
        // If it looks like a network URL, git clone it.
        if ( uri.protocol && uri.protocol != 'file:' && uri.protocol[1] != ':' && !plugin_src.match(/^\w+:\\/)) {
            events.emit('log', 'Fetching plugin "' + plugin_src + '" via git clone');
            if (options.link) {
                events.emit('log', '--link is not supported for git URLs and will be ignored');
            }

            return plugins.clonePluginGit(plugin_src, plugins_dir, options)
            .then(function(dir) {
                return {
                    pinfo: pluginInfoProvider.get(dir),
                    dest: dir,
                    fetchJsonSource: {
                        type: 'git',
                        url:  plugin_src,
                        subdir: options.subdir,
                        ref: options.git_ref
                    }
                };
            });
        }
        // If it's not a network URL, it's either a local path or a plugin ID.
        var plugin_dir = cordovaUtil.fixRelativePath(path.join(plugin_src, options.subdir));

        return Q.when().then(function() {
            if (fs.existsSync(plugin_dir)) {
                return {
                    pinfo: pluginInfoProvider.get(plugin_dir),
                    fetchJsonSource: {
                        type: 'local',
                        path: plugin_dir
                    }
                };
            }
            // If there is no such local path, it's a plugin id or id@versionspec.
            // First look for it in the local search path (if provided).
            var pinfo = findLocalPlugin(plugin_src, options.searchpath, pluginInfoProvider);
            if (pinfo) {
                events.emit('verbose', 'Found ' + plugin_src + ' at ' + pinfo.dir);
                return {
                    pinfo: pinfo,
                    fetchJsonSource: {
                        type: 'local',
                        path: pinfo.dir
                    }
                };
            } else if ( options.noregistry ) {
                return Q.reject(new CordovaError(
                    'Plugin ' + plugin_src + ' not found locally. ' +
                    'Note, plugin registry was disabled by --noregistry flag.'
                ));
            }
            // If not found in local search path, fetch from the registry.
            events.emit('log', 'Fetching plugin "' + plugin_src + '" via plugin registry');
            return registry.fetch([plugin_src], options.client)
            .then(function(dir) {
                return {
                    pinfo: pluginInfoProvider.get(dir),
                    fetchJsonSource: {
                        type: 'registry',
                        id: plugin_src
                    }
                };
            });
        }).then(function(result) {
            options.plugin_src_dir = result.pinfo.dir;
            return Q.when(copyPlugin(result.pinfo, plugins_dir, options.link && result.fetchJsonSource.type == 'local'))
            .then(function(dir) {
                result.dest = dir;
                return result;
            });
        });
    }).then(function(result){
        checkID(options.expected_id, result.pinfo);
        metadata.save_fetch_metadata(plugins_dir, result.pinfo.id, { source: result.fetchJsonSource });
        return result.dest;
    });
}

// Helper function for checking expected plugin IDs against reality.
function checkID(expected_id, pinfo) {
    if (!expected_id) return;
    var id = pinfo.id;
    // if id with specific version provided, append version to id
    if (expected_id.split('@').length > 1) {
        id = id + '@' + pinfo.version;
    }
    if (expected_id != id) {
        throw new Error('Expected fetched plugin to have ID "' + expected_id + '" but got "' + id + '".');
    }
}

// Note, there is no cache invalidation logic for local plugins.
// As of this writing loadLocalPlugins() is never called with different
// search paths and such case would not be handled properly.
function loadLocalPlugins(searchpath, pluginInfoProvider) {
    if (localPlugins) {
        // localPlugins already populated, nothing to do.
        // just in case, make sure it was loaded with the same search path
        if ( !underscore.isEqual(localPlugins.searchpath, searchpath) ) {
            var msg =
                'loadLocalPlugins called twice with different search paths.' +
                'Support for this is not implemented.';
            throw new Error(msg);
        }
        return;
    }

    // Populate localPlugins object.
    localPlugins = {};
    localPlugins.searchpath = searchpath;
    localPlugins.plugins = {};

    searchpath.forEach(function(dir) {
        var ps = pluginInfoProvider.getAllWithinSearchPath(dir);
        ps.forEach(function(p) {
            var versions = localPlugins.plugins[p.id] || [];
            versions.push(p);
            localPlugins.plugins[p.id] = versions;
        });
    });
}

// If a plugin is fund in local search path, return a PluginInfo for it.
// Ignore plugins that don't satisfy the required version spec.
// If several versions are present in search path, return the latest.
// Examples of accepted plugin_src strings:
//      org.apache.cordova.file
//      org.apache.cordova.file@>=1.2.0
function findLocalPlugin(plugin_src, searchpath, pluginInfoProvider) {
    loadLocalPlugins(searchpath, pluginInfoProvider);
    var id = plugin_src;
    var versionspec = '*';
    if (plugin_src.indexOf('@') != -1) {
        var parts = plugin_src.split('@');
        id = parts[0];
        versionspec = parts[1];
    }

    var latest = null;
    var versions = localPlugins.plugins[id];

    if (!versions) return null;

    versions.forEach(function(pinfo) {
        // Ignore versions that don't satisfy the the requested version range.
        if (!semver.satisfies(pinfo.version, versionspec)) {
            return;
        }
        if (!latest) {
            latest = pinfo;
            return;
        }
        if (semver.gt(pinfo.version, latest.version)) {
            latest = pinfo;
        }

    });
    return latest;
}

// Copy or link a plugin from plugin_dir to plugins_dir/plugin_id.
function copyPlugin(pinfo, plugins_dir, link) {
    var plugin_dir = pinfo.dir;
    var dest = path.join(plugins_dir, pinfo.id);
    shell.rm('-rf', dest);
    if (link) {
        var isRelativePath = plugin_dir[1] != ':' && plugin_dir[0] != path.sep;
        var fixedPath = isRelativePath ? path.join(path.relative(plugins_dir, process.env.PWD || process.cwd()), plugin_dir) : plugin_dir;
        events.emit('verbose', 'Linking "' + dest + '" => "' + fixedPath + '"');
        fs.symlinkSync(fixedPath, dest, 'dir');
    } else {
        shell.mkdir('-p', dest);
        events.emit('verbose', 'Copying plugin "' + plugin_dir + '" => "' + dest + '"');
        shell.cp('-R', path.join(plugin_dir, '*') , dest);
    }
    return dest;
}

redpajama_set_name: RedPajamaGithub


text:
import cPickle as pickle
import gzip
import logging as loggers
import os
from threading import Thread

import filelock
import numpy as np
import theano
import theano.tensor as T

import deepy
from deepy.utils.map_dict import MapDict
from deepy.layers.block import Block
from deepy.layers.layer import NeuralLayer
from deepy.utils import dim_to_var
from deepy.trainers.train_logger import TrainLogger

logging = loggers.getLogger("network")
save_logger = loggers.getLogger("saving")

DEEPY_MESSAGE = "deepy version = %s" % deepy.__version__

def save_network_params(params, path):
    lock = filelock.FileLock(path)
    with lock:
        if path.endswith('gz'):
            opener = gzip.open if path.lower().endswith('.gz') else open
            handle = opener(path, 'wb')
            pickle.dump(params, handle)
            handle.close()
        elif path.endswith('uncompressed.npz'):
            np.savez(path, *params)
        elif path.endswith('.npz'):
            np.savez_compressed(path, *params)
        else:
            raise Exception("File format of %s is not supported, use '.gz' or '.npz' or '.uncompressed.gz'" % path)

class NeuralNetwork(object):
    """
    The base class of neural networks.
    """

    def __init__(self, input_dim, input_tensor=None):
        logging.info(DEEPY_MESSAGE)
        self.input_dim = input_dim
        self.input_tensor = input_tensor
        self.parameter_count = 0

        self.parameters = []
        self.free_parameters = []

        self.training_updates = []
        self.updates = []

        self.input_variables = []
        self.target_variables = []

        self.training_callbacks = []
        self.testing_callbacks = []
        self.epoch_callbacks = []

        self.layers = []
        self._test_outputs = []
        self._test_output = None
        self._output_keys = None

        self._hidden_outputs = []
        self.training_monitors = []
        self.testing_monitors = []

        self.setup_variables()
        self.train_logger = TrainLogger()

    def stack_layer(self, layer, no_setup=False):
        """
        Stack a neural layer.
        :type layer: NeuralLayer
        :param no_setup: whether the layer is already initialized
        """
        if layer.name:
            layer.name += "%d" % (len(self.layers) + 1)
        if not self.layers:
            layer.init(self.input_dim, no_prepare=no_setup)
        else:
            layer.init(self.layers[-1].output_dim, no_prepare=no_setup)
        self._output = layer.compute_tensor(self._output)
        self._test_output = layer.compute_tensor(self._test_output)
        self._hidden_outputs.append(self._output)
        self.register_layer(layer)
        self.layers.append(layer)

    def register(self, *layers):
        """
        Register multiple layers as the components of the network.
        The parameter of those layers will be trained.
        But the output of the layer will not be stacked.
        """
        for layer in layers:
            self.register_layer(layer)

    def register_layer(self, layer):
        """
        Register the layer so that it's param will be trained.
        But the output of the layer will not be stacked.
        """
        if type(layer) == Block:
            layer.fix()
        self.parameter_count += layer.parameter_count
        self.parameters.extend(layer.parameters)
        self.free_parameters.extend(layer.free_parameters)
        self.training_monitors.extend(layer.training_monitors)
        self.testing_monitors.extend(layer.testing_monitors)
        self.updates.extend(layer.updates)
        self.training_updates.extend(layer.training_updates)
        self.input_variables.extend(layer.external_inputs)
        self.target_variables.extend(layer.external_targets)

        self.training_callbacks.extend(layer.training_callbacks)
        self.testing_callbacks.extend(layer.testing_callbacks)
        self.epoch_callbacks.extend(layer.epoch_callbacks)

    def first_layer(self):
        """
        Return first layer.
        """
        return self.layers[0] if self.layers else None

    def stack(self, *layers):
        """
        Stack layers.
        """
        for layer in layers:
            self.stack_layer(layer)
        return self

    def prepare_training(self):
        """
        This function will be called before training.
        """
        self.report()

    def monitor_layer_outputs(self):
        """
        Monitoring the outputs of each layer.
        Useful for troubleshooting convergence problems.
        """
        for layer, hidden in zip(self.layers, self._hidden_outputs):
            self.training_monitors.append(('mean(%s)' % (layer.name), abs(hidden).mean()))

    @property
    def all_parameters(self):
        """
        Return all parameters.
        """
        params = []
        params.extend(self.parameters)
        params.extend(self.free_parameters)

        return params

    def setup_variables(self):
        """
        Set up variables.
        """
        if self.input_tensor:
            if type(self.input_tensor) == int:
                x = dim_to_var(self.input_tensor, name="x")
            else:
                x = self.input_tensor
        else:
            x = T.matrix('x')
        self.input_variables.append(x)
        self._output = x
        self._test_output = x

    def _compile(self):
        if not hasattr(self, '_compute'):
            if isinstance(self._test_outputs, dict):
                self._output_keys, out_tensors = map(list, zip(*self._test_outputs.items()))
                if self._test_output:
                    self._output_keys.insert(0, "cost")
                    out_tensors.insert(0, self._test_output)
            elif isinstance(self._test_outputs, list) and self._test_outputs:
                out_tensors = self._test_outputs
                if self._test_output:
                    out_tensors.insert(0, self._test_output)
            else:
                out_tensors = self._test_output
            self._compute = theano.function(
                filter(lambda x: x not in self.target_variables, self.input_variables),
                out_tensors, updates=self.updates, allow_input_downcast=True)

    def compute(self, *x):
        """
        Return network output.
        """
        self._compile()
        outs = self._compute(*x)
        if self._output_keys:
            return MapDict(dict(zip(self._output_keys, outs)))
        else:
            return outs

    @property
    def output(self):
        """
        Return output variable.
        """
        return self._output

    @property
    def test_output(self):
        """
        Return output variable in test time.
        """
        return self._test_output

    @property
    def cost(self):
        """
        Return cost variable.
        """
        return T.constant(0)

    @property
    def test_cost(self):
        """
        Return cost variable in test time.
        """
        return self.cost

    def save_params(self, path, new_thread=False):
        """
        Save parameters to file.
        """
        save_logger.info(path)
        param_variables = self.all_parameters
        params = [p.get_value().copy() for p in param_variables]
        if new_thread:
            thread = Thread(target=save_network_params, args=(params, path))
            thread.start()
        else:
            save_network_params(params, path)
        self.train_logger.save(path)

    def load_params(self, path, exclude_free_params=False):
        """
        Load parameters from file.
        """
        if not os.path.exists(path): return;
        logging.info("loading parameters from %s" % path)
        # Decide which parameters to load
        if exclude_free_params:
            params_to_load = self.parameters
        else:
            params_to_load = self.all_parameters
        # Load parameters
        if path.endswith(".gz"):
            opener = gzip.open if path.lower().endswith('.gz') else open
            handle = opener(path, 'rb')
            saved_params = pickle.load(handle)
            handle.close()
            # Write parameters
            for target, source in zip(params_to_load, saved_params):
                logging.info('%s: setting value %s', target.name, source.shape)
                target.set_value(source)
        elif path.endswith(".npz"):
            arrs = np.load(path)
            # Write parameters
            for target, idx in zip(params_to_load, range(len(arrs.keys()))):
                source = arrs['arr_%d' % idx]
                logging.info('%s: setting value %s', target.name, source.shape)
                target.set_value(source)
        else:
            raise Exception("File format of %s is not supported, use '.gz' or '.npz' or '.uncompressed.gz'" % path)

        self.train_logger.load(path)

    def report(self):
        """
        Print network statistics.
        """
        logging.info("network inputs: %s", " ".join(map(str, self.input_variables)))
        logging.info("network targets: %s", " ".join(map(str, self.target_variables)))
        logging.info("network parameters: %s", " ".join(map(str, self.all_parameters)))
        logging.info("parameter count: %d", self.parameter_count)

    def epoch_callback(self):
        """
        Callback for each epoch.
        """
        for cb in self.epoch_callbacks:
            cb()

    def training_callback(self):
        """
        Callback for each training iteration.
        """
        for cb in self.training_callbacks:
            cb()

    def testing_callback(self):
        """
        Callback for each testing iteration.
        """
        for cb in self.training_callbacks:
            cb()


text:
<?php

/**
 * Booting the framework
 *
 * Routing and setup for controllers.
 *
 * @package    Prank
 * @subpackage Core
 */
class Boot {
	private $url        = null;
	private $controller = null;
	private $action     = null;
	private $config     = null;
	private $params     = [];
	private $route      = [];

/**
 * Constructor
 *
 * Initializes the framework, and starts the Controller.
 *
 * @param  string $start_point Full path of index.php (__FILE__)
 * @param  string $config_dir  Full path to the config directory
 * @return void
 */
	public function __construct($start_point, $config_dir = false) {
		ob_start();

		require 'base.php';
		require 'registry.php';
		require 'config.php';

		$registry         = Registry::instance();
		$config           = new Config($start_point, $config_dir);
		$this->config     = $config;
		$registry->config = $config;

		use_helper('inflector.php', 'base.php');

		spl_autoload_register('Boot::autoload');

		ini_set('include_path', $config['core'].$config['ps'].$config['app'].$config['ps'].'.');
		$this->set_error_reporting($config['state']);

		$this->url        = isset($_GET['url']) ? $_GET['url'] : '/';
		$registry->router = new Router($config);
		$this->route      = $registry->router->parse_url($this->url);

		$this->parse_route();

		$this->run_controller();

		ob_end_flush();
	}

/**
 * Autoloader function
 *
 * Registered in the constructor.
 *
 * @param  string $class_name Name of the class to be loaded
 * @return void
 **/
	public static function autoload($class) {
		if (substr($class, -10, 10) !== 'Controller') {

			if (class_exists($class) === false) {
				$class_underscore = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $class));
				$class = str_replace('_', DIRECTORY_SEPARATOR, $class_underscore);

				$registry = Registry::instance();

				if (is_file($registry->config['core'].$class.'.php')) {
					require $registry->config['core'].$class.'.php';
				}

				if (is_file($registry->config['models'].$class_underscore.'.model.php')) {
					require $registry->config['models'].$class_underscore.'.model.php';
				}
			}
		}
	}

/**
 * Sets error reporting
 *
 * Depending on $state sets proper error_reporting level.
 *
 * @param  string $state Envoirnmental state
 * @return void
 */
	private function set_error_reporting($state) {
		switch ($state) {
			case 'development':
				error_reporting(E_ALL | E_NOTICE | E_DEPRECATED | E_STRICT);
				break;
			case 'test':
				error_reporting(E_ALL);
				break;
			case 'production':
			default:
				error_reporting(0);
				break;
		}
	}

/**
 * Parses the route, loads controller
 *
 * @return void
 */
	private function parse_route() {
		$route      = $this->route;
		$controller = null;
		$action     = null;
		$params     = [];

		if (isset($route['controller']) && is_file($this->config['controllers'].down($route['controller']).'.controller.php')) {
			$controller = $route['controller'];
			unset($route['controller']);
		} else {
			$controller = 'Http404';
		}

		$this->load_controller($controller);

		if (isset($route['action']) && is_action_of($route['action'], $controller)) {
			$action = $route['action'];
			unset($route['action']);
		} else {
			$action = 'index';
		}

		$params = $route;

		$this->controller = $controller;
		$this->action     = $action;
		$this->params     = $params;
	}

/**
 * Runs the Controller determined by Boot::parse_url
 *
 * @return void
 */
	private function run_controller() {
		try {
			$registry          = Registry::instance();
			$controller_name   = to_controller($this->controller);
			$controller_object = new $controller_name($this->action, $this->action, $this->params, $this->controller, $this->config);

			$registry->current_controller = $controller_object;

			$controller_object->run($this->action, $this->action, $this->params, $this->controller, $this->config);

		} catch (Exception $e) {
			echo '
Exception: '.$e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().".
\n",
				str_replace("\n", "\n
", $e->getTraceAsString());
		}
	}

/**
 * Loads the controller file
 *
 * @return boolean
 * @param  string  $name Shortname of the controller.
 **/
	private function load_controller($name) {
		if (class_exists(ucfirst($name).'Controller') === false) {
			if (is_file($this->config['controllers'].down($name).'.controller.php')) {
				require $this->config['controllers'].down($name).'.controller.php';
				return true;
			} elseif (is_file(file_path($this->config['core'].'stubs', 'app', 'controllers', down($name).'.controller.php'))) {
				require file_path($this->config['core'].'stubs', 'app', 'controllers', down($name).'.controller.php');
				return true;
			} else {
				throw new Exception('File for '.ucfirst($name).'Controller was not found.');
			}
		}
	}

/**
 * Backwards compatible instantiation of the Boot class.
 *
 * @param  string $start_point
 * @param  string $config_dir
 * @return void
 */
	public static function run($start_point, $config_dir = false) {
		return new self($start_point, $config_dir);
	}
}

?>


text:
using DeveImageOptimizer.Helpers;
using ExifLibrary;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace DeveImageOptimizer.ImageOperations
{
    public static class ImageExifComparer
    {
        private static Dictionary<ExifTag, Func<ExifProperty, ExifPropertyCollection<ExifProperty>, bool>> _validExifTags = new()
        {
            { ExifTag.Make, ExifPropertyEqualInDestination },
            { ExifTag.Model, ExifPropertyEqualInDestination },
            { ExifTag.Orientation, ExifPropertyEqualInDestinationOrCompletelyMissingIfProp1ConformsToValue(prop1 => (prop1 as ExifEnumProperty<Orientation>)?.Tag == ExifTag.Orientation && (prop1 as ExifEnumProperty<Orientation>)?.Value == Orientation.Normal)},
            { ExifTag.Software, ExifPropertyEqualInDestination },
            { ExifTag.DateTime, ExifPropertyEqualInDestination },
            { ExifTag.ExposureTime, ExifPropertyEqualInDestination },
            { ExifTag.FNumber, ExifPropertyEqualInDestination },
            { ExifTag.ExposureProgram, ExifPropertyEqualInDestination },
            { ExifTag.ISOSpeedRatings, ExifPropertyEqualInDestination },
            { ExifTag.DateTimeOriginal, ExifPropertyEqualInDestination },
            { ExifTag.DateTimeDigitized, ExifPropertyEqualInDestination },
            { ExifTag.BrightnessValue, ExifPropertyEqualInDestination },
            { ExifTag.ExposureBiasValue, ExifPropertyEqualInDestination },
            { ExifTag.MaxApertureValue, ExifPropertyEqualInDestination },
            { ExifTag.MeteringMode, ExifPropertyEqualInDestination },
            { ExifTag.LightSource, ExifPropertyEqualInDestination },
            { ExifTag.Flash, ExifPropertyEqualInDestination },
            { ExifTag.FocalLength, ExifPropertyEqualInDestination },
            { ExifTag.MakerNote, ExifPropertyEqualInDestination },
            { ExifTag.UserComment, ExifPropertyEqualInDestination },
            { ExifTag.PixelXDimension, ExifPropertyEqualInDestination },
            { ExifTag.PixelYDimension, ExifPropertyEqualInDestination },
            { ExifTag.ExposureMode, ExifPropertyEqualInDestination },
            { ExifTag.WhiteBalance, ExifPropertyEqualInDestination },
            { ExifTag.DigitalZoomRatio, ExifPropertyEqualInDestination },
            { ExifTag.FocalLengthIn35mmFilm, ExifPropertyEqualInDestination },
            { ExifTag.SceneCaptureType, ExifPropertyEqualInDestination },
            { ExifTag.Contrast, ExifPropertyEqualInDestination },
            { ExifTag.Saturation, ExifPropertyEqualInDestination },
            { ExifTag.Sharpness, ExifPropertyEqualInDestination },
            { ExifTag.LensSpecification, ExifPropertyEqualInDestination },
            { ExifTag.LensModel, ExifPropertyEqualInDestination },

            { ExifTag.ApertureValue, ExifPropertyEqualInDestination }
        };

        public static async Task<bool> AreImageExifDatasEqual(string image1Path, string image2Path)
        {
            if (!File.Exists(image1Path))
            {
                throw new FileNotFoundException("Could not find Image1", image1Path);
            }

            if (!File.Exists(image2Path))
            {
                throw new FileNotFoundException("Could not find Image2", image2Path);
            }

            if (!FileTypeHelper.IsJpgFile(image1Path) || !FileTypeHelper.IsJpgFile(image2Path))
            {
                //For now only handle Jpg images
                return true;
            }

            var image1 = await ImageFile.FromFileAsync(image1Path);
            var image2 = await ImageFile.FromFileAsync(image2Path);

            return AreImageExifDatasEqual(image1, image2);
        }

        public static bool AreImageExifDatasEqual(ImageFile image1, ImageFile image2)
        {
            foreach (var prop1 in image1.Properties)
            {
                if (_validExifTags.TryGetValue(prop1.Tag, out var checkerFunc))
                {
                    if (!checkerFunc(prop1, image2.Properties))
                    {
                        return false;
                    }
                }
            }

            return true;
        }

        private static bool ExifPropertyEqualInDestination(ExifProperty prop1, ExifPropertyCollection<ExifProperty> collection)
        {
            //We check if all properties exist in the other image, but not the other way around.
            //For some reason the optimizers add some exif data in some cases
            return collection.Any(prop2 =>
                prop1.Name == prop2.Name &&
                prop1.Tag == prop2.Tag &&
                prop1.IFD == prop2.IFD &&
                prop1.Interoperability.TagID == prop2.Interoperability.TagID &&
                prop1.Interoperability.TypeID == prop2.Interoperability.TypeID &&
                prop1.Interoperability.Count == prop2.Interoperability.Count &&
                Enumerable.SequenceEqual(prop1.Interoperability.Data, prop2.Interoperability.Data)
                );
        }

        private static bool ExifPropertyEqualInDestinationOrCompletelyMissing(ExifProperty prop1, ExifPropertyCollection<ExifProperty> collection)
        {
            //First check if it is exactly equal, if not make sure it is completely missing
            var result = ExifPropertyEqualInDestination(prop1, collection);
            if (result)
            {
                return true;
            }
            if (collection.All(prop2 => prop1.Tag != prop2.Tag))
            {
                return true;
            }
            return false;
        }

        private static Func<ExifProperty, ExifPropertyCollection<ExifProperty>, bool> ExifPropertyEqualInDestinationOrCompletelyMissingIfProp1ConformsToValue(Func<ExifProperty, bool> conformsToValue)
        {
            return new Func<ExifProperty, ExifPropertyCollection<ExifProperty>, bool>((prop1, collection) =>
            {
                //First check if it is exactly equal, if not make sure it is completely missing
                var result = ExifPropertyEqualInDestination(prop1, collection);
                if (result)
                {
                    return true;
                }
                if (conformsToValue(prop1) && collection.All(prop2 => prop1.Tag != prop2.Tag))
                {
                    return true;
                }
                return false;
            });
        }
    }
}


text:
from random import Random

from engine.utils.dictutils import MappingView
from engine.user.user_stash import Stash

__author__ = 'kollad'

class UserStash(Stash):
    def __init__(self, state, **kwargs):
        self.state = state
        data = state['resources']
        super(UserStash, self).__init__(data, **kwargs)
        self._data = data

    def copy(self):
        return UserStash(self.state)

class UserState(MappingView):
    def __init__(self, data, *args, random, **kwargs):
        super(UserState, self).__init__(*args, **kwargs)
        self._data = data or {}
        self._content_manager = None
        if random is None:
            self.random = Random(0)
        else:
            self.random = random

    @property
    def content_manager(self):
        if self._content_manager is None:
            raise ValueError("Content manager is not set")
        return self._content_manager

    def set_content_manager(self, manager):
        self._content_manager = manager

    def __setitem__(self, item, value):
        self._data[item] = value

    def __delitem__(self, key):
        del self._data[key]

    def __getitem__(self, item):
        return self._data[item]

    def setdefault(self, key, default=None):
        if key not in self:
            self[key] = default
        return self[key]

    def increase_id_counter(self):
        count = self.get('_id_counter', 0)
        self['_id_counter'] = count + 1
        return count

    def make_stash(self, data):
        return Stash(data, random=self.random)

    @property
    def stash(self):
        """
        :return: User stash
        :rtype: UserStash
        """
        return UserStash(self._data, random=self.random)

    @stash.setter
    def stash(self, stash):
        """
        :type stash: UserStash
        :param stash: Stash
        """
        self._stash = stash

    @property
    def map(self):
        return self.setdefault('map', {})

    @property
    def tilegrid(self):
        """
        Information about cells that are not passable

        :return:
        """
        return self.map.setdefault('tilegrid', [])

    @property
    def layers(self):
        """
        Map layers

        :return:
        """
        return self.map.setdefault('layers', {})

    @property
    def objects(self):
        """
        Map placed objects

        :return:
        """
        return self.map.setdefault('objects', {})

    @property
    def open_cells(self):
        """
        Opened cells

        :return:
        """
        return self.map.setdefault('open_cells', [])

    @property
    def areas(self):
        """
        Map 3x3 areas

        :return:
        """
        return self.map.setdefault('areas', [])

    @property
    def active_processes(self):
        """
        Active interaction processes

        :return:
        """
        return self.setdefault('active_processes', {})


text:
package sympath

import (
	"log"
	"os"
	"path/filepath"
	"sort"

	"github.com/pkg/errors"
)

// Walk walks the file tree rooted at root, calling walkFn for each file or directory
// in the tree, including root. All errors that arise visiting files and directories
// are filtered by walkFn. The files are walked in lexical order, which makes the
// output deterministic but means that for very large directories Walk can be
// inefficient. Walk follows symbolic links.
func Walk(root string, walkFn filepath.WalkFunc) error {
	info, err := os.Lstat(root)
	if err != nil {
		err = walkFn(root, nil, err)
	} else {
		err = symwalk(root, info, walkFn)
	}
	if err == filepath.SkipDir {
		return nil
	}
	return err
}

// readDirNames reads the directory named by dirname and returns
// a sorted list of directory entries.
func readDirNames(dirname string) ([]string, error) {
	f, err := os.Open(dirname)
	if err != nil {
		return nil, err
	}
	names, err := f.Readdirnames(-1)
	f.Close()
	if err != nil {
		return nil, err
	}
	sort.Strings(names)
	return names, nil
}

// symwalk recursively descends path, calling walkFn.
func symwalk(path string, info os.FileInfo, walkFn filepath.WalkFunc) error {
	// Recursively walk symlinked directories.
	if IsSymlink(info) {
		resolved, err := filepath.EvalSymlinks(path)
		if err != nil {
			return errors.Wrapf(err, "error evaluating symlink %s", path)
		}
		log.Printf("found symbolic link in path: %s resolves to %s. Contents of linked file included and used", path, resolved)
		if info, err = os.Lstat(resolved); err != nil {
			return err
		}
		if err := symwalk(path, info, walkFn); err != nil && err != filepath.SkipDir {
			return err
		}
		return nil
	}

	if err := walkFn(path, info, nil); err != nil {
		return err
	}

	if !info.IsDir() {
		return nil
	}

	names, err := readDirNames(path)
	if err != nil {
		return walkFn(path, info, err)
	}

	for _, name := range names {
		filename := filepath.Join(path, name)
		fileInfo, err := os.Lstat(filename)
		if err != nil {
			if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
				return err
			}
		} else {
			err = symwalk(filename, fileInfo, walkFn)
			if err != nil {
				if (!fileInfo.IsDir() && !IsSymlink(fileInfo)) || err != filepath.SkipDir {
					return err
				}
			}
		}
	}
	return nil
}

// IsSymlink is used to determine if the fileinfo is a symbolic link.
func IsSymlink(fi os.FileInfo) bool {
	return fi.Mode()&os.ModeSymlink != 0
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _09.intdoublesttring
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please choose a type:");
            Console.WriteLine("1 --> int");
            Console.WriteLine("2 --> double");
            Console.WriteLine("3 --> string");
            int choice = int.Parse(Console.ReadLine());
            if (choice == 1)
            {
                Console.WriteLine("Please enter a int:");
                int intNum = int.Parse(Console.ReadLine());
                intNum = intNum + 1;
                Console.WriteLine(intNum);
            }
            else if (choice == 2)
            {
                Console.WriteLine("Please enter a double:");
                double doubleNum = double.Parse(Console.ReadLine());
                doubleNum = doubleNum + 1;
                Console.WriteLine(doubleNum);
            }
            else if (choice == 3)
            {
                Console.WriteLine("Please enter a string:");
                string str = Console.ReadLine();
                str += "*";
                Console.WriteLine(str);
            }
            else
            {
                Console.WriteLine("Invalid Input!");
            }
        }
    }
}


text:
import codecs
import os

from mountain.join import expand_manifest
from mountain.split import split_combined_document

class TestExpandManifest(object):

    def test_expand_manifest_simple(self):

        combined_document_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "fixtures",
            "simple",
            "screenplay.fountain")

        actual = expand_manifest(
            os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                "fixtures",
                "simple",
                "manifest.fountain"),
            combined_document_path)

        expected_contents = codecs.open(
            combined_document_path,
            "r",
            "utf-8"
        ).read()

        expected = [{"path": combined_document_path, "contents": expected_contents}]

        assert actual == expected

    def test_expand_manifest_complex(self):

        combined_document_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "fixtures",
            "complex",
            "screenplay.fountain")

        actual = expand_manifest(
            os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                "fixtures",
                "complex",
                "manifest.fountain"),
            combined_document_path)

        expected_contents = codecs.open(
            os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                "fixtures",
                "complex",
                "screenplay.fountain"),
            "r",
            "utf-8"
        ).read()

        expected = [{"path": combined_document_path, "contents": expected_contents}]

        assert actual == expected

class TestSplitCombinedDocument(object):

    def test_split_combined_document(self):

        actual = split_combined_document(
            os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                "fixtures",
                "simple",
                "manifest.fountain"),
            os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                "fixtures",
                "simple",
                "screenplay.fountain"))

        expected = list()

        for path in ["fixtures/simple/intro.fountain",
                     "fixtures/simple/inciting-incident.fountain",
                     "fixtures/simple/the-end.fountain",
                     "fixtures/simple/manifest.fountain"]:

            path = os.path.join(
                       os.path.dirname(os.path.realpath(__file__)),
                       path)

            expected.append(
                {"path": path,
                 "contents": codecs.open(path, "r", "utf-8").read()})

        assert actual == expected


text:
(function ($) {

	// default player values
	mejs.MepDefaults = {
		// url to poster (to fix iOS 3.x)
		poster: '',
		// default if the <video width> is not specified
		defaultVideoWidth: 480,
		// default if the <video height> is not specified
		defaultVideoHeight: 270,
		// if set, overrides <video width>
		videoWidth: -1,
		// if set, overrides <video height>
		videoHeight: -1,
		// width of audio player
		audioWidth: 400,
		// height of audio player
		audioHeight: 30,
		// initial volume when the player starts (overrided by user cookie)
		startVolume: 0.8,
		// useful for <audio> player loops
		loop: false,
		// resize to media dimensions
		enableAutosize: true,
		// features to show
		features: ['playpause','progress','current','duration','tracks','volume','fullscreen']
	};

	mejs.mepIndex = 0;

	// wraps a MediaElement object in player controls
	mejs.MediaElementPlayer = function($media, o) {
		// enforce object, even without "new" (via John Resig)
		if ( !(this instanceof mejs.MediaElementPlayer) ) {
			return new mejs.MediaElementPlayer($media, o);
		}

		var
			t = this,
			mf = mejs.MediaFeatures;

		t.$media = $($media);
		t.options = $.extend({},mejs.MepDefaults,o);
		t.isVideo = (t.$media[0].tagName.toLowerCase() == 'video');

		if (mf.isiPad || mf.isiPhone) {
			// add controls and stop
			t.$media.attr('controls', 'controls');

			// fix Apple bug
			t.$media.removeAttr('poster');

			// override Apple's autoplay override for iPads
			if (mf.isiPad && t.$media[0].getAttribute('autoplay') !== null) {
				t.$media[0].load();
				t.$media[0].play();
			}

			// don't do the rest
			return;
		} else if (mf.isAndroid && t.isVideo) {

			// Android fails when there are multiple types
			// <video>
			// <source src="file.mp4" type="video/mp4" />
			// <source src="file.webm" type="video/webm" />
			// </video>
			if (t.$media.find('source').length > 0) {
				// find an mp4 and make it the root element source
				t.$media[0].src = t.$media.find('source[src$="mp4"]').attr('src');
			}

			// attach a click event to the video and hope Android can play it
			t.$media.click(function() {
				t.$media[0].play();
			});

			return;

		} else {

			// remove native controls and use MEJS
			t.$media.removeAttr('controls');
		}

		t.init();

		return t;
	};

	// actual player
	mejs.MediaElementPlayer.prototype = {
		init: function() {

			var
				t = this,
				meOptions = $.extend(true, {}, t.options, {
					success: function(media, domNode) { t.meReady(media, domNode); },
					error: function(e) { t.handleError(e);}
				});

			// unique ID
			t.id = 'mep_' + mejs.mepIndex++;

			// build container
			t.container =
				$('
'+
					'
'+
						'

'+
						'

'+
						'

'+
						'

'+
					'
' +
				'
')
				.addClass(t.$media[0].className)
				.insertBefore(t.$media);

			// move the <video/video> tag into the right spot
			t.container.find('.mejs-mediaelement').append(t.$media);

			// find parts
			t.controls = t.container.find('.mejs-controls');
			t.layers = t.container.find('.mejs-layers');

			// determine the size
			if (t.isVideo) {
				// priority = videoWidth (forced), width attribute, defaultVideoWidth
				t.width = (t.options.videoWidth > 0) ? t.options.videoWidth : (t.$media[0].getAttribute('width') !== null) ? t.$media.attr('width') : t.options.defaultVideoWidth;
				t.height = (t.options.videoHeight > 0) ? t.options.videoHeight : (t.$media[0].getAttribute('height') !== null) ? t.$media.attr('height') : t.options.defaultVideoHeight;
			} else {
				t.width = t.options.audioWidth;
				t.height = t.options.audioHeight;
			}

			// set the size, while we wait for the plugins to load below
			t.setPlayerSize(t.width, t.height);

			// create MediaElementShim
			meOptions.pluginWidth = t.height;
			meOptions.pluginHeight = t.width;
			mejs.MediaElement(t.$media[0], meOptions);
		},

		// Sets up all controls and events
		meReady: function(media, domNode) {

			var t = this,
				f,
				feature;

			t.media = media;
			t.domNode = domNode;

			// two built in features
			t.buildposter(t, t.controls, t.layers, t.media);
			t.buildoverlay(t, t.controls, t.layers, t.media);

			// grab for use by feautres
			t.findTracks();

			// add user-defined features/controls
			for (f in t.options.features) {
				feature = t.options.features[f];
				if (t['build' + feature]) {
					try {
						t['build' + feature](t, t.controls, t.layers, t.media);
					} catch (e) {
						// TODO: report control error
					}
				}
			}

			// reset all layers and controls
			t.setPlayerSize(t.width, t.height);
			t.setControlsSize();

			// controls fade
			if (t.isVideo) {
				// show/hide controls
				t.container
					.bind('mouseenter', function () {
						t.controls.css('visibility','visible');
						t.controls.stop(true, true).fadeIn(200);
					})
					.bind('mouseleave', function () {
						if (!t.media.paused) {
							t.controls.stop(true, true).fadeOut(200, function() {
								$(this).css('visibility','hidden');
								$(this).css('display','block');
							});
						}
					});

				// resizer
				if (t.options.enableAutosize) {
					t.media.addEventListener('loadedmetadata', function(e) {
						// if the <video height> was not set and the options.videoHeight was not set
						// then resize to the real dimensions
						if (t.options.videoHeight <= 0 && t.$media[0].getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
							t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
							t.setControlsSize();
							t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
						}
					}, false);
				}
			}

			// ended for all
			t.media.addEventListener('ended', function (e) {
				t.media.setCurrentTime(0);
				t.media.pause();

				if (t.options.loop) {
					t.media.play();
				} else {
					t.controls.css('visibility','visible');
				}
			}, true);

			// webkit has trouble doing this without a delay
			setTimeout(function () {
				t.setControlsSize();
				t.setPlayerSize(t.width, t.height);
			}, 50);

			if (t.options.success) {
				t.options.success(t.media, t.domNode);
			}
		},

		setPlayerSize: function(width,height) {
			var t = this;

			// ie9 appears to need this (jQuery bug?)
			t.width = parseInt(width, 10);
			t.height = parseInt(height, 10);

			t.container
				.width(t.width)
				.height(t.height);

			t.layers.children('div.mejs-layer')
				.width(t.width)
				.height(t.height);
		},

		setControlsSize: function() {
			var t = this,
				usedWidth = 0,
				railWidth = 0,
				rail = t.controls.find('.mejs-time-rail'),
				total = t.controls.find('.mejs-time-total'),
				others = rail.siblings();

			// find the size of all the other controls besides the rail
			others.each(function() {
				if ($(this).css('position') != 'absolute') {
					usedWidth += $(this).outerWidth(true);
				}
			});
			// fit the rail into the remaining space
			railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.outerWidth(false));

			rail.width(railWidth);
			total.width(railWidth - (total.outerWidth(true) - total.width()));
		},

		buildposter: function(player, controls, layers, media) {
			var poster =
				$('
'+
					''+
				'
')
					.appendTo(layers),
				posterUrl = player.$media.attr('poster');

			if (player.options.poster != '') {
				poster.find('img').attr('src',player.options.poster);
			} else if (posterUrl !== '' && posterUrl != null) {
				poster.find('img').attr('src',posterUrl);
			} else {
				poster.hide();
			}

			media.addEventListener('play',function() {
				poster.hide();
			}, false);
		},

		buildoverlay: function(player, controls, layers, media) {
			if (!player.isVideo)
				return;

			var overlay =
				$('
'+
					'

'+
				'
')
				.appendTo(layers)
				.click(function() {
					if (media.paused) {
						media.play();
					} else {
						media.pause();
					}
				});

			media.addEventListener('play',function() {
				overlay.hide();
			}, false);
			media.addEventListener('pause',function() {
				overlay.show();
			}, false);
		},

		findTracks: function() {
			var t = this,
				tracktags = t.$media.find('track');

			// store for use by plugins
			t.tracks = [];
			tracktags.each(function() {
				t.tracks.push({
					srclang: $(this).attr('srclang').toLowerCase(),
					src: $(this).attr('src'),
					kind: $(this).attr('kind'),
					entries: [],
					isLoaded: false
				});
			});
		},
		changeSkin: function(className) {
			this.container[0].className = 'mejs-container ' + className;
			this.setPlayerSize();
			this.setControlsSize();
		},
		play: function() {
			this.media.play();
		},
		pause: function() {
			this.media.pause();
		},
		load: function() {
			this.media.load();
		},
		setMuted: function(muted) {
			this.media.setMuted(muted);
		},
		setCurrentTime: function(time) {
			this.media.setCurrentTime(time);
		},
		getCurrentTime: function() {
			return this.media.currentTime;
		},
		setVolume: function(volume) {
			this.media.setVolume(volume);
		},
		getVolume: function() {
			return this.media.volume;
		},
		setSrc: function(src) {
			this.media.setSrc(src);
		}
	};

	// turn into jQuery plugin
	jQuery.fn.mediaelementplayer = function (options) {
		return this.each(function () {
			return new mejs.MediaElementPlayer($(this), options);
		});
	};

	// push out to window
	window.MediaElementPlayer = mejs.MediaElementPlayer;

})(jQuery);

(function($) {
	// PLAY/pause BUTTON
	MediaElementPlayer.prototype.buildplaypause = function(player, controls, layers, media) {
		var play =
			$('
' +
				'' +
			'
')
			.appendTo(controls)
			.click(function() {
				if (media.paused) {
					media.play();
				} else {
					media.pause();
				}
			});

		media.addEventListener('play',function() {
			play.removeClass('mejs-play').addClass('mejs-pause');
		}, false);
		media.addEventListener('playing',function() {
			play.removeClass('mejs-play').addClass('mejs-pause');
		}, false);

		media.addEventListener('pause',function() {
			play.removeClass('mejs-pause').addClass('mejs-play');
		}, false);
		media.addEventListener('paused',function() {
			play.removeClass('mejs-pause').addClass('mejs-play');
		}, false);

	}
})(jQuery);
(function($) {
	// progress/loaded bar
	MediaElementPlayer.prototype.buildprogress = function(player, controls, layers, media) {

		$('
'+
			''+
				''+
				''+
				''+
				'' +
					'00:00' +
					'' +
				''+
			''+
		'
')
			.appendTo(controls);

		var total = controls.find('.mejs-time-total'),
			loaded  = controls.find('.mejs-time-loaded'),
			current  = controls.find('.mejs-time-current'),
			handle  = controls.find('.mejs-time-handle'),
			timefloat  = controls.find('.mejs-time-float'),
			timefloatcurrent  = controls.find('.mejs-time-float-current'),
			setProgress = function(e) {
				var
					target = e.target,
					percent = null;

				// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
				// to be anything other than 0. If the byte count is available we use this instead.
				// Browsers that support the else if do not seem to have the bufferedBytes value and
				// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
				if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
					percent = target.bufferedBytes / target.bytesTotal;
				}
				// need to account for a real array with multiple values (only Firefox 4 has this so far)
				else if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
					percent = target.buffered.end(0) / target.duration;
				}

				if (percent !== null) {
					// update loaded bar
					loaded.width(total.width() * percent);
				}
			},
			setCurrentTime = function(e) {

				if (media.currentTime && media.duration) {

					// update bar and handle
					var
						newWidth = total.width() * media.currentTime / media.duration,
						handlePos = newWidth - (handle.outerWidth(true) / 2);

					current.width(newWidth);
					handle.css('left', handlePos);
					timefloat.css('left', handlePos);
					timefloatcurrent.html( mejs.Utility.secondsToTimeCode(media.currentTime) );
				}

			},
			handleMouseMove = function (e) {
				// mouse position relative to the object
				var x = e.pageX,
					offset = total.offset(),
					width = total.outerWidth(),
					percentage = ((x - offset.left) / width),
					newTime = percentage * media.duration;

				media.setCurrentTime(newTime);
			},
			mouseIsDown = false;

		// handle clicks
		//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
		total
			.bind('mousedown', function (e) {
				handleMouseMove(e);
				mouseIsDown = true;
				return false;
			});

		$(document)
			.bind('mouseup', function (e) {
				mouseIsDown = false;
				//handleMouseMove(e);
			})
			.bind('mousemove', function (e) {
				if (mouseIsDown) {
					handleMouseMove(e);
				}
			});

		// loading
		media.addEventListener('progress', function (e) {
			setProgress(e);
		}, false);

		// current time
		media.addEventListener('timeupdate', function(e) {
			setProgress(e);
			setCurrentTime(e);
		}, false);
	}

})(jQuery);
(function($) {
	// current and duration 00:00 / 00:00
	MediaElementPlayer.prototype.buildcurrent = function(player, controls, layers, media) {
		$('
'+
				'00:00'+
			'
')
			.appendTo(controls);

		media.addEventListener('timeupdate',function() {
			if (media.currentTime) {
				controls.find('.mejs-currenttime').html(mejs.Utility.secondsToTimeCode(media.currentTime));
			}
		}, false);
	};

	MediaElementPlayer.prototype.buildduration = function(player, controls, layers, media) {
		if (controls.children().last().find('.mejs-currenttime').length > 0) {
			$('  |  '+
			   '00:00')
				.appendTo(controls.find('.mejs-time'));
		} else {

			$('
'+
				'00:00'+
			'
')
			.appendTo(controls);
		}

		media.addEventListener('timeupdate',function() {
			if (media.duration) {
				controls.find('.mejs-duration').html(mejs.Utility.secondsToTimeCode(media.duration));
			}
		}, false);
	};

})(jQuery);
(function($) {
	MediaElementPlayer.prototype.buildvolume = function(player, controls, layers, media) {
		var mute =
			$('
'+
				''+
				'
'+ // outer background
					'

'+ // line background
					'

'+ // current volume
					'

'+ // handle
				'
'+
			'
')
			.appendTo(controls),
		volumeSlider = mute.find('.mejs-volume-slider'),
		volumeTotal = mute.find('.mejs-volume-total'),
		volumeCurrent = mute.find('.mejs-volume-current'),
		volumeHandle = mute.find('.mejs-volume-handle'),

		positionVolumeHandle = function(volume) {

			var
				top = volumeTotal.height() - (volumeTotal.height() * volume);

			// handle
			volumeHandle.css('top', top - (volumeHandle.height() / 2));

			// show the current visibility
			volumeCurrent.height(volumeTotal.height() - top + parseInt(volumeTotal.css('top').replace(/px/,''),10));
			volumeCurrent.css('top',  top);
		},
		handleVolumeMove = function(e) {
			var
				railHeight = volumeTotal.height(),
				totalOffset = volumeTotal.offset(),
				totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
				newY = e.pageY - totalOffset.top,
				volume = (railHeight - newY) / railHeight

			// TODO: handle vertical and horizontal CSS
			// only allow it to move within the rail
			if (newY < 0)
				newY = 0;
			else if (newY > railHeight)
				newY = railHeight;

			// move the handle to match the mouse
			volumeHandle.css('top', newY - (volumeHandle.height() / 2) + totalTop );

			// show the current visibility
			volumeCurrent.height(railHeight-newY);
			volumeCurrent.css('top',newY+totalTop);

			// set mute status
			if (volume == 0) {
				media.setMuted(true);
				mute.removeClass('mejs-mute').addClass('mejs-unmute');
			} else {
				media.setMuted(false);
				mute.removeClass('mejs-unmute').addClass('mejs-mute');
			}

			volume = Math.max(0,volume);
			volume = Math.min(volume,1);

			// set the volume
			media.setVolume(volume);
		},
		mouseIsDown = false;

		// SLIDER
		volumeSlider
			.bind('mousedown', function (e) {
				handleVolumeMove(e);
				mouseIsDown = true;
				return false;
			});
		$(document)
			.bind('mouseup', function (e) {
				mouseIsDown = false;
			})
			.bind('mousemove', function (e) {
				if (mouseIsDown) {
					handleVolumeMove(e);
				}
			});

		// MUTE button
		mute.find('span').click(function() {
			if (media.muted) {
				media.setMuted(false);
				mute.removeClass('mejs-unmute').addClass('mejs-mute');
				positionVolumeHandle(1);
			} else {
				media.setMuted(true);
				mute.removeClass('mejs-mute').addClass('mejs-unmute');
				positionVolumeHandle(0);
			}
		});

		// listen for volume change events from other sources
		media.addEventListener('volumechange', function(e) {
			if (!mouseIsDown) {
				positionVolumeHandle(e.target.volume);
			}
		}, true);

		// set initial volume
		//player.options.startVolume = Math.min(Math.max(0,player.options.startVolume),1);
		media.setVolume(player.options.startVolume);
	}

})(jQuery);
(function($) {
	MediaElementPlayer.prototype.buildfullscreen = function(player, controls, layers, media) {

		if (!player.isVideo)
			return;

		var
			isFullScreen = false,
			normalHeight = 0,
			normalWidth = 0,
			container = player.container,
			fullscreenBtn =
				$('

')
				.appendTo(controls)
				.click(function() {
					setFullScreen(!isFullScreen);
				}),
			setFullScreen = function(goFullScreen) {
				switch (media.pluginType) {
					case 'flash':
					case 'silverlight':
						media.setFullscreen(goFullScreen);
						break;
					case 'native':

						if (mejs.MediaFeatures.hasNativeFullScreen) {
							if (goFullScreen) {
								media.webkitEnterFullScreen();
							} else {
								media.webkitExitFullScreen();
							}
						} else {
							if (goFullScreen) {

								// store
								normalHeight = player.$media.height();
								normalWidth = player.$media.width();

								// make full size
								container
									.addClass('mejs-container-fullscreen')
									.width('100%')
									.height('100%')
									.css('z-index', 1000);

								player.$media
									.width('100%')
									.height('100%');

								layers.children('div')
									.width('100%')
									.height('100%');

								fullscreenBtn
									.removeClass('mejs-fullscreen')
									.addClass('mejs-unfullscreen');

								player.setControlsSize();
							} else {

								container
									.removeClass('mejs-container-fullscreen')
									.width(normalWidth)
									.height(normalHeight)
									.css('z-index', 1);

								player.$media
									.width(normalWidth)
									.height(normalHeight);

								layers.children('div')
									.width(normalWidth)
									.height(normalHeight);

								fullscreenBtn
									.removeClass('mejs-unfullscreen')
									.addClass('mejs-fullscreen');

								player.setControlsSize();
							}
						}
				}
				isFullScreen = goFullScreen;
			};

		$(document).bind('keydown',function (e) {
			if (isFullScreen && e.keyCode == 27) {
				setFullScreen(false);
			}
		});

	}

})(jQuery);
(function($) {

	// add extra default options
	$.extend(mejs.MepDefaults, {
		// this will automatically turn on a <track>
		startLanguage: '',
		// a list of languages to auto-translate via Google
		translations: [],
		// a dropdownlist of automatic translations
		translationSelector: false,
		// key for tranlsations
		googleApiKey: ''
	});

	$.extend(MediaElementPlayer.prototype, {

		buildtracks: function(player, controls, layers, media) {
			if (!player.isVideo)
				return;

			if (player.tracks.length == 0)
				return;

			var i, options = '';

			player.chapters =
					$('

')
						.prependTo(layers).hide();
			player.captions =
					$('

')
						.prependTo(layers).hide();
			player.captionsText = player.captions.find('.mejs-captions-text');
			player.captionsButton =
					$('
'+
						''+
						'
'+
							'
'+
								'
'+
									'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
									'None'+
								'
'	+
							'
'+
						'
'+
					'
')
						.appendTo(controls)
						// handle clicks to the language radio buttons
						.delegate('input[type=radio]','click',function() {
							lang = this.value;

							if (lang == 'none') {
								player.selectedTrack = null;
							} else {
								for (i=0; i<player.tracks.length; i++) {
									if (player.tracks[i].srclang == lang) {
										player.selectedTrack = player.tracks[i];
										player.captions.attr('lang', player.selectedTrack.srclang);
										player.displayCaptions();
										break;
									}
								}
							}
						});
						//.bind('mouseenter', function() {
						//	player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
						//});
			// move with controls
			player.container
				.bind('mouseenter', function () {
					// push captions above controls
					var p = player.container.find('.mejs-captions-position');
					p.css('bottom', (parseInt(p.css('bottom').replace(/px/,''), 10) + player.controls.height()) + 'px');

				})
				.bind('mouseleave', function () {
					if (!media.paused) {
						// move back to normal place
						player.container.find('.mejs-captions-position').css('bottom','');
					}
				});

			player.trackToLoad = -1;
			player.selectedTrack = null;
			player.isLoadingTrack = false;

			// add user-defined translations
			if (player.tracks.length > 0 && player.options.translations.length > 0) {
				for (i=0; i<player.options.translations.length; i++) {
					player.tracks.push({
						srclang: player.options.translations[i].toLowerCase(),
						src: null,
						kind: 'subtitles',
						entries: [],
						isLoaded: false,
						isTranslation: true
					});
				}
			}

			// add to list
			for (i=0; i<player.tracks.length; i++) {
				if (player.tracks[i].kind == 'subtitles') {
					player.addTrackButton(player.tracks[i].srclang, player.tracks[i].isTranslation);
				}
			}

			player.loadNextTrack();

			media.addEventListener('timeupdate',function(e) {
				player.displayCaptions();
			}, false);

			media.addEventListener('loadedmetadata', function(e) {
				player.displayChapters();
			}, false);

			player.container.hover(
				function () {
					// chapters
					player.chapters.css('visibility','visible');
					player.chapters.fadeIn(200);
				},
				function () {
					if (!media.paused) {
						player.chapters.fadeOut(200, function() {
							$(this).css('visibility','hidden');
							$(this).css('display','block');
						});
					}
				});

			// auto selector
			if (player.options.translationSelector) {
				for (i in mejs.language.codes) {
					options += '<option value="' + i + '">' + mejs.language.codes[i] + '</option>';
				}
				player.container.find('.mejs-captions-selector ul').before($(
					'<select class="mejs-captions-translations">' +
						'<option value="">--Add Translation--</option>' +
						options +
					'</select>'
				));
				// add clicks
				player.container.find('.mejs-captions-translations').change(function() {
					var
						option = $(this);
						lang = option.val();
					// add this language to the tracks list
					if (lang != '') {
						player.tracks.push({
							srclang: lang,
							src: null,
							entries: [],
							isLoaded: false,
							isTranslation: true
						});

						if (!player.isLoadingTrack) {
							player.trackToLoad--;
							player.addTrackButton(lang,true);
							player.options.startLanguage = lang;
							player.loadNextTrack();
						}
					}
				});
			}

		},

		loadNextTrack: function() {
			var t = this;

			t.trackToLoad++;
			if (t.trackToLoad < t.tracks.length) {
				t.isLoadingTrack = true;
				t.loadTrack(t.trackToLoad);
			} else {
				// add done?
				t.isLoadingTrack = false;
			}
		},

		loadTrack: function(index){
			var
				t = this,
				track = t.tracks[index],
				after = function() {

					track.isLoaded = true;

					// create button
					//t.addTrackButton(track.srclang);
					t.enableTrackButton(track.srclang);

					t.loadNextTrack();

				};

			if (track.isTranslation) {

				// translate the first track
				mejs.SrtParser.translateSrt(t.tracks[0].entries, t.tracks[0].srclang, track.srclang, t.options.googleApiKey, function(newOne) {

					// store the new translation
					track.entries = newOne;

					after();
				});

			} else {
				$.ajax({
					url: track.src,
					success: function(d) {

						// parse the loaded file
						track.entries = mejs.SrtParser.parse(d);
						after();

						if (track.kind == 'chapters' && t.media.duration > 0) {
							t.drawChapters(track);
						}
					},
					error: function() {
						t.loadNextTrack();
					}
				});
			}
		},

		enableTrackButton: function(lang) {
			var t = this;

			t.captionsButton
				.find('input[value=' + lang + ']')
					.attr('disabled','')
				.siblings('label')
					.html( mejs.language.codes[lang] || lang );

			// auto select
			if (t.options.startLanguage == lang) {
				$('#' + t.id + '_captions_' + lang).click();
			}

			t.adjustLanguageBox();
		},

		addTrackButton: function(lang, isTranslation) {
			var t = this,
				l = mejs.language.codes[lang] || lang;

			t.captionsButton.find('ul').append(
				$('
'+
					'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
					'' + l + ((isTranslation) ? ' (translating)' : ' (loading)') + ''+
				'
')
			);

			t.adjustLanguageBox();

			// remove this from the dropdownlist (if it exists)
			t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
		},

		adjustLanguageBox:function() {
			var t = this;
			// adjust the size of the outer box
			t.captionsButton.find('.mejs-captions-selector').height(
				t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
				t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
			);
		},

		displayCaptions: function() {

			if (typeof this.tracks == 'undefined')
				return;

			var
				t = this,
				i,
				track = t.selectedTrack;

			if (track != null && track.isLoaded) {
				for (i=0; i<track.entries.times.length; i++) {
					if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
						t.captionsText.html(track.entries.text[i]);
						t.captions.show();
						return; // exit out if one is visible;
					}
				}
				t.captions.hide();
			} else {
				t.captions.hide();
			}
		},

		displayChapters: function() {
			var
				t = this,
				i;

			for (i=0; i<t.tracks.length; i++) {
				if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
					t.drawChapters(t.tracks[i]);
					break;
				}
			}
		},

		drawChapters: function(chapters) {
			var
				t = this,
				i,
				dur,
				//width,
				//left,
				percent = 0,
				usedPercent = 0;

			t.chapters.empty();

			for (i=0; i<chapters.entries.times.length; i++) {
				dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
				percent = Math.floor(dur / t.media.duration * 100);
				if (percent + usedPercent > 100 || // too large
					i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
					{
					percent = 100 - usedPercent;
				}
				//width = Math.floor(t.width * dur / t.media.duration);
				//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
				//if (left + width > t.width) {
				//	width = t.width - left;
				//}

				t.chapters.append( $(
					'
' +
						'
' +
							'' + chapters.entries.text[i] + '' +
							'' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '' +
						'
' +
					'
'));
				usedPercent += percent;
			}

			t.chapters.find('div.mejs-chapter').click(function() {
				t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
				if (t.media.paused) {
					t.media.play();
				}
			});

			t.chapters.show();
		}
	});

	mejs.language = {
		codes:  {
			af:'Afrikaans',
			sq:'Albanian',
			ar:'Arabic',
			be:'Belarusian',
			bg:'Bulgarian',
			ca:'Catalan',
			zh:'Chinese',
			'zh-cn':'Chinese Simplified',
			'zh-tw':'Chinese Traditional',
			hr:'Croatian',
			cs:'Czech',
			da:'Danish',
			nl:'Dutch',
			en:'English',
			et:'Estonian',
			tl:'Filipino',
			fi:'Finnish',
			fr:'French',
			gl:'Galician',
			de:'German',
			el:'Greek',
			ht:'Haitian Creole',
			iw:'Hebrew',
			hi:'Hindi',
			hu:'Hungarian',
			is:'Icelandic',
			id:'Indonesian',
			ga:'Irish',
			it:'Italian',
			ja:'Japanese',
			ko:'Korean',
			lv:'Latvian',
			lt:'Lithuanian',
			mk:'Macedonian',
			ms:'Malay',
			mt:'Maltese',
			no:'Norwegian',
			fa:'Persian',
			pl:'Polish',
			pt:'Portuguese',
			//'pt-pt':'Portuguese (Portugal)',
			ro:'Romanian',
			ru:'Russian',
			sr:'Serbian',
			sk:'Slovak',
			sl:'Slovenian',
			es:'Spanish',
			sw:'Swahili',
			sv:'Swedish',
			tl:'Tagalog',
			th:'Thai',
			tr:'Turkish',
			uk:'Ukrainian',
			vi:'Vietnamese',
			cy:'Welsh',
			yi:'Yiddish'
		}
	};

	/*
	Parses SRT format which should be formatted as
	1
	00:00:01,1 --> 00:00:05,000
	A line of text

	2
	00:01:15,1 --> 00:02:05,000
	A second line of text

	Adapted from: http://www.delphiki.com/html5/playr
	*/
	mejs.SrtParser = {
		pattern_identifier: /^[0-9]+$/,
		pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}(,[0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}(,[0-9]{3})?)(.*)$/,
		timecodeToSeconds: function(timecode){
			var tab = timecode.split(':');
			return tab[0]*60*60 + tab[1]*60 + parseFloat(tab[2].replace(',','.'));
		},
		split2: function (text, regex) {
			// normal version for compliant browsers
			// see below for IE fix
			return text.split(regex);
		},
		parse: function(srtText) {
			var
				i = 0,
				lines = this.split2(srtText, /\r?\n/),
				entries = {text:[], times:[]},
				timecode,
				text;

			for(; i<lines.length; i++) {
				// check for the line number
				if (this.pattern_identifier.exec(lines[i])){
					// skip to the next line where the start --> end time code should be
					i++;
					timecode = this.pattern_timecode.exec(lines[i]);
					if (timecode && i<lines.length){
						i++;
						// grab all the (possibly multi-line) text that follows
						text = lines[i];
						i++;
						while(lines[i] !== '' && i<lines.length){
							text = text + '\n' + lines[i];
							i++;
						}

						// Text is in a different array so I can use .join
						entries.text.push(text);
						entries.times.push(
						{
							start: this.timecodeToSeconds(timecode[1]),
							stop: this.timecodeToSeconds(timecode[3]),
							settings: timecode[5]
						});
					}
				}
			}

			return entries;
		},

		translateSrt: function(srtData, fromLang, toLang, googleApiKey, callback) {

			var
				entries = {text:[], times:[]},
				lines,
				i

			this.translateText( srtData.text.join(' '), fromLang, toLang, googleApiKey, function(result) {
				// split on separators
				lines = result.split('');

				// create new entries
				for (i=0;i<srtData.text.length; i++) {
					// add translated line
					entries.text[i] = lines[i];
					// copy existing times
					entries.times[i] = {
						start: srtData.times[i].start,
						stop: srtData.times[i].stop,
						settings: srtData.times[i].settings
					};
				}

				callback(entries);
			});
		},

		translateText: function(text, fromLang, toLang, googleApiKey, callback) {

			var
				separatorIndex,
				chunks = [],
				chunk,
				maxlength = 1000,
				result = '',
				nextChunk= function() {
					if (chunks.length > 0) {
						chunk = chunks.shift();
						mejs.SrtParser.translateChunk(chunk, fromLang, toLang, googleApiKey, function(r) {
							if (r != 'undefined') {
								result += r;
							}
							nextChunk();
						});
					} else {
						callback(result);
					}
				};

			// split into chunks
			while (text.length > 0) {
				if (text.length > maxlength) {
					separatorIndex = text.lastIndexOf('.', maxlength);
					chunks.push(text.substring(0, separatorIndex));
					text = text.substring(separatorIndex+1);
				} else {
					chunks.push(text);
					text = '';
				}
			}

			// start handling the chunks
			nextChunk();
		},
		translateChunk: function(text, fromLang, toLang, googleApiKey, callback) {

			var data = {
				q: text,
				langpair: fromLang + '|' + toLang,
				v: '1.0'
			};
			if (googleApiKey !== '' && googleApiKey !== null) {
				data.key = googleApiKey;
			}

			$.ajax({
				url: 'https://ajax.googleapis.com/ajax/services/language/translate', // 'https://www.google.com/uds/Gtranslate', //'https://ajax.googleapis.com/ajax/services/language/translate', //
				data: data,
				type: 'GET',
				dataType: 'jsonp',
				success: function(d) {
					callback(d.responseData.translatedText);
				},
				error: function(e) {
					callback(null);
				}
			});
		}
	};
	// test for browsers with bad String.split method.
	if ('x\n\ny'.split(/\n/gi).length != 3) {
		// add super slow IE8 and below version
		mejs.SrtParser.split2 = function(text, regex) {
			var
				parts = [],
				chunk = '',
				i;

			for (i=0; i<text.length; i++) {
				chunk += text.substring(i,i+1);
				if (regex.test(chunk)) {
					parts.push(chunk.replace(regex, ''));
					chunk = '';
				}
			}
			parts.push(chunk);
			return parts;
		}
	}

})(jQuery);


text:
#ifndef USE_POSIX_REGEX
#define USE_POSIX_REGEX		/* put before includes; always use POSIX */
#endif

#include "squid.h"

typedef enum {
    rcHTTP,
    rcICP,
#if USE_HTCP
    rcHTCP,
#endif
#if USE_CACHE_DIGESTS
    rcCDigest,
#endif
    rcStore,
    rcCount
} refreshCountsEnum;

typedef struct {
    unsigned int expires:1;
    unsigned int min:1;
    unsigned int lmfactor:1;
    unsigned int max;
} stale_flags;

/*
 * This enumerated list assigns specific values, ala HTTP/FTP status
 * codes.  All Fresh codes are in the range 100-199 and all stale
 * codes are 200-299.  We might want to use these codes in logging,
 * so best to keep them consistent over time.
 */
enum {
    FRESH_REQUEST_MAX_STALE_ALL = 100,
    FRESH_REQUEST_MAX_STALE_VALUE,
    FRESH_EXPIRES,
    FRESH_LMFACTOR_RULE,
    FRESH_MIN_RULE,
    FRESH_OVERRIDE_EXPIRES,
    FRESH_OVERRIDE_LASTMOD,
    STALE_MUST_REVALIDATE = 200,
    STALE_RELOAD_INTO_IMS,
    STALE_FORCED_RELOAD,
    STALE_EXCEEDS_REQUEST_MAX_AGE_VALUE,
    STALE_EXPIRES,
    STALE_MAX_RULE,
    STALE_LMFACTOR_RULE,
    STALE_WITHIN_DELTA,
    STALE_ASYNC_REFRESH,
    STALE_MAX_STALE,
    STALE_DEFAULT = 299
};

static struct RefreshCounts {
    const char *proto;
    int total;
    int status[STALE_DEFAULT + 1];
} refreshCounts[rcCount];

/*
 * Defaults:
 *      MIN     NONE
 *      PCT     20%
 *      MAX     3 days
 */
#define REFRESH_DEFAULT_MIN	(time_t)0
#define REFRESH_DEFAULT_PCT	0.20
#define REFRESH_DEFAULT_MAX	(time_t)259200

static const refresh_t *refreshUncompiledPattern(const char *);
static OBJH refreshStats;
static int refreshStaleness(const StoreEntry *, time_t, time_t, const refresh_t *, stale_flags *);

static refresh_t DefaultRefresh;

const refresh_t *
refreshLimits(const char *url)
{
    const refresh_t *R;
    for (R = Config.Refresh; R; R = R->next) {
	if (!regexec(&(R->compiled_pattern), url, 0, 0, 0))
	    return R;
    }
    return NULL;
}

static const refresh_t *
refreshUncompiledPattern(const char *pat)
{
    const refresh_t *R;
    for (R = Config.Refresh; R; R = R->next) {
	if (0 == strcmp(R->pattern, pat))
	    return R;
    }
    return NULL;
}

refresh_cc
refreshCC(const StoreEntry * entry, request_t * request)
{
    const refresh_t *R;
    const char *uri = NULL;
    refresh_cc cc;
    cc.negative_ttl = Config.negativeTtl;
    cc.max_stale = Config.maxStale;
    if (entry->mem_obj)
	uri = entry->mem_obj->url;
    else if (request)
	uri = urlCanonical(request);

    R = uri ? refreshLimits(uri) : refreshUncompiledPattern(".");

    if (R && R->negative_ttl >= 0)
	cc.negative_ttl = R->negative_ttl;

    if (R && R->max_stale >= 0)
	cc.max_stale = R->max_stale;

    return cc;
}

/*
 * Calculate how stale the response is (or will be at the check_time).
 * Staleness calculation is based on the following: (1) response
 * expiration time, (2) age greater than configured maximum, (3)
 * last-modified factor, and (4) age less than configured minimum.
 *
 * If the response is fresh, return -1.  Otherwise return its
 * staleness.  NOTE return value of 0 means the response is stale.
 *
 * The 'stale_flags' structure is used to tell the calling function
 * _why_ this response is fresh or stale.  Its used, for example,
 * when the admin wants to override expiration and last-modified
 * times.
 */
static int
refreshStaleness(const StoreEntry * entry, time_t check_time, time_t age, const refresh_t * R, stale_flags * sf)
{
    /*
     * Check for an explicit expiration time.
     */
    if (entry->expires > -1) {
	sf->expires = 1;
	if (entry->expires > check_time) {
	    debug(22, 3) ("FRESH: expires %d >= check_time %d \n",
		(int) entry->expires, (int) check_time);
	    return -1;
	} else {
	    debug(22, 3) ("STALE: expires %d < check_time %d \n",
		(int) entry->expires, (int) check_time);
	    return (check_time - entry->expires);
	}
    }
    assert(age >= 0);
    /*
     * Use local heuristics to determine staleness.  Start with the
     * max age from the refresh_pattern rule.
     */
    if (age > R->max) {
	debug(22, 3) ("STALE: age %d > max %d \n", (int) age, (int) R->max);
	sf->max = 1;
	return (age - R->max);
    }
    if (check_time < entry->timestamp) {
	debug(22, 1) ("STALE: Entry's timestamp greater than check time. Clock going backwards?\n");
	debug(22, 1) ("\tcheck_time:\t%s\n", mkrfc1123(check_time));
	debug(22, 1) ("\tentry->timestamp:\t%s\n", mkrfc1123(entry->timestamp));
	debug(22, 1) ("\tstaleness:\t%ld\n", (long int) entry->timestamp - check_time);
	return (entry->timestamp - check_time);
    }
    /*
     * Try the last-modified factor algorithm.
     */
    if (entry->lastmod > -1 && entry->timestamp > entry->lastmod) {
	/*
	 * stale_age is the Age of the response when it became/becomes
	 * stale according to the last-modified factor algorithm.
	 */
	time_t stale_age = (entry->timestamp - entry->lastmod) * R->pct;
	sf->lmfactor = 1;
	if (age >= stale_age) {
	    debug(22, 3) ("STALE: age %d > stale_age %d\n",
		(int) age, (int) stale_age);
	    return (age - stale_age);
	} else {
	    debug(22, 3) ("FRESH: age %d <= stale_age %d\n",
		(int) age, (int) stale_age);
	    return -1;
	}
    }
    /*
     * If we are here, staleness is determined by the refresh_pattern
     * configured minimum age.
     */
    if (age < R->min) {
	debug(22, 3) ("FRESH: age %d < min %d\n", (int) age, (int) R->min);
	sf->min = 1;
	return -1;
    }
    debug(22, 3) ("STALE: age %d >= min %d\n", (int) age, (int) R->min);
    return (age - R->min);
}

/*  return 1 if the entry must be revalidated within delta seconds
 *         0 otherwise
 *
 *  note: request maybe null (e.g. for cache digests build)
 */
static int
refreshCheck(const StoreEntry * entry, request_t * request, time_t delta)
{
    const refresh_t *R;
    const char *uri = NULL;
    time_t age = 0;
    time_t check_time = squid_curtime;
    int staleness;
    stale_flags sf;
    if (entry->mem_obj)
	uri = entry->mem_obj->url;
    else if (request)
	uri = urlCanonical(request);

    debug(22, 3) ("refreshCheck: '%s'\n", uri ? uri : "<none>");

    if (delta > 0)
	check_time += delta;
    if (check_time > entry->timestamp)
	age = check_time - entry->timestamp;
    R = uri ? refreshLimits(uri) : refreshUncompiledPattern(".");
    if (NULL == R)
	R = &DefaultRefresh;
    memset(&sf, '\0', sizeof(sf));
    staleness = refreshStaleness(entry, check_time, age, R, &sf);
    debug(22, 3) ("Staleness = %d\n", staleness);

    debug(22, 3) ("refreshCheck: Matched '%s %d %d%% %d'\n",
	R->pattern, (int) R->min, (int) (100.0 * R->pct), (int) R->max);
    debug(22, 3) ("refreshCheck: age = %d\n", (int) age);
    debug(22, 3) ("\tcheck_time:\t%s\n", mkrfc1123(check_time));
    debug(22, 3) ("\tentry->timestamp:\t%s\n", mkrfc1123(entry->timestamp));

    if (EBIT_TEST(entry->flags, ENTRY_REVALIDATE) && staleness > -1) {
	debug(22, 3) ("refreshCheck: YES: Must revalidate stale response\n");
	return STALE_MUST_REVALIDATE;
    }
    /* request-specific checks */
    if (request) {
	HttpHdrCc *cc = request->cache_control;
#if HTTP_VIOLATIONS
	if (!request->flags.nocache_hack) {
	    (void) 0;
	} else if (R->flags.ignore_reload) {
	    /* The clients no-cache header is ignored */
	    debug(22, 3) ("refreshCheck: MAYBE: ignore-reload\n");
	} else if (R->flags.reload_into_ims || Config.onoff.reload_into_ims) {
	    /* The clients no-cache header is changed into a IMS query */
	    debug(22, 3) ("refreshCheck: YES: reload-into-ims\n");
	    return STALE_RELOAD_INTO_IMS;
	} else {
	    /* The clients no-cache header is not overridden on this request */
	    debug(22, 3) ("refreshCheck: YES: client reload\n");
	    request->flags.nocache = 1;
	    return STALE_FORCED_RELOAD;
	}
#endif
	if (NULL != cc) {
	    if (cc->max_age > -1) {
#if HTTP_VIOLATIONS
		if (R->flags.ignore_reload && cc->max_age == 0) {
		} else
#endif
		if (age > cc->max_age) {
		    debug(22, 3) ("refreshCheck: YES: age > client-max-age\n");
		    return STALE_EXCEEDS_REQUEST_MAX_AGE_VALUE;
		}
	    }
	    if (EBIT_TEST(cc->mask, CC_MAX_STALE) && staleness >= 0) {
		if (cc->max_stale < 0) {
		    /* max-stale directive without a value */
		    debug(22, 3) ("refreshCheck: NO: max-stale wildcard\n");
		    return FRESH_REQUEST_MAX_STALE_ALL;
		} else if (staleness < cc->max_stale) {
		    debug(22, 3) ("refreshCheck: NO: staleness < max-stale\n");
		    return FRESH_REQUEST_MAX_STALE_VALUE;
		}
	    }
	}
    }
    if (staleness < 0) {
	if (sf.expires)
	    return FRESH_EXPIRES;
	assert(!sf.max);
	if (sf.lmfactor)
	    return FRESH_LMFACTOR_RULE;
	assert(sf.min);
	return FRESH_MIN_RULE;
    }
    /*
     * At this point the response is stale, unless one of
     * the override options kicks in.
     */
#if HTTP_VIOLATIONS
    if (sf.expires && R->flags.override_expire && age < R->min) {
	debug(22, 3) ("refreshCheck: NO: age < min && override-expire\n");
	return FRESH_OVERRIDE_EXPIRES;
    }
    if (sf.lmfactor && R->flags.override_lastmod && age < R->min) {
	debug(22, 3) ("refreshCheck: NO: age < min && override-lastmod\n");
	return FRESH_OVERRIDE_LASTMOD;
    }
#endif
    if (entry->mem_obj) {
	int stale_while_revalidate = -1;
	if (entry->mem_obj->reply && entry->mem_obj->reply->cache_control && EBIT_TEST(entry->mem_obj->reply->cache_control->mask, CC_STALE_WHILE_REVALIDATE))
	    stale_while_revalidate = entry->mem_obj->reply->cache_control->stale_while_revalidate;
	if (R->flags.ignore_stale_while_revalidate || stale_while_revalidate == -1)
	    stale_while_revalidate = R->stale_while_revalidate;
	if (staleness < stale_while_revalidate) {
	    debug(22, 3) ("stale-while-revalidate: age=%d, staleness=%d, stale_while_revalidate=%d\n", (int) age, staleness, stale_while_revalidate);
	    entry->mem_obj->stale_while_revalidate = stale_while_revalidate;
	    return STALE_ASYNC_REFRESH;
	}
    } {
	int max_stale = Config.maxStale;
	if (R->max_stale >= 0)
	    max_stale = R->max_stale;
	if (entry->mem_obj && entry->mem_obj->reply && entry->mem_obj->reply->cache_control && EBIT_TEST(entry->mem_obj->reply->cache_control->mask, CC_STALE_IF_ERROR))
	    max_stale = entry->mem_obj->reply->cache_control->stale_if_error;
	if (max_stale >= 0 && staleness >= max_stale)
	    return STALE_MAX_STALE;
    }
    if (delta < 0 && staleness + delta < 0) {
	return STALE_WITHIN_DELTA;
    }
    if (sf.expires)
	return STALE_EXPIRES;
    if (sf.max)
	return STALE_MAX_RULE;
    if (sf.lmfactor)
	return STALE_LMFACTOR_RULE;
    return STALE_DEFAULT;
}

int
refreshIsCachable(const StoreEntry * entry)
{
    /*
     * Don't look at the request to avoid no-cache and other nuisances.
     * the object should have a mem_obj so the URL will be found there.
     * 60 seconds delta, to avoid objects which expire almost
     * immediately, and which can't be refreshed.
     */
    int reason = refreshCheck(entry, NULL, Config.minimum_expiry_time);
    int can_revalidate = 0;
    refreshCounts[rcStore].total++;
    refreshCounts[rcStore].status[reason]++;
    if (reason < 200)
	/* Does not need refresh. This is certainly cachable */
	return 1;
    if (entry->lastmod > 0)
	can_revalidate = 1;
    if (entry->mem_obj && entry->mem_obj->reply) {
	if (httpHeaderHas(&entry->mem_obj->reply->header, HDR_ETAG))
	    can_revalidate = 1;
    }
    /* Last modified is needed to do a refresh */
    if (!can_revalidate)
	return 0;

    /* This seems to be refreshable. Cache it */
    return 1;
}

/* refreshCheck... functions below are protocol-specific wrappers around
 * refreshCheck() function above */

int
refreshCheckHTTP(const StoreEntry * entry, request_t * request)
{
    int reason = refreshCheck(entry, request, 0);
    refreshCounts[rcHTTP].total++;
    refreshCounts[rcHTTP].status[reason]++;
    return (reason < 200) ? 0 : 1;
}

int
refreshCheckHTTPStale(const StoreEntry * entry, request_t * request)
{
    int reason = refreshCheck(entry, request, -Config.refresh_stale_window);
    if (reason == STALE_WITHIN_DELTA)
	return -1;
    if (reason == STALE_ASYNC_REFRESH)
	return -2;
    if (reason == STALE_MAX_STALE)
	return 3;
    return (reason < 200) ? 0 : 1;
}

int
refreshCheckStaleOK(const StoreEntry * entry, request_t * request)
{
    int reason = refreshCheck(entry, request, 0);
    if (reason == STALE_MUST_REVALIDATE)
	return 0;
    if (reason == STALE_MAX_STALE)
	return 0;
    return 1;
}

int
refreshCheckICP(const StoreEntry * entry, request_t * request)
{
    int reason = refreshCheck(entry, request, 30);
    refreshCounts[rcICP].total++;
    refreshCounts[rcICP].status[reason]++;
    return (reason < 200) ? 0 : 1;
}

#if USE_HTCP
int
refreshCheckHTCP(const StoreEntry * entry, request_t * request)
{
    int reason = refreshCheck(entry, request, 10);
    refreshCounts[rcHTCP].total++;
    refreshCounts[rcHTCP].status[reason]++;
    return (reason < 200) ? 0 : 1;
}
#endif

#if USE_CACHE_DIGESTS
int
refreshCheckDigest(const StoreEntry * entry, time_t delta)
{
    int reason = refreshCheck(entry,
	entry->mem_obj ? entry->mem_obj->request : NULL,
	delta);
    refreshCounts[rcCDigest].total++;
    refreshCounts[rcCDigest].status[reason]++;
    return (reason < 200) ? 0 : 1;
}
#endif

time_t
getMaxAge(const char *url)
{
    const refresh_t *R;
    debug(22, 3) ("getMaxAge: '%s'\n", url);
    if ((R = refreshLimits(url)))
	return R->max;
    else
	return REFRESH_DEFAULT_MAX;
}

static void
refreshCountsStats(StoreEntry * sentry, struct RefreshCounts *rc)
{
    int sum = 0;
    int tot = rc->total;

    storeAppendPrintf(sentry, "\n\n%s histogram:\n", rc->proto);
    storeAppendPrintf(sentry, "Count\t%%Total\tCategory\n");

#define refreshCountsStatsEntry(code,desc) { \
	storeAppendPrintf(sentry, "%6d\t%6.2f\t%s\n", \
	    rc->status[code], xpercent(rc->status[code], tot), desc); \
    sum += rc->status[code]; \
}

    refreshCountsStatsEntry(FRESH_REQUEST_MAX_STALE_ALL,
	"Fresh: request max-stale wildcard");
    refreshCountsStatsEntry(FRESH_REQUEST_MAX_STALE_VALUE,
	"Fresh: request max-stale value");
    refreshCountsStatsEntry(FRESH_EXPIRES,
	"Fresh: expires time not reached");
    refreshCountsStatsEntry(FRESH_LMFACTOR_RULE,
	"Fresh: refresh_pattern last-mod factor percentage");
    refreshCountsStatsEntry(FRESH_MIN_RULE,
	"Fresh: refresh_pattern min value");
    refreshCountsStatsEntry(FRESH_OVERRIDE_EXPIRES,
	"Fresh: refresh_pattern override expires");
    refreshCountsStatsEntry(FRESH_OVERRIDE_LASTMOD,
	"Fresh: refresh_pattern override lastmod");
    refreshCountsStatsEntry(STALE_MUST_REVALIDATE,
	"Stale: response has must-revalidate");
    refreshCountsStatsEntry(STALE_RELOAD_INTO_IMS,
	"Stale: changed reload into IMS");
    refreshCountsStatsEntry(STALE_FORCED_RELOAD,
	"Stale: request has no-cache directive");
    refreshCountsStatsEntry(STALE_EXCEEDS_REQUEST_MAX_AGE_VALUE,
	"Stale: age exceeds request max-age value");
    refreshCountsStatsEntry(STALE_EXPIRES,
	"Stale: expires time reached");
    refreshCountsStatsEntry(STALE_MAX_RULE,
	"Stale: refresh_pattern max age rule");
    refreshCountsStatsEntry(STALE_LMFACTOR_RULE,
	"Stale: refresh_pattern last-mod factor percentage");
    refreshCountsStatsEntry(STALE_WITHIN_DELTA,
	"Staĺe: but within a certain delta");
    refreshCountsStatsEntry(STALE_ASYNC_REFRESH,
	"Stale: suitable for an async refresh");
    refreshCountsStatsEntry(STALE_MAX_STALE,
	"Stale: max-stale");
    refreshCountsStatsEntry(STALE_DEFAULT,
	"Stale: by default");

    tot = sum;			/* paranoid: "total" line shows 100% if we forgot nothing */
    storeAppendPrintf(sentry, "%6d\t%6.2f\tTOTAL\n",
	rc->total, xpercent(rc->total, tot));
    \
	storeAppendPrintf(sentry, "\n");
}

static void
refreshStats(StoreEntry * sentry)
{
    int i;
    int total = 0;

    /* get total usage count */
    for (i = 0; i < rcCount; ++i)
	total += refreshCounts[i].total;

    /* protocol usage histogram */
    storeAppendPrintf(sentry, "\nRefreshCheck calls per protocol\n\n");
    storeAppendPrintf(sentry, "Protocol\t#Calls\t%%Calls\n");
    for (i = 0; i < rcCount; ++i)
	storeAppendPrintf(sentry, "%10s\t%6d\t%6.2f\n",
	    refreshCounts[i].proto,
	    refreshCounts[i].total,
	    xpercent(refreshCounts[i].total, total));

    /* per protocol histograms */
    storeAppendPrintf(sentry, "\n\nRefreshCheck histograms for various protocols\n");
    for (i = 0; i < rcCount; ++i)
	refreshCountsStats(sentry, &refreshCounts[i]);
}

void
refreshInit(void)
{
    memset(refreshCounts, 0, sizeof(refreshCounts));
    refreshCounts[rcHTTP].proto = "HTTP";
    refreshCounts[rcICP].proto = "ICP";
#if USE_HTCP
    refreshCounts[rcHTCP].proto = "HTCP";
#endif
    refreshCounts[rcStore].proto = "On Store";
#if USE_CACHE_DIGESTS
    refreshCounts[rcCDigest].proto = "Cache Digests";
#endif
    cachemgrRegister("refresh",
	"Refresh Algorithm Statistics",
	refreshStats,
	0,
	1);
    memset(&DefaultRefresh, '\0', sizeof(DefaultRefresh));
    DefaultRefresh.pattern = "<none>";
    DefaultRefresh.min = REFRESH_DEFAULT_MIN;
    DefaultRefresh.pct = REFRESH_DEFAULT_PCT;
    DefaultRefresh.max = REFRESH_DEFAULT_MAX;
}


text:
module Strings where

import Escapes
import Text.ParserCombinators.Parsec (parse)
import Text.Parsec.Error (ParseError)

partOne :: String -> Either ParseError Int
partOne input = do
  result <- parse pQuotedStrings "" input
  let xs = lines input
  let quotedLengths = sum (map length xs)
  return $ quotedLengths - sum (map (length . unQuoted) result)

partTwo input =
  let xs = lines input
      orig = sum (map length xs)
      new = sum (map (length . show) xs)
  in new - orig

main = do
  input <- readFile "input.txt"
  print $ partTwo input


text:
/*
 * Decompiled with CFR 0_79.
 */
package org.anddev.andengine.extension.multiplayer.protocol.server;

import java.io.IOException;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.BaseClientMessage;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.connection.ConnectionCloseClientMessage;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.connection.ConnectionEstablishClientMessage;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.connection.ConnectionPingClientMessage;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.connection.ConnectionPongClientMessage;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.BaseServerMessage;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.connection.ConnectionAcceptedServerMessage;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.connection.ConnectionPongServerMessage;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.connection.ConnectionRefusedServerMessage;
import org.anddev.andengine.extension.multiplayer.protocol.server.ClientConnector;
import org.anddev.andengine.extension.multiplayer.protocol.server.IClientMessageSwitch;
import org.anddev.andengine.extension.multiplayer.protocol.shared.BaseConnectionListener;
import org.anddev.andengine.extension.multiplayer.protocol.util.constants.ClientMessageFlags;

public abstract class BaseClientMessageSwitch
implements ClientMessageFlags,
IClientMessageSwitch {
    @Override
    public void doSwitch(ClientConnector clientConnector, BaseClientMessage baseClientMessage) throws IOException {
        switch (baseClientMessage.getFlag()) {
            default: {
                return;
            }
            case -32768: {
                this.onHandleConnectionEstablishClientMessage(clientConnector, (ConnectionEstablishClientMessage)baseClientMessage);
                return;
            }
            case -32767: {
                this.onHandleConnectionCloseClientMessage(clientConnector, (ConnectionCloseClientMessage)baseClientMessage);
                return;
            }
            case -32766: {
                this.onHandleConnectionPingClientMessage(clientConnector, (ConnectionPingClientMessage)baseClientMessage);
                return;
            }
            case -32765:
        }
        this.onHandleConnectionPongClientMessage(clientConnector, (ConnectionPongClientMessage)baseClientMessage);
    }

    protected void onHandleConnectionCloseClientMessage(ClientConnector clientConnector, ConnectionCloseClientMessage connectionCloseClientMessage) throws IOException {
        if (!clientConnector.hasConnectionListener()) return;
        clientConnector.getConnectionListener().onDisconnect(clientConnector);
    }

    protected void onHandleConnectionEstablishClientMessage(ClientConnector clientConnector, ConnectionEstablishClientMessage connectionEstablishClientMessage) throws IOException {
        if (connectionEstablishClientMessage.getProtocolVersion() == 1) {
            clientConnector.sendServerMessage(new ConnectionAcceptedServerMessage());
            return;
        }
        clientConnector.sendServerMessage(new ConnectionRefusedServerMessage());
    }

    protected void onHandleConnectionPingClientMessage(ClientConnector clientConnector, ConnectionPingClientMessage connectionPingClientMessage) throws IOException {
        clientConnector.sendServerMessage(new ConnectionPongServerMessage(connectionPingClientMessage));
    }

    protected void onHandleConnectionPongClientMessage(ClientConnector clientConnector2, ConnectionPongClientMessage clientConnector2) {
    }
}


text:
import path from 'path';
import program from 'commander';
import jsonfile from 'jsonfile';
import pathExt from 'path-extra';
import assign from 'lodash.assign';
import getStdin from 'get-stdin';
import BoxcarNotification from 'boxcar-notification';
import pkg from '../package.json';

const CONFNAME = '.boxcarrc';

program
    .version(pkg.version)
    .option('-c --credential <token>', 'your api token credential.')
    .option('-t --title <title>', 'notification title.')
    .option('-m --message <body>', 'notification message body. HTML allowed.')
    .option('-s --sound <sound>', 'notification sound. see below.', /^(beep-crisp|beep-soft|bell-modern|bell-one-tone|bell-simple|bell-triple|bird-1|bird-2|boing|cash|clanging|detonator-charge|digital-alarm|done|echo|flourish|harp|light|magic-chime|magic-coin|notifier-1|notifier-2|notifier-3|orchestral-long|orchestral-short|score|success|up)$/)
    .option('-f --from <source>', 'notification source name.')
    .option('-i --icon <url>', 'notification icon url.')
    .option('-q --quiet', 'no output unless error')
    .on('--help', function () {
        console.log('  Sounds: [%s]', BoxcarNotification.VALID_SOUNDS.join(','));
    })
    .parse(process.argv);

getStdin().then((fromStdin) => {

    let argvConf = {};
    if (program.credential) argvConf['credential'] = program.credential;
    if (program.title) argvConf['title'] = program.title;
    if (program.message) argvConf['message'] = program.message;
    if (program.sound) argvConf['sound'] = program.sound;
    if (program.from) argvConf['from'] = program.from;
    if (program.icon) argvConf['icon'] = program.icon;
    if (program.quiet) argvConf['quiet'] = program.quiet;

    let homeConf, currentConf;
    try {
        homeConf = jsonfile.readFileSync(path.join(pathExt.homedir(), CONFNAME));
    } catch (e) {
        homeConf = {};
    }
    try {
        currentConf = jsonfile.readFileSync(path.join(process.cwd(), CONFNAME));
    } catch (e) {
        currentConf = {};
    }

    // merge all configures
    let conf = assign(homeConf, currentConf, argvConf);

    let bn = new BoxcarNotification(conf.credential);
    let notificationSettings = {
        title: conf.title,
        longMessage: fromStdin || conf.message,
        sound: conf.sound,
        sourceName: conf.from,
        iconUrl: conf.icon
    };
    bn.send(notificationSettings).then((body) => {
        if (!conf.quiet) console.log(body);
        process.exit(0)
    }).catch((error) => {
        console.error(error);
        process.exit(1);
    });

});