text:
const bodyParser = require('body-parser');
const fs = require('fs');
const express = require('express');
const router = new express.Router();
//const sortobject = require('deep-sort-object');
const env = process.env;
import getDataSetsFromManifest from './merge_cols';
const DATA_FOLDER = env.DATA_FOLDER.replace(/\/$/,'');

router.use(bodyParser.json({ strict: false, limit: '500mb' }));

//list top-level folders or next level
router.route('/list')
  .get((req, res, next) => {
    let folder = DATA_FOLDER;
    if (req.query.folder)
      folder = DATA_FOLDER + '/' + req.query.folder;
    fs.readdir(folder, (err,out) => {
      if (err) {
        res.status(500).send(err);
        return;
      }
      var list = [];
      out.map(val => {
        if (!val.startsWith('.') && !val.match(/\.[a-zA-Z0-9]+$/)) {
          list.push(val);
        }
      });
      res.json(list);
    });
  });

//get data described in the manifest file
router.route('/data')
  .get((req, res, next) => {
    let folder = DATA_FOLDER + '/' + req.query.folder;
    getDataSetsFromManifest(folder)
      .then(output => {
        res.send(output);
      })
      .catch(err => {
        console.log(err);
        res.status(500).send(err);
      });
  });

//get data described in the manifest file
router.route('/raw/:folder/:file')
  .get((req, res, next) => {
    let file = DATA_FOLDER + '/' + req.params.folder + '/' + req.params.file;
    console.log('Download ' + file);
    fs.readFile(file, 'utf-8', (err, out) => {
      if (err) {
        console.log(err);
        res.status(500).send(err);
      } else {
        let header = {
          'Content-Type': 'text/plain',
          'Content-Disposition': 'attachment; data.txt'
        };
        res.set(header).send(out);
      }
    });
  });

module.exports = router;


text:
package parse

const specialHelpMessage = `
) help
	Print this list of special commands.
) base 0
	Set the number base for input and output. The commands
	ibase and obase control setting of the base for input
	and output alone, respectively.
	Base 0 allows C-style input: decimal, with 037 being octal
	and 0x10 being hexadecimal.
	If the base is greater than 10, any identifier formed from
	valid numerals in the base system, such as abe for base 16,
	is taken to be a number.
	TODO: To output rationals and bigs, obase must be one of 0 2 8 10 16.
) debug name 0|1
	Toggle or set the named debugging flag. With no argument,
	lists the settings.
) format ""
	Set the format for printing values. If empty, the output
	is printed using the output base. If non-empty, the
	format determines the base used in printing.
	The format is in the style of golang.org/pkg/fmt.
	For floating-point formats, flags and width are ignored.
) get "file.ivy"
	Read commands from the named file; return to
	interactive execution afterwards.
) maxbits 1e6
	To avoid consuming too much memory, if an integer result
	would require more than this many bits to store, abort
	the calculation.
	If maxbits is 0, there is no limit; the default is 1e6.
) maxdigits 1e4
	To avoid overwhelming amounts of output, if an integer has more
	than this many digits, print it using the defined floating-point
	format. If maxdigits is 0, integers are always printed as integers.
) op X
	Show the definition of the user-defined operator X.
	Inside the definition, numbers are always shown base
	10, ignoring the ibase and obase.
) origin 1
	Set the origin for indexing a vector or matrix.
) prec 256
	Set the precision (mantissa length) for floating-point values.
	The value is in bits. The exponent always has 32 bits.
) prompt ""
	Set the interactive prompt.
) seed 0
	Set the seed for the ? operator.
`

redpajama_set_name: RedPajamaGithub


text:
<?php

// Gets the filtered value of the redirect_to parameter (string)
// Taken from wp-login.php
$get_redirect_to = function ($user) {
    if (isset($_REQUEST['redirect_to'])) {
        $redirect_to = $_REQUEST['redirect_to'];
    // // Redirect to https if user wants ssl
        // if ( $secure_cookie && false !== strpos($redirect_to, 'wp-admin') ) { //
        //   $redirect_to = preg_replace('|^http://|', 'https://', $redirect_to);
        // } //
    } else {
        $redirect_to = admin_url();
    }

    $requested_redirect_to = isset($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : '';
    return apply_filters('login_redirect', $redirect_to, $requested_redirect_to, $user);
};

// Uses wp_safe_redirect()
// Taken from wp-login.php
$redirect = function ($user) use ($get_redirect_to) {
    global $interim_login;

    if ($interim_login) {
        $message = '
' . __('You have logged in successfully.') . '
';
        $interim_login = 'success';
        login_header('', $message); ?>
        <?php
        do_action('login_footer'); ?>

        <?php
        exit;
    }

    $redirect_to = $get_redirect_to($user);
    // Copied verbatim from wp-login.php

    if ((empty($redirect_to) || $redirect_to == 'wp-admin/' || $redirect_to == admin_url())) {
        // If the user doesn't belong to a blog, send them to user admin. If the user can't edit posts, send them to their profile.
        if (is_multisite() && !get_active_blog_for_user($user->ID) && !is_super_admin($user->ID)) {
            $redirect_to = user_admin_url();
        } elseif (is_multisite() && !$user->has_cap('read')) {
            $redirect_to = get_dashboard_url($user->ID);
        } elseif (!$user->has_cap('edit_posts')) {
            $redirect_to = admin_url('profile.php');
        }
    }

    wp_safe_redirect($redirect_to);
    exit();
};

// Renders the HTML of the login form
$render = function ($phase, $errors, $rememberme, $user_id) use ($get_redirect_to) {
    global $interim_login;

    $first_phase = $phase === 1;

    $user = get_user_by('id', $user_id);
    $user_login = '';
    if ($user !== false) {
        $user_login = $user->user_login;
    }

    $redirect_to = $get_redirect_to($user);

    do_action('login_enqueue_scripts');
    do_action('login_head');

    $errors = apply_filters('wp_login_errors', $errors, $redirect_to);
    login_header(__('Log In'), '', $errors);

    if ($first_phase) {
        // Phase 1 - user/pass form?>

        <form method="POST" action="<?php echo esc_url(site_url('wp-login.php', 'login_post')) ?>" id="loginform" name="loginform">

                    <?php _e('Username') ?>

                    <input type="text" name="log" id="user_login" class="input" value="<?php echo esc_attr($user_login); ?>" size="20" autofocus>

                    <?php _e('Password') ?>

                    <input type="password" name="pwd" id="user_pass" class="input" value="" size="20">

            <?php do_action('login_form') ?>

<input name="rememberme" type="checkbox" id="rememberme" value="forever"> Remember Me

                <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="<?php esc_attr_e('Log In'); ?>">
                <?php if ($interim_login) : ?>
                    <input type="hidden" name="interim-login" value="1">
                <?php else : ?>
                    <input type="hidden" name="redirect_to" value="<?php echo esc_attr($redirect_to); ?>">
                <?php endif ?>
                <input type="hidden" name="testcookie" value="1">

        </form>

        <?php
    } else {
        // Phase 2 - token input
        ?>

        <form method="POST" action="<?php echo esc_url(site_url('wp-login.php', 'login_post')) ?>" id="loginform" name="loginform">

                    <?php _e('Enter the code shown in the authenticator app on your device, the SMS sent to your mobile, or the email sent to your inbox') ?>

                    <input type="text" name="token" id="token" class="input" size="20" autofocus>

<input name="skip_2fa" type="checkbox" id="skip_2fa" value="yes"> <?php printf('Remember this computer for %d days (do not check if this is a shared computer)', twofa_skip_days()) ?>

            <?php if (twofa_bruteforce_login_show_captcha($user_id)) : ?>
                <div class="g-recaptcha" data-sitekey="<?php echo esc_attr(RECAPTCHA_PUBLIC_KEY) ?>">

            <?php endif ?>

            <?php do_action('2fa_login_form_second_factor') ?>

                <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="<?php esc_attr_e('Verify'); ?>">
                <input type="hidden" name="user_id" value="<?php echo esc_attr(absint($user_id)) ?>">
                <input type="hidden" name="nonce" value="<?php echo esc_attr(wp_create_nonce('2fa_phase2_'.$user_id)) ?>">
                <input type="hidden" name="rememberme" value="<?php echo isset($_POST['rememberme']) ? 'yes' : 'no' ?>">
                <?php if ($interim_login) : ?>
                    <input type="hidden" name="interim-login" value="1">
                <?php else : ?>
                    <input type="hidden" name="redirect_to" value="<?php echo esc_attr($redirect_to); ?>">
                <?php endif ?>

        </form>

        <?php
    }

    login_footer();
    exit(0);
};

function twofa_wp_set_auth_cookie($user_id, $rememberme)
{
    wp_set_auth_cookie($user_id, $rememberme);

    $user = get_user_by('ID', $user_id);
    do_action('wp_login', $user->user_login, $user);
}

// Replaces the stock WordPress login form with our own
add_action('login_form_login', function () use ($redirect, $render) {
    global $interim_login;

    // An interim login is where you're in the middle of editing a post and you get logged out
    // An interim login prompt appears and asks you to sign in again
    $interim_login = isset($_REQUEST['interim-login']);

    $errors = new WP_Error;

    // Phase 1

    if (isset($_POST['log']) && isset($_POST['pwd'])) {
        // Verify credentials
        $user = wp_authenticate($_POST['log'], $_POST['pwd']);

        if (is_wp_error($user)) {
            $render(1, $user, null, null);
        }

        if (twofa_verify_skip_cookie($user->ID) || !twofa_user_activated($user->ID)) {
            // If the user has a valid skip cookier or haven't got 2FA set up, log them in

            $rememberme = isset($_POST['rememberme']);
            twofa_wp_set_auth_cookie($user->ID, $rememberme);
            $redirect($user);
        } else {
            // Otherwise, send them to phase 2

            // But first send an SMS or email if they have that activated
            twofa_sms_send_login_tokens($user->ID);
            $emailLogin = new \Dxw\TwoFa\EmailLogin();
            $emailLogin->sendLoginTokens($user->ID);

            $render(2, null, null, $user->ID);
        }
    }

    // Phase 2

    if (isset($_POST['token']) && isset($_POST['user_id']) && isset($_POST['nonce'])) {
        $user_id = absint($_POST['user_id']);

        if ($user_id <= 0) {
            $errors->add('bad_user_id', __('An error has occurred. Please try again.'));
            $render(1, $errors, null, null);
        }

        if (twofa_bruteforce_login_show_captcha($user_id)) {
            $recaptcha = new \ReCaptcha\ReCaptcha(RECAPTCHA_PRIVATE_KEY);
            $resp = $recaptcha->verify(stripslashes($_POST['g-recaptcha-response']), $_SERVER['REMOTE_ADDR']);
            if (!$resp->isSuccess()) {
                $errors->add('invalid_captcha', __('Invalid CAPTCHA. Try again.'));
                $render(2, $errors, null, $user_id);
            }
        }

        if (!wp_verify_nonce($_POST['nonce'], '2fa_phase2_'.$user_id)) {
            $errors->add('invalid_nonce', __('An error occurred. Please try again.'));
            $render(1, $errors, null, null);
        }

        $token = preg_replace('_[^0-9]_', '', $_POST['token']);
        if (!twofa_user_verify_token($user_id, $token)) {
            $errors->add('invalid_token', __('Invalid code. Try again or go back to the previous screen and reenter your login details. Make sure you're using one of your activated devices.'));

            // Report failed login attempt
            twofa_log_failure($user_id, $token);
            twofa_bruteforce_login_failure($user_id);

            $render(2, $errors, null, $user_id);
        }

        $rememberme = isset($_POST['rememberme']) && $_POST['rememberme'] === 'yes';
        twofa_wp_set_auth_cookie($user_id, $rememberme);

        if (isset($_POST['skip_2fa']) && $_POST['skip_2fa'] === 'yes') {
            twofa_set_skip_cookie($user_id);
        }

        // Reset captcha
        twofa_bruteforce_login_success($user_id);

        $redirect(get_user_by('id', $user_id));
    }

    $render(1, $errors, null, null);
    exit(0);
});


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Theme_Default extends Theme {

    public $name = 'PyroCMS Theme';
    public $author = 'iKreativ';
    public $author_website = 'http://ikreativ.com/';
    public $website = 'http://pyrocms.com/';
    public $description = 'Default PyroCMS v1.0 Theme - 2 Column, Fixed width, Horizontal navigation, CSS3 styling.';
    public $version = '1.0';

}

/* End of file theme.php */


text:
package org.javadrupe.collections;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/** This is the ubiquitous unmodifiable list class.
 *
 * A not-bad implementation of the ubiquitous unmodifiable list class. Can be used in
 * places where Stream.Builder doesn't fit the bill; the join() method allows two partially
 * built lists to be joined together.
 *
 * TODO: maybe provide better spliterator implementation
 *
 * @author Jonathan Essex.
 *
 * @param <E> Element type.
 */
public interface UnmodifiableList<E> extends Iterable<E> {

	@SuppressWarnings("rawtypes")
	public static final UnmodifiableList EMPTY = new Empty();

	/** Get first element in list. */
	public E head();
	/** Get sublist containing all elements in list after first. */
	public UnmodifiableList<E> tail();
	/** Create a new list, containing all elements in this list plus elem. */
	public UnmodifiableList<E> add(E elem);
	/** Create a new list, containing all elements in this list plus list */
	public UnmodifiableList<E> join(UnmodifiableList<E> list);
	/** is this list empty? */
	public boolean isEmpty();
	/** get stream */
	public default Stream<E> stream() { return StreamSupport.stream(spliterator(), false); }

	/** Create an unmodifiable view of an existing list.
	 *
	 * This allows us, for example, to create a single unmodifiable list containing
	 * several source lists without copying the underlying data in the source lists.
	 * However, it should be noted that unless the 'viewed' list provides an efficient
	 * sublist method, some operations on the resulting unmodifiable list may be very
	 * inefficient.
	 *
	 */
	public static <E> UnmodifiableList<E> view(List<E> to_view) {
		return new Proxy<E>(to_view);
	}

	@SuppressWarnings("unchecked")
	public static <E> UnmodifiableList<E> empty() {
		return (UnmodifiableList<E>)EMPTY;
	}

	/** Convenient way to create umodifiable list with type inference.
	 *
	 *  @param es Array of elmenets to create an unmodifiable list from.
	 *  @return an unmodifiable list containing the specified elements.
	 */
	@SafeVarargs
	public static <E> UnmodifiableList<E> of(E... es) {
		return new Proxy<E>(Arrays.asList(es));
	}

	/** Empty Iterator.
	 *
	 * Come java 9, hopefully this will be private. Do not use directly.
	 *
	 */
	public static class EmptyIterator<E> implements Iterator<E> {
		public boolean hasNext() { return false; }
		public E next() { return null; }
	}

	/** Empty Unmodifiable List.
	 *
	 * Come java 9, hopefully this will be private. Do not use directly.
	 *
	 */
	public static class Empty<E> implements UnmodifiableList<E> {
		@Override
		public E head() { return null; }
		@Override
		public UnmodifiableList<E> tail() { return null; }
		@Override
		public UnmodifiableList<E> add(E elem) { return new Impl<E>(elem, this); }
		@Override
		public boolean isEmpty() { return true; }
		@Override
		public UnmodifiableList<E> join(UnmodifiableList<E> list) { return list; }
		@Override
		public Iterator<E> iterator() { return new EmptyIterator<E>(); }
	}

	/** Iterator over an unmodifiable list.
	 *
	 * Come java 9, hopefully this will be private. Do not use directly.
	 *
	 */
	public static class IteratorImpl<E> implements Iterator<E> {
		private UnmodifiableList<E> next;
		@Override
		public boolean hasNext() { return !next.isEmpty(); }
		@Override
		public E next() { E rv = next.head(); next = next.tail(); return rv; }
		public IteratorImpl(UnmodifiableList<E> next) { this.next = next; }
	}

	/** Main implementation class.
	 *
	 * Come java 9, hopefully this will be private. Do not use directly.
	 *
	 */
	public static class Impl<E> implements UnmodifiableList<E> {
		private final E head;
		private final UnmodifiableList<E> tail;
		public Impl(E head, UnmodifiableList<E> tail) { this.head = head; this.tail = tail; }
		@Override
		public boolean isEmpty() { return false; }
		@Override
		public E head() { return head; }
		@Override
		public UnmodifiableList<E> tail() { return tail; }
		@Override
		public UnmodifiableList<E> add(E elem) { return new Impl<E>(elem, this); }
		@Override
		public Iterator<E> iterator() { return new IteratorImpl<E>(this); }
		@Override
		public UnmodifiableList<E> join(UnmodifiableList<E> list) { return list.isEmpty() ? this : new Merged<E>(this, list); }
	}

	/** Main implementation class.
	 *
	 * Come java 9, hopefully this will be private. Do not use directly.
	 *
	 */
	public static class Merged<E> implements UnmodifiableList<E> {
		UnmodifiableList<E> a;
		UnmodifiableList<E> b;
		public Merged(UnmodifiableList<E> a, UnmodifiableList<E> b) { this.a = a; this.b = b; }
		@Override
		public E head() { return a.head(); }
		@Override
		public UnmodifiableList<E> tail() { return (a.tail().isEmpty()) ? b : new Merged<E>(a.tail(), b); }
		@Override
		public UnmodifiableList<E> add(E elem) { return new Impl<E>(elem, this); }
		@Override
		public Iterator<E> iterator() { return new IteratorImpl<E>(this); }
		@Override
		public UnmodifiableList<E> join(UnmodifiableList<E> list) { return list.isEmpty() ? this : new Merged<E>(this, list); }
		@Override
		public boolean isEmpty() { return false; }
	}

	/** Why can't I make this fucking private, java?? */
	public static class Proxy<E> implements UnmodifiableList<E> {

		private List<E> proxied;

		public Proxy(List<E> proxied) { this.proxied = proxied; }
		@Override
		public boolean isEmpty() { return proxied.isEmpty(); }
		@Override
		public Iterator<E> iterator() { return proxied.iterator(); }
		@Override
		public E head() { return proxied.get(0); }
		@Override
		public UnmodifiableList<E> tail() { return new Proxy<E>(proxied.subList(1, proxied.size())); }
		@Override
		public UnmodifiableList<E> add(E elem) { return new Impl<E>(elem, this); }
		@Override
		public UnmodifiableList<E> join(UnmodifiableList<E> list) { return list.isEmpty() ? this : new Merged<E>(this, list);	}
	}

}


text:
classdef FitObject < handle
    %FITOBJECT Object to perform standard fits on data
    %

    properties
        % name of the fit
        name

        % function that is used to fit
        func

        % if only the function body should be used to fit
        useFuncBody = true

        % if only the function name should be used to fit
        useFuncName = false

        startX = -Inf
        endX = Inf
        startY = -Inf
        endY = Inf

        options = struct( ...
            'Method', 'NonLinearLeastSquares', ...
            'MaxFunEvals', 5000, ...
            'MaxIter', 5000 ...
        )
    end

    properties (SetAccess=private)
        lastResult
        numArguments
        arguments
        parameter
        problem
        independent
    end

    properties (Access=private)
        funcBody
        argumentType

        funcTex_
    end

    properties (Dependent)
        funcTex

        argumentNames
        parameterNames
        problemNames
        independentNames
    end

    events
        valueChange
    end

    methods
        function obj = FitObject(func)
            if (nargin)
                obj.func = func;
            end
        end
    end

    % SETTER
    methods
        function set.func(this, func)
            parNames = getFunctionArguments(func);
            this.numArguments = nargin(func);

            this.arguments = Fit.Parameter.empty();
            this.arguments(this.numArguments) = Fit.Parameter;
            this.parameter = 1:this.numArguments;
            this.argumentType = cell(this.numArguments, 1);

            for i = 1:this.numArguments
                this.arguments(i) = Fit.Parameter(this, parNames{i});
                addlistener( ...
                    this.arguments(i), ...
                    'type', 'PostSet', ...
                    @(~,~)this.addArgumentToList( ...
                        this.arguments(i).name, ...
                        this.arguments(i).type ...
                    ) ...
                );
                this.argumentType{i} = 'parameter';
            end

            this.problem = [];
            this.independent = [];
            this.setIndependent(parNames{end});

            this.func = func;
            str = func2str(func);
            this.funcBody = str(strfind(str, ')') + 1:end);

            this.funcTex = [];
        end

        function set.funcTex(this, funcTex)
            this.funcTex_ = funcTex;
        end
    end

    % GETTER
    methods
        function funcTex = get.funcTex(this)
            if (isempty(this.funcTex_))

                symbols = cell(this.numArguments, 1);
                for i = 1:this.numArguments
                    symbols{i} = sym(this.arguments(i).name);
                end
                try
                    this.funcTex = ['$', latex(this.func(symbols{:})), '$'];
                catch
                    this.funcTex = '... not spezified ...';
                end
            end
            funcTex = this.funcTex_;
        end
        function names = get.argumentNames(obj)
            names = {obj.arguments.name};
        end
        function names = get.parameterNames(obj)
            names = obj.getListProperties('parameter');
        end
        function names = get.problemNames(obj)
            names = obj.getListProperties('problem');
        end
        function names = get.independentNames(obj)
            names = obj.getListProperties('independent');
        end
    end

    methods
        function has = hasArgument(this, name)
            has = (sum(ismember(this.argumentNames, name) > 0));
        end
        function arg = arg(this, name)
            %OBJ.arg(NAME) alias to OBJ.getArgumentByName(NAME)

            arg = this.getArgumentByName(name);
        end
        function arg = getArgumentByName(this, name)
            arg = this.arguments(this.getArgumentIndex(name));
        end

        function setParameter(this, name)
            this.addArgumentToList(name, 'parameter');
        end
        function setProblem(this, name)
            this.addArgumentToList(name, 'problem');
        end
        function setIndependent(this, name)
            this.addArgumentToList(name, 'independent');
        end

        function setArgumentValue(this, name, value)
            if isa(name, 'cell')
                if length(value) == 1
                    value = ones(size(name)) * value;
                end
                for i = 1:numel(name)
                    this.setArgumentValue(name{i}, value(i));
                end
            else
                this.arguments(this.getArgumentIndex(name)).value = value;
            end
        end

        [fitobj, goodness, output, warnstr, errstr, convmsg] = ...
                fit(obj, xData, yData, weights)
        interval = confidenceInterval(fitObj, level, name)
    end

    % external functions
    methods
        guiChangeSettings(obj)
        y = feval(obj, x)
        z = feval2D(obj, x, y)
        h = plot(obj, x, varargin)
        str = getTextResult(this)

        result = guiFitToGraph(this, graph)
        % converter
        str = char(obj)
    end

    methods (Access=private)
        function is = isArgumentInList(obj, argIndex, list)
            is = any(obj.(list) == argIndex);
        end

        function removeArgumentFromList(obj, argIndex, list)
            if (nargin < 3)
                list = obj.argumentType{argIndex};
            end
            obj.(list) = obj.(list)(obj.(list) ~= argIndex);
        end

        function addArgumentToList(obj, argIndex, list)
            if (isa(argIndex, 'cell'))
                for i = 1:numel(argIndex)
                    obj.addArgumentToList(argIndex{i}, list);
                end
            elseif (isa(argIndex, 'char'))
                obj.addArgumentToList(obj.getArgumentIndex(argIndex), list);
            else
                assert(isnumeric(argIndex), ...
                    'Fit:addArgumentToList:argumentNoStringOrNumber', ...
                    'Argument must be a string or numeric.');

                if numel(argIndex) ~= 1
                    for i = argIndex
                        obj.addArgumentToList(i, list);
                    end
                else
                    if ~obj.isArgumentInList(argIndex, list)
                        obj.removeArgumentFromList(argIndex);
                        obj.(list)(end+1) = argIndex;
                        obj.argumentType{argIndex} = list;
                        if (~strcmp(list, obj.arguments(argIndex).type))
                            obj.arguments(argIndex).type = list;
                        end
                    end
                end
                if (strcmp(list, 'independent'))
                    obj.(list) = sort(obj.(list));
                end
            end
        end

        function argIndex = getArgumentIndex(obj, argName)
            for i = 1:obj.numArguments
                if strcmp(argName, obj.arguments(i).name)
                    argIndex = i;
                    return;
                end
            end
            error('Fit:getArgumentIndex:notFound', ...
                ['Argument ' argName ' not found.']);
        end

        function [varargout] = getListProperties(obj, list)
            args = obj.arguments(obj.(list));

            if nargout > 0
                varargout{1} = {args.name};
            end
            if nargout > 1
                varargout{2} = [args.value];
            end
            if nargout > 2
                varargout{3} = [args.lowerBound];
            end
            if nargout > 3
                varargout{4} = [args.upperBound];
            end
        end
    end

    methods (Static)
        function this = loadobj(o)
            if (isstruct(o))
                this = Fit.FitObject();
                for fieldname = fieldnames(o)
                    this.(fieldname{1}) = o.(fieldname{1});
                end
            else
                this = o;
            end

            for arg = o.arguments
                arg.fit = o;
            end
        end
    end
end


text:
package server

import (
	"bytes"
	"context"
	"io/ioutil"
	"net"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"syscall"
	"time"

	"github.com/fnproject/fn/api/common"
	"github.com/fnproject/fn/api/id"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func init() {
	// init logging stuff in init, in case any packages log stuff on startup
	common.SetLogFormat(getEnv(EnvLogFormat, DefaultLogFormat))
	common.SetLogLevel(getEnv(EnvLogLevel, DefaultLogLevel))
	common.SetLogDest(getEnv(EnvLogDest, DefaultLogDest), getEnv(EnvLogPrefix, ""))

	// gin is not nice by default, this can get set in logging initialization
	gin.SetMode(gin.ReleaseMode)

	// set machine id in init() before any packages are initialized that may use it
	// (you may change this to seed the id another way but be wary of package initialization)
	setMachineID()

}

func setMachineID() {
	port := uint16(getEnvInt(EnvPort, DefaultPort))
	addr := whoAmI().To4()
	if addr == nil {
		addr = net.ParseIP("127.0.0.1").To4()
		logrus.Warn("could not find non-local ipv4 address to use, using '127.0.0.1' for ids, if this is a cluster beware of duplicate ids!")
	}
	id.SetMachineIdHost(addr, port)
}

// whoAmI searches for a non-local address on any network interface, returning
// the first one it finds. it could be expanded to search eth0 or en0 only but
// to date this has been unnecessary.
func whoAmI() net.IP {
	ints, _ := net.Interfaces()
	for _, i := range ints {
		if i.Name == "docker0" || i.Name == "lo" {
			// not perfect
			continue
		}
		addrs, _ := i.Addrs()
		for _, a := range addrs {
			ip, _, err := net.ParseCIDR(a.String())
			if a.Network() == "ip+net" && err == nil && ip.To4() != nil {
				if !bytes.Equal(ip, net.ParseIP("127.0.0.1")) {
					return ip
				}
			}
		}
	}
	return nil
}

func getEnv(key, fallback string) string {
	if value, ok := os.LookupEnv(key); ok {
		return value
	} else if value, ok := os.LookupEnv(key + "_FILE"); ok {
		dat, err := ioutil.ReadFile(filepath.Clean(value))
		if err == nil {
			return string(dat)
		}
	}
	return fallback
}

func getEnvInt(key string, fallback int) int {
	if value, ok := os.LookupEnv(key); ok {
		// linter liked this better than if/else
		var err error
		var i int
		if i, err = strconv.Atoi(value); err != nil {
			logrus.WithError(err).WithFields(logrus.Fields{"string": value, "environment_key": key}).Fatal("Failed to convert string to int")
		}
		return i
	} else if value, ok := os.LookupEnv(key + "_FILE"); ok {
		dat, err := ioutil.ReadFile(filepath.Clean(value))
		if err == nil {
			var err error
			var i int
			if i, err = strconv.Atoi(strings.TrimSpace(string(dat))); err != nil {
				logrus.WithError(err).WithFields(logrus.Fields{"string": dat, "environment_key": key}).Fatal("Failed to convert string to int")
			}
			return i
		}
	}
	return fallback
}

func getEnvDuration(key string, fallback time.Duration) time.Duration {
	var err error
	res := fallback
	if tmp := os.Getenv(key); tmp != "" {
		// if the returned value is not null it needs to be either an integral value in seconds or a parsable duration-format string
		res, err = time.ParseDuration(tmp)
		if err != nil {
			// try to parse an int
			s, perr := strconv.Atoi(tmp)
			if perr != nil {
				logrus.WithError(err).WithFields(logrus.Fields{"duration_string": tmp, "environment_key": key}).Fatal("Failed to parse duration from env")
			} else {
				res = time.Duration(s) * time.Second
			}
		}
	}
	return res
}

func contextWithSignal(ctx context.Context, signals ...os.Signal) (context.Context, context.CancelFunc) {
	newCTX, halt := context.WithCancel(ctx)
	c := make(chan os.Signal, 1)
	signal.Notify(c, signals...)
	go func() {
		for {
			select {
			case <-c:
				common.Logger(ctx).Info("Halting...")
				halt()
				return
			case <-ctx.Done():
				common.Logger(ctx).Info("Halting... Original server context canceled.")
				halt()
				return
			}
		}
	}()
	return newCTX, halt
}

// Installs a child process reaper if init process
func installChildReaper() {
	// assume responsibilities of init process if running as init process for Linux
	if runtime.GOOS != "linux" || os.Getpid() != 1 {
		return
	}

	var sigs = make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGCHLD)

	// we run this forever and leak a go routine. As init, we must
	// reap our children until the very end, so this is OK.
	go func() {
		for {
			<-sigs
			for {
				var status syscall.WaitStatus
				var rusage syscall.Rusage

				pid, err := syscall.Wait4(-1, &status, syscall.WNOHANG, &rusage)
				// no children
				if pid <= 0 {
					break
				}

				logrus.Infof("Child terminated pid=%d err=%v status=%v usage=%v", pid, err, status, rusage)
			}
		}
	}()
}


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

    <RelativeLayout
        android:id="@+id/video_layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1.0" >

        <SurfaceView
            android:id="@+id/surface"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center">
        </SurfaceView>

        <View
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:background="@android:color/holo_blue_bright" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/video_layout2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_weight="1.0" >

        <VideoView
            android:id="@+id/video1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />

        <View
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:background="@android:color/holo_blue_bright" />
    </RelativeLayout>

</LinearLayout>


text:
/**
 * Test for SERVER-2417 - should not preallocate a database file while we are
 * dropping its directory in directoryperdb mode.
 */

// Preallocation is an mmap only behavior.
// @tags: [requires_mmapv1]

var baseDir = "jstests_disk_preallocate_directoryperdb";
var baseName = "preallocate_directoryperdb";
var baseName2 = "preallocate_directoryperdb2";
var baseName3 = "preallocate_directoryperdb3";
dbpath = MongoRunner.dataPath + baseDir + "/";

function checkDb2DirAbsent() {
    files = listFiles(dbpath);
    //    printjson( files );
    for (var f in files) {
        var name = files[f].name;
        assert.eq(-1, name.indexOf(dbpath + baseName2), "baseName2 dir still present");
    }
}

var m = MongoRunner.runMongod(
    {smallfiles: "", directoryperdb: "", dbpath: dbpath, bind_ip: "127.0.0.1"});
db = m.getDB(baseName);
db2 = m.getDB(baseName2);
var bulk = db[baseName].initializeUnorderedBulkOp();
var bulk2 = db2[baseName2].initializeUnorderedBulkOp();
var big = new Array(5000).toString();
for (var i = 0; i < 3000; ++i) {
    bulk.insert({b: big});
    bulk2.insert({b: big});
}
assert.writeOK(bulk.execute());
assert.writeOK(bulk2.execute());

// Due to our write pattern, we expect db2's .3 file to be queued up in the file
// allocator behind db's .3 file at the time db2 is dropped.  This will
// (incorrectly) cause db2's dir to be recreated until SERVER-2417 is fixed.
db2.dropDatabase();

checkDb2DirAbsent();

db.dropDatabase();

// Try writing a new database, to ensure file allocator is still working.
db3 = m.getDB(baseName3);
c3 = db[baseName3];
assert.writeOK(c3.insert({}));
assert.eq(1, c3.count());

checkDb2DirAbsent();


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />

        Left

          Elm modul browser


text:
FROM python

RUN pip install --upgrade pip

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

COPY src src


text:
package com.intellij.tasks.jira.jql.psi.impl;

import com.intellij.lang.ASTNode;
import com.intellij.tasks.jira.jql.psi.JqlElementVisitor;
import com.intellij.tasks.jira.jql.psi.JqlOrClause;
import javax.annotation.Nonnull;

/**
 * @author Mikhail Golubev
 */
public class JqlOrClauseImpl extends JqlBinaryClauseImpl implements JqlOrClause {
  public JqlOrClauseImpl(@Nonnull ASTNode node) {
    super(node);
  }

  @Override
  public void accept(JqlElementVisitor visitor) {
    visitor.visitJqlOrClause(this);
  }
}


text:
import {IFormModel} from '../../../models/forms/FormModel';
import {ChildWithCat} from '../../../models/base/ChildWithCat';
import {ArticleCategory} from '../../../models/ArticleCategory';

export class ArticlesCatFormModel extends ChildWithCat<ArticleCategory> implements IFormModel {
    public title: string;
    public url: string;
    public descr: string;
    public content: string;

    createCat(): ArticleCategory {
        return new ArticleCategory();
    }
}


text:
/**
 *	This JS waits until the page has loaded,
 *	 then goes and fetches all the posts
 *	 in our WordPress database, and displays
 *	 them all on our page.
 */

// Wait until the document has loaded completely
$('document').ready(function(){

	// Now, let's go fetch the WordPress posts from the API
	$.get('http://localhost/wordpress/wp-json/wp/v2/posts', function (data){

		// Once we get a successful response,
		//  lets just log it in our browser console.
		console.log(data);

		// SANITY CHECK!
		//  Make sure we have proper data

		/**
		 * The `if` just checks for a `true` value.
		 * Therefore, if data's length is not 0, this will be true.
		 *  (And an array's length can never be less than 0)
		 */
		if (data.length) {

			// So, now that we know we have some proper data,
			//  let's clear the waiting content wrapper of the
			//  `loading` message:
			$('#content').html('');

			//  Secondly, we need to loop through the array

			// Use this, if you want to:
			// for (var i = 0; i < data.length; i++) {

			// or...
			//  this one loops through the data in the opposite direction
			//  starting at the last item, and moving forward
			for (var i = data.length - 1; i >= 0; i--) {
				// Assign a variable to store the current iteration
				//  note the "data[i]" <- the `i` changes on every loop,
				//  meaning we get a different post each time we run the loop.
				var post = data[i];

				// From the browser console log (above), as well as from the
				//  endpoint itself, we can gather the JSON structure.
				// Therefore, we know that the title and content sit here:

				var title = post.title.rendered;
				var content = post.content.rendered;

				// Now all that's left to do is to actually write it onto the page!
				//  So, remember, this happens FOR EACH ITERATION of the loop we're in
				//  right now!

				// Create an empty <h2>, and pop the title into it:
				var h2 = $('<h2 />').html(title);

				// Create an empty <div>, and place the content into it:
				var div = $('<div />').html(content);

				// Now, append them to the wrapper in our HTML page:
				$('#content').append(h2);
				$('#content').append(div);

				// Done! Yay!

			};
			//  and write each post onto the page

		} else {

			// Data was returned properly,
			//  but there are no posts!

			// Let's create a warning message
			var message = "Oops, there doesn't seem to be any posts yet. " +
						  "Sign into WordPress and go create some!";

			// And place it on our page!
			$('#content').append(message);

		}

	})

	// Handle errors with the $.get()
	.fail(function(){

		// Let's create another message
		//  to let the user know what went wrong!
		var message = "Oops, it seems the WP REST API endpoint is unreachable. " +
					  "Make sure you have Apache and MySQL running, and that you're browsing from your localhost."

		// Remember, due to scope and closure, the `message` variable
		//  doesn't exist inside this {block}, so we're free to use the same name again.

		console.warn(message);
	});

}); // END: document.ready


text:
require 'flexmock/noop'

class FlexMock
  ####################################################################
  # Match any object
  class AnyMatcher
    def ===(target)
      true
    end
    def inspect
      "ANY"
    end
  end

  ####################################################################
  # Match only things that are equal.
  class EqualMatcher
    def initialize(obj)
      @obj = obj
    end
    def ===(target)
      @obj == target
    end
    def inspect
      "==(#{@obj.inspect})"
    end
  end

  ANY = AnyMatcher.new

  ####################################################################
  # Match only things where the block evaluates to true.
  class ProcMatcher
    def initialize(&block)
      @block = block
    end
    def ===(target)
      @block.call(target)
    end
    def inspect
      "on{...}"
    end
  end

  ####################################################################
  # Match only things where the block evaluates to true.
  class HashMatcher
    def initialize(hash)
      @hash = hash
    end
    def ===(target)
      @hash.all? { |k, v| target[k] == v }
    end
    def inspect
      "hsh(#{@hash.inspect})"
    end
  end

  ####################################################################
  # Match only things where the block evaluates to true.
  class DuckMatcher
    def initialize(methods)
      @methods = methods
    end
    def ===(target)
      @methods.all? { |m| target.respond_to?(m) }
    end
    def inspect
      "ducktype(#{@methods.map{|m| m.inspect}.join(',')})"
    end
  end

end


text:
using System;
using System.Threading.Tasks;

using Mobet.Events.Handlers;

namespace Mobet.Events
{
    /// <summary>
    /// An event bus that implements Null object pattern.
    /// </summary>
    public sealed class NullEventBus : IEventBus
    {
        public static IEventBus Instance { get { return _eventBus; } }
        private static readonly NullEventBus _eventBus = new NullEventBus();
        private NullEventBus()
        {
        }
        /// <inheritdoc/>
        public IDisposable Register<TEventData>(Action<TEventData> action) where TEventData : IDomainEvent
        {
            return NullDisposable.Instance;
        }

        /// <inheritdoc/>
        public IDisposable Register<TEventData>(IEventHandler<TEventData> handler) where TEventData : IDomainEvent
        {
            return NullDisposable.Instance;
        }

        /// <inheritdoc/>
        public IDisposable Register<TDomainEvent, THandler>()
            where TDomainEvent : IDomainEvent
            where THandler : IEventHandler<TDomainEvent>, new()
        {
            return NullDisposable.Instance;
        }

        /// <inheritdoc/>
        public IDisposable Register(Type eventType, IEventHandler handler)
        {
            return NullDisposable.Instance;
        }

        /// <inheritdoc/>
        public void Unregister<TEventData>(Action<TEventData> action) where TEventData : IDomainEvent
        {
        }

        /// <inheritdoc/>
        public void Unregister<TEventData>(IEventHandler<TEventData> handler) where TEventData : IDomainEvent
        {
        }

        /// <inheritdoc/>
        public void Unregister(Type eventType, IEventHandler handler)
        {
        }

        /// <inheritdoc/>
        public void UnregisterAll<TEventData>() where TEventData : IDomainEvent
        {
        }

        /// <inheritdoc/>
        public void UnregisterAll(Type eventType)
        {
        }

        /// <inheritdoc/>
        public void Trigger<TEventData>(TEventData eventData) where TEventData : IDomainEvent
        {
        }

        /// <inheritdoc/>
        public void Trigger<TEventData>(object eventSource, TEventData eventData) where TEventData : IDomainEvent
        {
        }

        /// <inheritdoc/>
        public void Trigger(Type eventType, IDomainEvent eventData)
        {
        }

        /// <inheritdoc/>
        public void Trigger(Type eventType, object eventSource, IDomainEvent eventData)
        {
        }

        /// <inheritdoc/>
        public Task TriggerAsync<TEventData>(TEventData eventData) where TEventData : IDomainEvent
        {
            return new Task(() => { });
        }

        /// <inheritdoc/>
        public Task TriggerAsync<TEventData>(object eventSource, TEventData eventData) where TEventData : IDomainEvent
        {
            return new Task(() => { });
        }

        /// <inheritdoc/>
        public Task TriggerAsync(Type eventType, IDomainEvent eventData)
        {
            return new Task(() => { });
        }

        /// <inheritdoc/>
        public Task TriggerAsync(Type eventType, object eventSource, IDomainEvent eventData)
        {
            return new Task(() => { });
        }
    }
}


text:
package org.darkstorm.darkbot.minecraftbot.event.protocol.client;

import org.darkstorm.darkbot.minecraftbot.event.protocol.ProtocolEvent;
import org.darkstorm.darkbot.minecraftbot.world.block.BlockLocation;

public abstract class BlockEvent extends ProtocolEvent {
	private final int x, y, z;

	public BlockEvent(BlockLocation location) {
		this(location.getX(), location.getY(), location.getZ());
	}

	public BlockEvent(int x, int y, int z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	public int getZ() {
		return z;
	}
}


text:
View per faculty

     View overall

<?php

?>

Fellowship Baptist College

Rizal Street, Kabankalan City

<?php echo $college_name; ?>

    Fullname
    Role
    Student
    Peer
    Program Head
    Dean

    <?php
      foreach( $faculties as $fac ):
        $fullname = $fac->lastname . ', ' . $fac->firstname . ' ' . $fac->middlename;
        $stud = 'id.'/1" target="_blank"> Print';
        $peer = 'id.'/2" target="_blank"> Print';
        $prog = 'id.'/3" target="_blank"> Print';
        $dean = 'id.'/4" target="_blank"> Print';

        if ( $fac->role == '3' ) {
          $stud = 'NA';
          $prog = 'NA';
        }
    ?>

      <?php echo $fullname; ?>
      <?php echo strtoupper($fac->rolename); ?>
      <?php echo $stud;?>
      <?php echo $peer;?>
      <?php echo $prog;?>
      <?php echo $dean;?>
    <?php endforeach; ?>


text:
classdef NedelecShapeFunction < handle
    methods (Static)
        function v = evaluate(op, fun, kfun, msh, X, els, varargin)
            if (fun == ShapeFunctions.nedelec) && (msh.elementType == Elements.prism)
                C = NedelecShapeFunction.PrismCoefficients(op);
                vloc = C{kfun}*...
                    PolynomialBasis3D.bteval(X, BasisTypes.bilinearz3);
                if ~any(els) || els(1) < -1
                    els = 1:size(msh.elements,2);
                end
                if numel(varargin) == 2
                    F = varargin{1};
                    detF = varargin{2};
                else
                    F = msh.getMappingMatrix(els);
                    detF = matrixDeterminant(F);
                end
                if op == Operators.I
                    v = matrixTimesVector(F, vloc, true, true, detF);
                elseif op == Operators.curl
                    v = bsxfun(@rdivide, matrixTimesVector(F, vloc, false, false), detF);
                else
                    error(['Operator ' char(op) ' not yet implemented.']);
                end
                v = bsxfun(@times, v, sign(msh.elements2edges(kfun, els)));
            end
        end

        function C = PrismCoefficients(op)
            persistent CI Ccurl
            switch op
                case Operators.I
                    if isempty(CI)
                    	CI = preCompute_referenceShapeFunctions(Elements.prism, ShapeFunctions.nedelec);
                    end
                    C = CI; return;
                case Operators.curl
                    if isempty(Ccurl)
                        Ctemp = Nedelec_Prism.getCoefficients(Operators.I);
                        Ccurl = PolynomialBasis3D.curl_coeffs(Ctemp, Elements.prism, ShapeFunctions.nedelec);
                    end
                    C = Ccurl; return
                otherwise
                    error('Operator type not yet implemented')
            end

        end
    end
end


text:
/*global define*/
// ignore non-camel case decided by server
/* jshint -W106*/
define(['underscore', 'backbone'], function(_, Backbone) {
    'use strict';

    var UserRequestModel = Backbone.Model.extend({
        url: function() {
            return '/api/v2/cluster/' + this.get('cluster') + '/request/' + this.get('id');
        },
        defaults: {
            id: 0,
            cluster: 1
        }
    });
    return UserRequestModel;
});


text:
package com.github.wojtuch.boxer2java.models;

import java.util.List;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;

import com.github.wojtuch.boxer2java.models.unioninterfaces.DrsMergeAlfa;

public class Alfa implements DrsMergeAlfa
{
	@Attribute(name="type")
	private String type;

	@ElementListUnion({
			@ElementList(entry="drs", inline=true, type=Drs.class),
			@ElementList(entry="merge", inline=true, type=Merge.class),
			@ElementList(entry="alfa", inline=true, type=Alfa.class)
	})
	private List<DrsMergeAlfa> dmas;

	public Alfa()
	{
	}

	public List<DrsMergeAlfa> getDMAAlternatives()
	{
		return dmas;
	}

	public void setDMAAlternatives(List<DrsMergeAlfa> dmas)
	{
		this.dmas = dmas;
	}

	public String getType()
	{
		return type;
	}

	public void setType(String type)
	{
		this.type = type;
	}
}


text:
<bill session="110" type="h" number="4212" updated="2009-01-09T01:37:57-05:00">
	<status><introduced date="1195102800" datetime="2007-11-15"/></status>

	<introduced date="1195102800" datetime="2007-11-15"/>
	<titles>
		<title type="official" as="introduced">To authorize the Administrator of the Small Business Administration to deem certain small business concerns qualified HUBZone small business concerns.</title>
	</titles>
	<sponsor id="400084"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1195102800" datetime="2007-11-15"><text>Referred to the House Committee on Small Business.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	11/15/2007--Introduced.
Amends the Small Business Act to authorize the Administrator of the Small Business Administration (SBA) to deem a small business a qualified HUBZone (heavily underutilized business zone) small business if such small business has certified to the Administrator that: (1) it is not currently a HUBZone small business; (2) its principal office is located in a census tract adjacent to a HUBZone; (3) at least 35% of the employees reside in a HUBZone; and (4) it meets current SBA requirements applicable to qualified HUBZone small businesses.

</bill>


text:
#pragma once

#include "../core/GLImageAllocator.h"

#import <CoreVideo/CoreVideo.h>

template <class T>
class IOSGLImageAllocator : public GLImageAllocator<T> {
  static const GLTexture::Type& type;

  std::vector<CVPixelBufferRef> pixelbuffers;

 public:
  static const FourCharCode pixelFormat;

  IOSGLImageAllocator() : GLImageAllocator<T>() { gl_log(GL_VERBOSE, "%s\n", __PRETTY_FUNCTION__); }

  ~IOSGLImageAllocator() {
    gl_log(GL_VERBOSE, "%s\n", __PRETTY_FUNCTION__);

    for (auto&& pixelbuffer : pixelbuffers) {
      CFRelease(pixelbuffer);
    }
  }

  GLImageVector<T>* newImage(int num_images,
                             int width,
                             int height,
                             int channels,
                             int tile_x,
                             int tile_y,
                             bool useCVPixelBuffer);
};


text:
package tabletserver

import (
	"net/http"
	"sync"
	"time"

	log "github.com/golang/glog"
	"golang.org/x/net/context"

	"github.com/youtube/vitess/go/stats"
	"github.com/youtube/vitess/go/sync2"
	"github.com/youtube/vitess/go/vt/dbconfigs"
	"github.com/youtube/vitess/go/vt/dbconnpool"
	"github.com/youtube/vitess/go/vt/logutil"
	vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
	"github.com/youtube/vitess/go/vt/tableacl"
	"github.com/youtube/vitess/go/vt/tableacl/acl"
)

// spotCheckMultiplier determines the precision of the
// spot check ratio: 1e6 == 6 digits
const spotCheckMultiplier = 1e6

// QueryEngine implements the core functionality of tabletserver.
// It assumes that no requests will be sent to it before Open is
// called and succeeds.
// Shutdown is done in the following order:
//
// WaitForTxEmpty: There should be no more new calls to Begin
// once this function is called. This will return when there
// are no more pending transactions.
//
// Close: There should be no more pending queries when this
// function is called.
//
// Functions of QueryEngine do not return errors. They instead
// panic with NewTabletError as the error type.
// TODO(sougou): Switch to error return scheme.
type QueryEngine struct {
	schemaInfo *SchemaInfo
	config     Config
	dbconfigs  dbconfigs.DBConfigs

	// Pools
	cachePool      *CachePool
	connPool       *ConnPool
	streamConnPool *ConnPool

	// Services
	txPool       *TxPool
	consolidator *sync2.Consolidator
	streamQList  *QueryList
	tasks        sync.WaitGroup

	// Vars
	spotCheckFreq    sync2.AtomicInt64
	strictMode       sync2.AtomicInt64
	autoCommit       sync2.AtomicInt64
	maxResultSize    sync2.AtomicInt64
	maxDMLRows       sync2.AtomicInt64
	streamBufferSize sync2.AtomicInt64
	// tableaclExemptCount count the number of accesses allowed
	// based on membership in the superuser ACL
	tableaclExemptCount  sync2.AtomicInt64
	tableaclAllowed      *stats.MultiCounters
	tableaclDenied       *stats.MultiCounters
	tableaclPseudoDenied *stats.MultiCounters
	strictTableAcl       bool
	enableTableAclDryRun bool
	exemptACL            acl.ACL

	// Loggers
	accessCheckerLogger *logutil.ThrottledLogger

	// Stats
	queryServiceStats *QueryServiceStats
}

type compiledPlan struct {
	Query string
	*ExecPlan
	BindVars      map[string]interface{}
	TransactionID int64
}

// CacheInvalidator provides the abstraction needed for an instant invalidation
// vs. delayed invalidation in the case of in-transaction dmls
type CacheInvalidator interface {
	Delete(key string)
}

// Helper method for conn pools to convert errors
func getOrPanic(ctx context.Context, pool *ConnPool) *DBConn {
	conn, err := pool.Get(ctx)
	if err == nil {
		return conn
	}
	if err == ErrConnPoolClosed {
		panic(ErrConnPoolClosed)
	}
	// If there's a problem with getting a connection out of the pool, that is
	// probably not due to the query itself. The query might succeed on a different
	// tablet.
	panic(NewTabletErrorSQL(vtrpcpb.ErrorCode_INTERNAL_ERROR, err))
}

// NewQueryEngine creates a new QueryEngine.
// This is a singleton class.
// You must call this only once.
func NewQueryEngine(checker MySQLChecker, config Config) *QueryEngine {
	qe := &QueryEngine{config: config}
	qe.queryServiceStats = NewQueryServiceStats(config.StatsPrefix, config.EnablePublishStats)

	qe.cachePool = NewCachePool(
		config.PoolNamePrefix+"Rowcache",
		config.RowCache,
		time.Duration(config.IdleTimeout*1e9),
		config.DebugURLPrefix+"/memcache/",
		config.EnablePublishStats,
		qe.queryServiceStats,
	)
	qe.schemaInfo = NewSchemaInfo(
		config.StatsPrefix,
		checker,
		config.QueryCacheSize,
		time.Duration(config.SchemaReloadTime*1e9),
		time.Duration(config.IdleTimeout*1e9),
		qe.cachePool,
		map[string]string{
			debugQueryPlansKey: config.DebugURLPrefix + "/query_plans",
			debugQueryStatsKey: config.DebugURLPrefix + "/query_stats",
			debugTableStatsKey: config.DebugURLPrefix + "/table_stats",
			debugSchemaKey:     config.DebugURLPrefix + "/schema",
			debugQueryRulesKey: config.DebugURLPrefix + "/query_rules",
		},
		config.EnablePublishStats,
		qe.queryServiceStats,
	)

	qe.connPool = NewConnPool(
		config.PoolNamePrefix+"ConnPool",
		config.PoolSize,
		time.Duration(config.IdleTimeout*1e9),
		config.EnablePublishStats,
		qe.queryServiceStats,
		checker,
	)
	qe.streamConnPool = NewConnPool(
		config.PoolNamePrefix+"StreamConnPool",
		config.StreamPoolSize,
		time.Duration(config.IdleTimeout*1e9),
		config.EnablePublishStats,
		qe.queryServiceStats,
		checker,
	)

	qe.txPool = NewTxPool(
		config.PoolNamePrefix+"TransactionPool",
		config.StatsPrefix,
		config.TransactionCap,
		time.Duration(config.TransactionTimeout*1e9),
		time.Duration(config.IdleTimeout*1e9),
		config.EnablePublishStats,
		qe.queryServiceStats,
		checker,
	)
	qe.consolidator = sync2.NewConsolidator()
	http.Handle(config.DebugURLPrefix+"/consolidations", qe.consolidator)
	qe.streamQList = NewQueryList()

	qe.spotCheckFreq = sync2.NewAtomicInt64(int64(config.SpotCheckRatio * spotCheckMultiplier))
	if config.StrictMode {
		qe.strictMode.Set(1)
	}
	if config.EnableAutoCommit {
		qe.autoCommit.Set(1)
	}
	qe.strictTableAcl = config.StrictTableAcl
	qe.enableTableAclDryRun = config.EnableTableAclDryRun

	if config.TableAclExemptACL != "" {
		if f, err := tableacl.GetCurrentAclFactory(); err == nil {
			if exemptACL, err := f.New([]string{config.TableAclExemptACL}); err == nil {
				log.Infof("Setting Table ACL exempt rule for %v", config.TableAclExemptACL)
				qe.exemptACL = exemptACL
			} else {
				log.Infof("Cannot build exempt ACL for table ACL: %v", err)
			}
		} else {
			log.Infof("Cannot get current ACL Factory: %v", err)
		}
	}

	qe.maxResultSize = sync2.NewAtomicInt64(int64(config.MaxResultSize))
	qe.maxDMLRows = sync2.NewAtomicInt64(int64(config.MaxDMLRows))
	qe.streamBufferSize = sync2.NewAtomicInt64(int64(config.StreamBufferSize))

	qe.accessCheckerLogger = logutil.NewThrottledLogger("accessChecker", 1*time.Second)

	var tableACLAllowedName string
	var tableACLDeniedName string
	var tableACLPseudoDeniedName string
	if config.EnablePublishStats {
		stats.Publish(config.StatsPrefix+"MaxResultSize", stats.IntFunc(qe.maxResultSize.Get))
		stats.Publish(config.StatsPrefix+"MaxDMLRows", stats.IntFunc(qe.maxDMLRows.Get))
		stats.Publish(config.StatsPrefix+"StreamBufferSize", stats.IntFunc(qe.streamBufferSize.Get))
		stats.Publish(config.StatsPrefix+"RowcacheSpotCheckRatio", stats.FloatFunc(func() float64 {
			return float64(qe.spotCheckFreq.Get()) / spotCheckMultiplier
		}))
		stats.Publish(config.StatsPrefix+"TableACLExemptCount", stats.IntFunc(qe.tableaclExemptCount.Get))
		tableACLAllowedName = "TableACLAllowed"
		tableACLDeniedName = "TableACLDenied"
		tableACLPseudoDeniedName = "TableACLPseudoDenied"
	}

	qe.tableaclAllowed = stats.NewMultiCounters(tableACLAllowedName, []string{"TableName", "TableGroup", "PlanID", "Username"})
	qe.tableaclDenied = stats.NewMultiCounters(tableACLDeniedName, []string{"TableName", "TableGroup", "PlanID", "Username"})
	qe.tableaclPseudoDenied = stats.NewMultiCounters(tableACLPseudoDeniedName, []string{"TableName", "TableGroup", "PlanID", "Username"})

	return qe
}

// Open must be called before sending requests to QueryEngine.
func (qe *QueryEngine) Open(dbconfigs dbconfigs.DBConfigs, schemaOverrides []SchemaOverride) {
	qe.dbconfigs = dbconfigs
	appParams := dbconfigs.App.ConnParams
	// Create dba params based on App connection params
	// and Dba credentials.
	dbaParams := dbconfigs.App.ConnParams
	if dbconfigs.Dba.Uname != "" {
		dbaParams.Uname = dbconfigs.Dba.Uname
		dbaParams.Pass = dbconfigs.Dba.Pass
	}

	strictMode := false
	if qe.strictMode.Get() != 0 {
		strictMode = true
	}
	if !strictMode && qe.config.RowCache.Enabled {
		panic(NewTabletError(vtrpcpb.ErrorCode_INTERNAL_ERROR, "Rowcache cannot be enabled when queryserver-config-strict-mode is false"))
	}
	if qe.config.RowCache.Enabled {
		qe.cachePool.Open()
		log.Infof("rowcache is enabled")
	} else {
		log.Infof("rowcache is not enabled")
	}

	start := time.Now()
	// schemaInfo depends on cachePool. Every table that has a rowcache
	// points to the cachePool.
	qe.schemaInfo.Open(&appParams, &dbaParams, schemaOverrides, strictMode)
	log.Infof("Time taken to load the schema: %v", time.Now().Sub(start))

	qe.connPool.Open(&appParams, &dbaParams)
	qe.streamConnPool.Open(&appParams, &dbaParams)
	qe.txPool.Open(&appParams, &dbaParams)
}

// Launch launches the specified function inside a goroutine.
// If Close or WaitForTxEmpty is called while a goroutine is running,
// QueryEngine will not return until the existing functions have completed.
// This functionality allows us to launch tasks with the assurance that
// the QueryEngine will not be closed underneath us.
func (qe *QueryEngine) Launch(f func()) {
	qe.tasks.Add(1)
	go func() {
		defer func() {
			qe.tasks.Done()
			if x := recover(); x != nil {
				qe.queryServiceStats.InternalErrors.Add("Task", 1)
				log.Errorf("task error: %v", x)
			}
		}()
		f()
	}()
}

// IsMySQLReachable returns true if we can connect to MySQL.
func (qe *QueryEngine) IsMySQLReachable() bool {
	conn, err := dbconnpool.NewDBConnection(&qe.dbconfigs.App.ConnParams, qe.queryServiceStats.MySQLStats)
	if err != nil {
		if IsConnErr(err) {
			return false
		}
		log.Warningf("checking MySQL, unexpected error: %v", err)
		return true
	}
	conn.Close()
	return true
}

// WaitForTxEmpty must be called before calling Close.
// Before calling WaitForTxEmpty, you must ensure that there
// will be no more calls to Begin.
func (qe *QueryEngine) WaitForTxEmpty() {
	qe.txPool.WaitForEmpty()
}

// Close must be called to shut down QueryEngine.
// You must ensure that no more queries will be sent
// before calling Close.
func (qe *QueryEngine) Close() {
	qe.tasks.Wait()
	// Close in reverse order of Open.
	qe.txPool.Close()
	qe.streamConnPool.Close()
	qe.connPool.Close()
	qe.schemaInfo.Close()
	qe.cachePool.Close()
}

// Commit commits the specified transaction.
func (qe *QueryEngine) Commit(ctx context.Context, logStats *LogStats, transactionID int64) {
	dirtyTables, err := qe.txPool.SafeCommit(ctx, transactionID)
	for tableName, invalidList := range dirtyTables {
		tableInfo := qe.schemaInfo.GetTable(tableName)
		if tableInfo == nil {
			continue
		}
		invalidations := int64(0)
		for key := range invalidList {
			// Use context.Background, becaause we don't want to fail
			// these deletes.
			tableInfo.Cache.Delete(context.Background(), key)
			invalidations++
		}
		logStats.CacheInvalidations += invalidations
		tableInfo.invalidations.Add(invalidations)
	}
	if err != nil {
		panic(err)
	}
}

// ClearRowcache invalidates all items in the rowcache.
func (qe *QueryEngine) ClearRowcache(ctx context.Context) error {
	if qe.cachePool.IsClosed() {
		return NewTabletError(vtrpcpb.ErrorCode_INTERNAL_ERROR, "rowcache is not up")
	}
	conn := qe.cachePool.Get(ctx)
	defer func() { qe.cachePool.Put(conn) }()

	if err := conn.FlushAll(); err != nil {
		conn.Close()
		conn = nil
		return NewTabletError(vtrpcpb.ErrorCode_INTERNAL_ERROR, "%s", err)
	}
	return nil
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<title>Steven Skelton:Software Developer</title>

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css">

<link rel="stylesheet" href="../css/main.css" type="text/css" media="screen, projection"/>

<link  href="http://fonts.googleapis.com/css?family=Droid+Sans+Mono" rel="stylesheet" type="text/css">

Steven Skelton

Software Developer

Blog

Code

Twitter

Facebook

Last.FM

Email

CV


text:
#ifndef _MAGICKCORE_EFFECT_H
#define _MAGICKCORE_EFFECT_H

#include "MagickCore/morphology.h"

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

typedef enum
{
  UndefinedPreview,
  RotatePreview,
  ShearPreview,
  RollPreview,
  HuePreview,
  SaturationPreview,
  BrightnessPreview,
  GammaPreview,
  SpiffPreview,
  DullPreview,
  GrayscalePreview,
  QuantizePreview,
  DespecklePreview,
  ReduceNoisePreview,
  AddNoisePreview,
  SharpenPreview,
  BlurPreview,
  ThresholdPreview,
  EdgeDetectPreview,
  SpreadPreview,
  SolarizePreview,
  ShadePreview,
  RaisePreview,
  SegmentPreview,
  SwirlPreview,
  ImplodePreview,
  WavePreview,
  OilPaintPreview,
  CharcoalDrawingPreview,
  JPEGPreview
} PreviewType;

extern MagickExport Image
  *AdaptiveBlurImage(const Image *,const double,const double,ExceptionInfo *),
  *AdaptiveSharpenImage(const Image *,const double,const double,
     ExceptionInfo *),
  *BlurImage(const Image *,const double,const double,ExceptionInfo *),
  *ConvolveImage(const Image *,const KernelInfo *,ExceptionInfo *),
  *DespeckleImage(const Image *,ExceptionInfo *),
  *EdgeImage(const Image *,const double,ExceptionInfo *),
  *EmbossImage(const Image *,const double,const double,ExceptionInfo *),
  *GaussianBlurImage(const Image *,const double,const double,ExceptionInfo *),
  *KuwaharaImage(const Image *,const double,const double,ExceptionInfo *),
  *MotionBlurImage(const Image *,const double,const double,const double,
    ExceptionInfo *),
  *PreviewImage(const Image *,const PreviewType,ExceptionInfo *),
  *RotationalBlurImage(const Image *,const double,ExceptionInfo *),
  *SelectiveBlurImage(const Image *,const double,const double,const double,
    ExceptionInfo *),
  *ShadeImage(const Image *,const MagickBooleanType,const double,const double,
    ExceptionInfo *),
  *SharpenImage(const Image *,const double,const double,ExceptionInfo *),
  *SpreadImage(const Image *,const double,const PixelInterpolateMethod,
    ExceptionInfo *),
  *UnsharpMaskImage(const Image *,const double,const double,const double,
    const double,ExceptionInfo *);

#if defined(__cplusplus) || defined(c_plusplus)
}
#endif

#endif


text:
package org.codehaus.xfire.aegis.type.xml;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.aegis.MessageReader;
import org.codehaus.xfire.aegis.MessageWriter;
import org.codehaus.xfire.aegis.stax.ElementReader;
import org.codehaus.xfire.aegis.stax.ElementWriter;
import org.codehaus.xfire.aegis.type.Type;
import org.codehaus.xfire.fault.XFireFault;
import org.codehaus.xfire.util.STAXUtils;

/**
 * Reads and writes org.w3c.dom.Document types.
 *
 * @author Dan Diephouse
 */
public class XMLStreamReaderType
    extends Type
{
    public XMLStreamReaderType()
    {
        setWriteOuter(false);
    }

    public Object readObject(MessageReader mreader, MessageContext context)
        throws XFireFault
    {
        return ((ElementReader) mreader).getXMLStreamReader();
    }

    public void writeObject(Object object, MessageWriter writer, MessageContext context)
        throws XFireFault
    {
        XMLStreamReader reader = (XMLStreamReader) object;

        try
        {
            STAXUtils.copy(reader, ((ElementWriter) writer).getXMLStreamWriter());
            reader.close();
        }
        catch (XMLStreamException e)
        {
            throw new XFireFault("Could not write xml.", e, XFireFault.SENDER);
        }
    }
}