text:
"use strict";

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var Tabpane = React.createClass({
    displayName: "Tabpane",
    render: function render() {
        return;
    }
});

var Tabnav = React.createClass({
    displayName: "Tabnav",
    onClick: function onClick() {
        this.props.tabClick(this.props.tab_id);
    },
    render: function render() {
        return React.createElement(
            "div",
            { className: this.props.class, onClick: this.onClick },
            this.props.tab
        );
    }
});

var Tabs = React.createClass({
    displayName: "Tabs",
    getInitialState: function getInitialState() {
        var live = React.Children.map(this.props.children, function (val) {
            return false;
        });
        return { now_tab: 0, live: live };
    },
    tabClick: function tabClick(n) {
        this.setState({ now_tab: n });
    },
    render: function render() {
        var tab_navs = [];
        var tab_contents = [];

        var children = this.props.children;
        var now_tab = this.state.now_tab;
        var live = this.state.live;

        React.Children.forEach(children, function (val, n) {
            var tab_class = "tab-nav";
            var list_class = "tab-tabpane tab-tabpane-hidden";
            var aria_hidden = "false";
            if (now_tab == n) {
                tab_class = "tab-nav tab-selected";
                list_class = "tab-tabpane";
                aria_hidden = "true";
            }
            if (now_tab == n) live[n] = true;
            tab_navs.push(React.createElement(Tabnav, _extends({}, val.props, { tab_id: n, tabClick: this.tabClick, "class": tab_class, now_tab: now_tab })));

            if (live[n]) tab_contents.push(React.createElement(
                "div",
                { "aria-hidden": aria_hidden, className: list_class },
                val.props.children
            ));
        }.bind(this));

        return React.createElement(
            "div",
            { className: "tab" },
            React.createElement(
                "div",
                { className: "tab-list" },
                tab_navs
            ),
            React.createElement(
                "div",
                { className: "tab-content" },
                tab_contents
            )
        );
    }
});

var _antd = antd;
var Pagination = _antd.Pagination;
var Spin = _antd.Spin;
var Popconfirm = _antd.Popconfirm;
var message = _antd.message;

var Zen_item = React.createClass({
    displayName: "Zen_item",
    render: function render() {
        var _this = this;

        var data = this.props.data;
        var p = data.loc_province;
        var c = data.loc_city;
        var a = mengwu.address_json;
        var b = _.find(a, ['value', p]);
        var address = "";
        if (b) {
            var pt = b.label;
            var _a = _.find(b.children, ['value', c]);
            if (_a) {
                var ct = _a.label;
                address = pt + ct;
            }
        }
        var url = document.getElementsByTagName('base')[0].href;
        var img_list = data.show_imgs ? data.show_imgs.map(function (val) {
            return React.createElement(
                "li",
                null,
                React.createElement(
                    "a",
                    { href: "javascript:void(0);" },
                    " ",
                    React.createElement("img", { src: val })
                )
            );
        }) : null;
        return React.createElement(
            "div",
            { className: "zengwuxian" },
            React.createElement(
                "div",
                { className: "user-info" },
                React.createElement(
                    "div",
                    { className: "head" },
                    React.createElement("img", { src: data.head })
                ),
                React.createElement(
                    "div",
                    { className: "user-right" },
                    React.createElement(
                        "div",
                        { className: "name" },
                        data.nickname
                    ),
                    React.createElement(
                        "div",
                        { "class": "tp" },
                        React.createElement(
                            "span",
                            { className: "time" },
                            data.create_time_show
                        ),
                        React.createElement(
                            "span",
                            { className: "pos" },
                            address
                        )
                    ),
                    React.createElement(
                        Popconfirm,
                        { title: "确定要取消收藏吗?", onConfirm: function onConfirm() {
                                return _this.props.delete(data.pid);
                            } },
                        React.createElement(
                            "a",
                            { className: "delete", href: "javascript:void(0);" },
                            React.createElement("img", { src: url + 'Public/Mengwu/img/user/favorite/delete.png' })
                        )
                    )
                )
            ),
            React.createElement(
                "div",
                { className: "zcontent" },
                React.createElement(
                    "ul",
                    null,
                    img_list
                )
            ),
            React.createElement(
                "div",
                { className: "caption" },
                React.createElement("img", { src: url + 'Public/Mengwu/img/user/favorite/zengwuxian.png' }),
                " ",
                React.createElement(
                    "h4",
                    null,
                    React.createElement(
                        "a",
                        { href: "javascript:void(0);" },
                        data.name
                    )
                )
            )
        );
    }
});

var Yu_item = React.createClass({
    displayName: "Yu_item",
    render: function render() {
        var _this2 = this;

        var data = this.props.data;
        var fenlei = data.fid == 7 ? '热门分享' : data.fid == 8 ? '宝妈提问' : '';
        var type = data.fid == 7 ? 'share' : data.fid == 8 ? 'question' : '';
        var url = document.getElementsByTagName('base')[0].href;
        var t_url = getBaseUrl() + '/mengwu/yuerjing/detail/type/' + type + '/tid/' + data.tid;
        return React.createElement(
            "div",
            { className: "yuerjing" },
            React.createElement(
                "div",
                { className: "user-info" },
                React.createElement(
                    "div",
                    { className: "head" },
                    React.createElement("img", { src: data.author_info.head || null })
                ),
                React.createElement(
                    "div",
                    { className: "user-right" },
                    React.createElement(
                        "div",
                        { className: "name" },
                        data.author_info.nickname || 'null'
                    ),
                    React.createElement(
                        "div",
                        { className: "reason" },
                        React.createElement(
                            "div",
                            { className: "text" },
                            React.createElement(
                                "a",
                                { href: t_url, target: "_blank" },
                                data.subject || '无标题'
                            )
                        ),
                        React.createElement(
                            "div",
                            { className: "fenlei" },
                            fenlei
                        )
                    ),
                    React.createElement(
                        Popconfirm,
                        { title: "确定要取消收藏吗?", onConfirm: function onConfirm() {
                                return _this2.props.delete(data.tid);
                            } },
                        React.createElement(
                            "a",
                            { href: "javascript:void(0);", className: "delete" },
                            React.createElement("img", { src: url + 'Public/Mengwu/img/user/favorite/delete.png' })
                        )
                    )
                )
            ),
            React.createElement(
                "div",
                { className: "yuanwen" },
                React.createElement(
                    "a",
                    { href: t_url, target: "_blank" },
                    data.message
                )
            )
        );
    }
});

var Zenwuxian = React.createClass({
    displayName: "Zenwuxian",
    getInitialState: function getInitialState() {
        return {
            nowPage: 1,
            num: 0,
            page_size: 5,
            list: [],
            loading: true
        };
    },
    componentDidMount: function componentDidMount() {
        this.jumpPage(1);
    },
    jumpPage: function jumpPage(page_no) {
        var url = getBaseUrl() + '/mengwu/mengwuApi/product_favorites_gift';
        var data = {
            page_no: page_no,
            page_size: this.state.page_size
        };

        _post(url, jQuery.param(data), { data_back: function (data) {
                if (data.status) {
                    this.setState({ list: data.info.list, num: data.info.count, loading: false, nowPage: page_no });
                } else {
                    if (typeof data.info.redirect != "undefined") {
                        window.location.href = data.info.redirect;
                    }
                }
            }.bind(this) });
    },
    PaginationChange: function PaginationChange(page) {
        this.setState({ loading: true, list: [] });
        $('html, body').animate({
            scrollTop: 0
        }, 200);
        this.jumpPage(page);
    },
    delete: function _delete(pid) {
        this.setState({ loading: true });
        var url = getBaseUrl() + '/mengwu/mengwuApi/zengwuxian_favorite_favorites';
        var data = {
            pid: pid,
            favorite_value: 0
        };

        _post(url, jQuery.param(data), { data_back: function (data) {
                if (data.status) {
                    this.setState({ loading: false });
                    message.success('取消成功');
                    this.jumpPage(this.state.nowPage);
                    $('html, body').animate({
                        scrollTop: 0
                    }, 200);
                } else {
                    if (typeof data.info.redirect != "undefined") {
                        window.location.href = data.info.redirect;
                    }
                }
            }.bind(this) });
    },
    render: function render() {
        var list = this.state.list.map(function (val) {
            return React.createElement(Zen_item, { data: val, "delete": this.delete });
        }.bind(this));

        var page = [];
        if (!this.state.loading) {
            if (this.state.list.length != 0) {
                page = React.createElement(
                    "div",
                    { className: "pagination-wrap" },
                    React.createElement(
                        "div",
                        { className: "pagination-middle" },
                        React.createElement(Pagination, { current: this.state.nowPage, total: this.state.num, pageSize: this.state.page_size, onChange: this.PaginationChange })
                    )
                );
            } else {
                list = React.createElement(
                    "div",
                    { className: "text-center", style: { marginTop: 50 } },
                    "没有收藏任何帖子哟~"
                );
            }
        }
        return React.createElement(
            Spin,
            { spinning: this.state.loading },
            React.createElement(
                "div",
                { className: "post-list" },
                list,
                page
            )
        );
    }
});
var Yuerjing = React.createClass({
    displayName: "Yuerjing",
    getInitialState: function getInitialState() {
        return {
            nowPage: 1,
            num: 0,
            page_size: 5,
            list: [],
            loading: true
        };
    },
    componentDidMount: function componentDidMount() {
        this.jumpPage(1);
    },
    jumpPage: function jumpPage(page_no) {
        var url = getBaseUrl() + '/mengwu/yuerjing/yej_getFavorites';
        var data = {
            page_no: page_no,
            page_size: this.state.page_size
        };

        _post(url, jQuery.param(data), { data_back: function (data) {
                if (data.status) {
                    this.setState({ list: data.info.list, num: data.info.count, loading: false, nowPage: page_no });
                } else {
                    if (typeof data.info.redirect != "undefined") {
                        window.location.href = data.info.redirect;
                    }
                }
            }.bind(this) });
    },
    PaginationChange: function PaginationChange(page) {
        this.setState({ loading: true, list: [] });
        $('html, body').animate({
            scrollTop: 0
        }, 200);
        this.jumpPage(page);
    },
    delete: function _delete(tid) {
        this.setState({ loading: true });
        var url = getBaseUrl() + '/mengwu/mengwuApi/post_favorites';
        var data = {
            tid: tid,
            favorite_value: 0
        };

        _post(url, jQuery.param(data), { data_back: function (data) {
                if (data.status) {
                    this.setState({ loading: false });
                    message.success('取消成功');
                    this.jumpPage(this.state.nowPage);
                    $('html, body').animate({
                        scrollTop: 0
                    }, 200);
                } else {
                    if (typeof data.info.redirect != "undefined") {
                        window.location.href = data.info.redirect;
                    }
                }
            }.bind(this) });
    },
    render: function render() {
        var list = this.state.list.map(function (val) {
            return React.createElement(Yu_item, { data: val, "delete": this.delete });
        }.bind(this));

        var page = [];
        if (!this.state.loading) {
            if (this.state.list.length != 0) {
                page = React.createElement(
                    "div",
                    { className: "pagination-wrap" },
                    React.createElement(
                        "div",
                        { className: "pagination-middle" },
                        React.createElement(Pagination, { current: this.state.nowPage, total: this.state.num, pageSize: this.state.page_size, onChange: this.PaginationChange })
                    )
                );
            } else {
                list = React.createElement(
                    "div",
                    { className: "text-center", style: { marginTop: 50 } },
                    "没有收藏任何帖子哟~"
                );
            }
        }
        return React.createElement(
            Spin,
            { spinning: this.state.loading },
            React.createElement(
                "div",
                { className: "post-list" },
                list,
                page
            )
        );
    }
});

var Favorite_posts = React.createClass({
    displayName: "Favorite_posts",
    getDefaultProps: function getDefaultProps() {
        return { data: [] };
    },
    render: function render() {
        return React.createElement(
            Tabs,
            null,
            React.createElement(
                Tabpane,
                { tab: "赠无限" },
                React.createElement(Zenwuxian, null)
            ),
            React.createElement(
                Tabpane,
                { tab: "育儿经" },
                React.createElement(Yuerjing, null)
            )
        );
    }
});

ReactDOM.render(React.createElement(Favorite_posts, null), document.getElementById('favorite_post'));

//# sourceMappingURL=common.js.map

redpajama_set_name: RedPajamaGithub


text:
class Speakertalk < ActiveRecord::Base
  belongs_to :speaker
  belongs_to :talk
end


text:
import { getEditor } from './../editors';
import { getRenderer } from './../renderers';
import { getValidator } from './../validators';

const CELL_TYPE = 'date';

export default {
  editor: getEditor(CELL_TYPE),
  // displays small gray arrow on right side of the cell
  renderer: getRenderer('autocomplete'),
  validator: getValidator(CELL_TYPE),
};


text:
package fi.agisol.checkout.exceptions;

// @ResponseStatus(HttpStatus.FORBIDDEN)
public class PaymentResultValidationException extends CheckoutExceptionBase {

	private static final long serialVersionUID = -2277793579447226049L;

	public PaymentResultValidationException(String violations) {
		super("CheckoutPaymentResult had following validation violations: " +
				System.lineSeparator() + violations);
	}

}


text:
<?php

namespace Xabbuh\PandaClient\Model;

/**
 * Model representing a profile configuration.
 *
 * @author Christian Flothmann <christian.flothmann@xabbuh.de>
 */
class Profile implements ModelInterface
{
    private $id;

    private $title;

    private $name;

    private $presetName;

    private $extname;

    private $width;

    private $height;

    private $upscale;

    private $aspectMode;

    private $twoPass;

    private $videoBitrate;

    private $fps;

    private $keyframeInterval;

    private $keyframeRate;

    private $audioBitrate;

    private $audioSampleRate;

    private $audioChannels;

    private $clipLength;

    private $clipOffset;

    private $frameCount;

    private $command;

    private $createdAt;

    private $updatedAt;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

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

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

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getPresetName()
    {
        return $this->presetName;
    }

    public function setPresetName($presetName)
    {
        $this->presetName = $presetName;
    }

    public function getExtname()
    {
        return $this->extname;
    }

    public function setExtname($extname)
    {
        $this->extname = $extname;
    }

    public function getWidth()
    {
        return $this->width;
    }

    public function setWidth($width)
    {
        $this->width = $width;
    }

    public function getHeight()
    {
        return $this->height;
    }

    public function setHeight($height)
    {
        $this->height = $height;
    }

    public function getUpscale()
    {
        return $this->upscale;
    }

    public function setUpscale($upscale)
    {
        $this->upscale = $upscale;
    }

    public function getAspectMode()
    {
        return $this->aspectMode;
    }

    public function setAspectMode($aspectMode)
    {
        $this->aspectMode = $aspectMode;
    }

    public function getTwoPass()
    {
        return $this->twoPass;
    }

    public function setTwoPass($twoPass)
    {
        $this->twoPass = $twoPass;
    }

    public function getVideoBitrate()
    {
        return $this->videoBitrate;
    }

    public function setVideoBitrate($videoBitrate)
    {
        $this->videoBitrate = $videoBitrate;
    }

    public function getFps()
    {
        return $this->fps;
    }

    public function setFps($fps)
    {
        $this->fps = $fps;
    }

    public function getKeyframeInterval()
    {
        return $this->keyframeInterval;
    }

    public function setKeyframeInterval($keyframeInterval)
    {
        $this->keyframeInterval = $keyframeInterval;
    }

    public function getKeyframeRate()
    {
        return $this->keyframeRate;
    }

    public function setKeyframeRate($keyframeRate)
    {
        $this->keyframeRate = $keyframeRate;
    }

    public function getAudioBitrate()
    {
        return $this->audioBitrate;
    }

    public function setAudioBitrate($audioBitrate)
    {
        $this->audioBitrate = $audioBitrate;
    }

    public function getAudioSampleRate()
    {
        return $this->audioSampleRate;
    }

    public function setAudioSampleRate($audioSampleRate)
    {
        $this->audioSampleRate = $audioSampleRate;
    }

    public function getAudioChannels()
    {
        return $this->audioChannels;
    }

    public function setAudioChannels($audioChannels)
    {
        $this->audioChannels = $audioChannels;
    }

    public function getClipLength()
    {
        return $this->clipLength;
    }

    public function setClipLength($clipLength)
    {
        $this->clipLength = $clipLength;
    }

    public function getClipOffset()
    {
        return $this->clipOffset;
    }

    public function setClipOffset($clipOffset)
    {
        $this->clipOffset = $clipOffset;
    }

    public function getFrameCount()
    {
        return $this->frameCount;
    }

    public function setFrameCount($frameCount)
    {
        $this->frameCount = $frameCount;
    }

    public function getCommand()
    {
        return $this->command;
    }

    public function setCommand($command)
    {
        $this->command = $command;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }

    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.3"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Kernel Tuning Toolkit: Source/KernelRunner/KernelRunMode.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Kernel Tuning Toolkit 2.1

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Namespaces |
Enumerations

KernelRunMode.h File Reference

Go to the source code of this file.

Namespaces

namespace  	ktt

Enumerations

enum class  	ktt::KernelRunMode { ktt::Running
, ktt::OfflineTuning
, ktt::OnlineTuning
, ktt::ResultValidation
 }

Detailed Description

Definition of different kernel running scenarios.

Source

KernelRunner

KernelRunMode.h

Generated by  1.9.3


text:
var params = location.hash.slice(1).split("/"),
    email = params[0],
    ids = params[1];

function showError(message) {
  hideSpinner();
  $(".alert").html(message).removeClass("hidden");
}

function showStatus(data) {
  $.each(data.orders, function(_, order) {
    $(".js-status-rows").append(
      [ '
',
          '
',
            '
',
              '',
                order.number,
              '',
              order.progress + " " + order.message,
            '
',
          '
',
          '
',
            order.description,
          '
',
        '
'
      ].join("")
    );
  });

  $(".status").removeClass("hidden");
}

function hideSpinner(){
  $(".spinner").addClass("hidden");
}

if (email && ids) {
  $.get(
    ["", email, ids].join("/")
  ).done(function(data) {
    showStatus(data);
  }).fail(function() {
    showError("There was an error. Are your order numbers correct?");
  }).always(function() {
    hideSpinner();
  });
} else {
  showError("Both an email address and order number are required.");
}


text:
'use strict';
const env = process.env.BUILD_ENV || 'dev';
module.exports = require(`./${env}`);


text:
package alien4cloud.model.deployment.matching;

import alien4cloud.model.orchestrators.locations.LocationResourceTemplate;

import java.util.List;

/**
 * Result of a node matching that defines multiple ordered proposal elements for a matching.
 */
public class NodeMatchingResult {
    /** The node template against which the node has been matched. */
    private List<LocationResourceTemplate> matchedTemplates;
}


text:
/**
 * Simple IMG wrapper
 *
 * @class image
 * @augments elation.ui.base
 * @memberof elation.ui
 *
 * @param {object} args
 * @param {string} args.src
 */
elation.require("ui.base", function() {
  elation.component.add("ui.image", function() {
    this.defaultcontainer = {tag: 'img', classname: 'ui_image'};

    this.init = function() {
      this.addPropertyProxies(['src', 'width', 'height']);
      if (this.args.src) {
        this.src = this.args.src;
      }
      if (this.args.classname) {
        elation.html.addclass(this.container, this.args.classname);
      }

      if (this.args.hidden) {
        this.hide();
      }
    }
  }, elation.ui.base);
});


text:
std::string FileLoader::loadFile(std::string &filename)
{
    std::ifstream file(filename);
    std::string str((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
    return str;
}


text:
use warnings;
# vi: set ts=4 sw=4 :
#____________________________________________________________________________
#
#   MusicBrainz -- the open internet music database
#
#   Copyright (C) 1998 Robert Kaye
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#   $Id$
#____________________________________________________________________________

package DBDefs;
use parent 'DBDefs::Default';
use MusicBrainz::Server::Replication ':replication_type';
use MusicBrainz::Server::DatabaseConnectionFactory;

# Commented-out lines should generally have sane defaults; anything that's uncommented
# probably needs personal attention.

################################################################################
# Directories
################################################################################

# The server root, i.e. the parent directory of admin, bin, lib, root, etc.
# By default, this uses the path of lib/DBDefs/Default.pm, minus '/lib/DBDefs/Default.pm'
# sub MB_SERVER_ROOT    { "/home/httpd/musicbrainz/musicbrainz-server" }
# Where static files are located
# sub STATIC_FILES_DIR { my $self= shift; $self->MB_SERVER_ROOT . '/root/static' }

################################################################################
# The Database
################################################################################

# Configuring databases here is required; there are no defaults.
MusicBrainz::Server::DatabaseConnectionFactory->register_databases(
    # How to connect when we need read-write access to the database
    READWRITE => {
        database    => "musicbrainz_db",
        schema          => "musicbrainz",
        username    => "root",
#        password        => "musicbrainz",
#       host            => "",
#       port            => "",
    },
    # How to connect to a test database
    TEST => {
        database    => "musicbrainz_test",
        schema          => "musicbrainz",
        username    => "root",
#        password        => "musicbrainz",
#       host            => "",
#       port            => "",
    },
    # How to connect for read-only access.  See "REPLICATION_TYPE" (below)
    READONLY => {
        database    => "musicbrainz_db",
        schema          => "musicbrainz",
        username    => "root",
#        password        => "musicbrainz",
#       host            => "",
#       port            => "",
    },
    # How to connect for administrative access
    SYSTEM    => {
        database    => "template1",
        username    => "postgres",
#       password        => "",
#       host            => "",
#       port            => "",
    },
    # Fill out only if RAWDATA lives on a different host from the READWRITE server.
    # RAWDATA_SYSTEM => undef,
);

# The schema sequence number.  Must match the value in
# replication_control.current_schema_sequence.
# This is required, there is no default in order to prevent it changing without
# manual intervention.
sub DB_SCHEMA_SEQUENCE { 19 }

# What type of server is this?
# * RT_MASTER - This is a master replication server.  Changes are allowed, and
#               they result in replication packets being produced.
# * RT_SLAVE  - This is a slave replication server.  After loading a snapshot
#               produced by a master, the only changes allowed are those made
#               by applying the next replication packet in turn.  If the slave
#               server is not going to be used for development work, change
#               DB_STAGING_SERVER to 0.
#
#               A READONLY database connection must be configured if you
#               choose RT_SLAVE, as well as the usual READWRITE.
# * RT_STANDALONE - This server neither generates nor uses replication
#               packets.  Changes to the database are allowed.
sub REPLICATION_TYPE { RT_SLAVE }

################################################################################
# GPG Signature
################################################################################

# Location of the public key file
# sub GPG_PUB_KEY { "" }

# Define how validation deals with the missing signature file:
#   FAIL    - validation fails if signature file is missing
#   PASS    - validation passes if signature file is missing
# sub GPG_MISSING_SIGNATURE_MODE { "PASS" }

# Key identifiers (compatible with --recipient in GPG) for
# signatures and encryption of data dumps and packets. Should
# only be required on the master server.
# sub GPG_SIGN_KEY { "" }
# sub GPG_ENCRYPT_KEY { "" }

################################################################################
# HTTP Server Names
################################################################################

# The host names used by the server.
# To use a port number other than 80, add it like so: "myhost:8000"
# Additionally you should set the environment variable
# MUSICBRAINZ_USE_PROXY=1 when using a reverse proxy to make the server
# aware of it when generating things like the canonical url in catalyst.
sub WEB_SERVER                { "musicbrainz.docker.325i.org" }
# sub LUCENE_SERVER             { "search.musicbrainz.org" }
# sub WEB_SERVER_USED_IN_EMAIL  { my $self = shift; $self->WEB_SERVER }

################################################################################
# Mail Settings
################################################################################

# sub SMTP_SERVER { "localhost" }

# This value should be set to some secret value for your server.  Any old
# string of stuff should do; something suitably long and random, like for
# passwords.  However you MUST change it from the default
# value (the empty string).  This is so an attacker can't just look in CVS and
# see the default secret value, and then use it to attack your server.

# sub SMTP_SECRET_CHECKSUM { "" }
# sub EMAIL_VERIFICATION_TIMEOUT { 604800 } # one week

################################################################################
# Server Settings
################################################################################

# Set this to 0 if this is the master MusicBrainz server or a slave mirror.
# Keeping this defined enables the banner that is shown across the top of each
# page, as well as some testing features that are only enabled when not on
# the live server.
# sub DB_STAGING_SERVER { 1 }

# This description is shown in the banner when DB_STAGING_SERVER is enabled.
# If left undefined the default value will be shown.
# Default: "This is a MusicBrainz development server."
# sub DB_STAGING_SERVER_DESCRIPTION { "" }

# Only change this if running a non-sanitized database on a dev server,
# e.g. http://test.musicbrainz.org.
# sub DB_STAGING_SERVER_SANITIZED { 1 }

# Testing features enable "Accept edit" and "Reject edit" links on edits,
# this should only be enabled on staging servers. Also, this enables non-admin
# users to edit user permissions.
# sub DB_STAGING_TESTING_FEATURES { my $self = shift; $self->DB_STAGING_SERVER }

################################################################################
# Documentation Server Settings
################################################################################
# sub WIKITRANS_SERVER     { "wiki.musicbrainz.org" }

# The path to MediaWiki's api.php file. This is required to automatically
# determine which documentation pages need to be updated in the
# transclusion table.
# sub WIKITRANS_SERVER_API { "wiki.musicbrainz.org/-/api.php" }

# sub WIKITRANS_INDEX_FILE { my $self = shift; $self->MB_SERVER_ROOT . "/root/static/wikidocs/index.txt" }
# sub WIKITRANS_INDEX_URL  { "http://musicbrainz.org/static/wikidocs/index.txt" }

# To enable documentation search on your server, create your own Google Custom
# Search engine and enter its ID as the value of GOOGLE_CUSTOM_SEARCH.
# Alternatively, if you're okay with the search results pointing to
# the musicbrainz.org server, you can use '006539527923176875863:xsv3chs2ovc'.
# sub GOOGLE_CUSTOM_SEARCH { '' }

################################################################################
# Cache Settings
################################################################################

# MEMCACHED_SERVERS allows configuration of global memcached servers, if more
# close configuration is not required
# sub MEMCACHED_SERVERS { return ['127.0.0.1:11211']; };

# MEMCACHED_NAMESPACE allows configuration of a global memcached namespace, if
# more close configuration is not required
# sub MEMCACHED_NAMESPACE { return 'MB:'; };

# PLUGIN_CACHE_OPTIONS are the options configured for Plugin::Cache.  $c->cache
# is provided by Plugin::Cache, and is required for HTTP Digest authentication
# in the webservice (Catalyst::Authentication::Credential::HTTP).
#
# Using Cache::Memory is good for a development environment, but is likely not
# suited for production.  Use something like memcached in a production setup.
#
# If you want to use something such as Memcached, the settings here should be
# the same as the settings you use for the session store.
#
# sub PLUGIN_CACHE_OPTIONS {
#     my $self = shift;
#     return {
#         class => "Cache::Memcached::Fast",
#         servers => $self->MEMCACHED_SERVERS(),
#         namespace => $self->MEMCACHED_NAMESPACE(),
#     };
# };

# Use memcached and a small in-memory cache, see below if you
# want to disable caching
#
# The caching options here relate to object caching - such as caching artists,
# releases, etc in order to speed up queries. If you are using Memcached
# to store sessions as well this should be a *different* memcached server.
# our %CACHE_MANAGER_OPTIONS = (
#     profiles => {
#         memory => {
#             class => 'Cache::Memory',
#             wrapped => 1,
#             keys => [qw( area_type artist_type g c lng label_type mf place_type release_group_type release_group_secondary_type rs rp scr work_type )],
#             options => {
#                 default_expires => '1 hour',
#             },
#         },
#         external => {
#             class => 'Cache::Memcached::Fast',
#             options => {
#                 servers => MEMCACHED_SERVERS(),
#                 namespace => MEMCACHED_NAMESPACE()
#             },
#         },
#     },
#     default_profile => 'external',
# );

# No caching
#our %CACHE_MANAGER_OPTIONS = (
#    profiles => {
#        null => {
#            class => 'Cache::Null',
#            wrapped => 1,
#        },
#    },
#    default_profile => 'null',
#);

# sub CACHE_MANAGER_OPTIONS { \%CACHE_MANAGER_OPTIONS }

################################################################################
# Rate-Limiting
################################################################################

# The "host:port" of the ratelimit server ($MB_SERVER/bin/ratelimit-server).
# If undef, the rate-limit code always returns undef (as it does if there is
# an error).
# Just like the memcached server settings, there is NO SECURITY built into the
# ratelimit protocol, so be careful about enabling it.
# sub RATELIMIT_SERVER { undef }

################################################################################
# Minify settings
################################################################################

# The following two values determine how scripts and styles are minified. By
# default, a dummy minifier is used:
# sub MINIFY_DUMMY { shift; my %args = @_; return $args{input}; }
# sub MINIFY_SCRIPTS { return \&MINIFY_DUMMY; }
# sub MINIFY_STYLES { return \&MINIFY_DUMMY; }

# If you wish to minify either javascript or css, uncomment the following lines
# and install the neccesary CPAN packages.
# sub MINIFY_SCRIPTS { use Javascript::Closure; return \&Javascript::Closure::minify }
# sub MINIFY_STYLES { use CSS::Minifier; return \&CSS::Minifier::minify }

################################################################################
# Other Settings
################################################################################

# Set this value to something true (e.g. 1) to set the server to read-only.
# To date, this option is widely ignored in the code; don't be surprised if you
# set it to true and find that writes are still possible.
# sub DB_READ_ONLY { 0 }

# Set this value to a message that you'd like to display to users when
# they attempt to write to your read-only database (not used if DB_READ_ONLY
# is false)
# sub DB_READ_ONLY_MESSAGE { <<EOF }
# This server is temporarily in read-only mode
# for database maintainance.
# EOF

# Development server feature.
# Used to display which git branch is currently running along with information
# about the last commit
# sub GIT_BRANCH
# {
#   my $self = shift;
#   if ($self->DB_STAGING_SERVER) {
#     my $branch = `git branch --no-color 2> /dev/null | sed -e '/^[^*]/d'`;
#     $branch =~ s/\* (.+)/$1/;
#     my $sha = `git log -1 --format=format:"%h"`;
#     my $msg = `git log -1 --format=format:"Last commit by %an on %ad%n%s" --date=short`;
#     return $branch, $sha, $msg;
#   }
# }

# How long (in seconds) a web/rdf session can go "idle" before being timed out
# sub WEB_SESSION_SECONDS_TO_LIVE { 3600 * 3 }

# The cookie name to use
# sub SESSION_COOKIE { "AF_SID" }
# The domain into which the session cookie is written
# sub SESSION_DOMAIN { undef }

# How long an annotation is considered as being locked.
# sub ANNOTATION_LOCK_TIME { 60*15 }

# Amazon associate and developer ids
# my %amazon_store_associate_ids = (
#     'amazon.ca'         => 'musicbrainz01-20',
#     'amazon.co.jp'    => 'musicbrainz-22',
#     'amazon.co.uk'    => 'musicbrainz0c-21',
#     'amazon.com'    => 'musicbrainz0d-20',
#     'amazon.de'         => 'musicbrainz00-21',
#     'amazon.fr'         => 'musicbrainz0e-21',
#     'amazon.it'         => '', #TODO: Someone should probably sign up for an associate ID.
# );

# sub AWS_ASSOCIATE_ID
# {
#     shift;
#     return keys %amazon_store_associate_ids if not @_;
#     return $amazon_store_associate_ids{$_[0]};
# }

# sub AWS_PRIVATE { '' }
# sub AWS_PUBLIC { '' }

# sub AMAZON_ASSOCIATE_TAG { '' }

# To enable use of reCAPTCHA:
# 1. make sure $ENV{'REMOTE_ADDR'} is the ip address of the visitor.
# 2. replace undef with your recaptcha keys:
# sub RECAPTCHA_PUBLIC_KEY { return undef }
# sub RECAPTCHA_PRIVATE_KEY { return undef }

# internet archive private/public keys (for coverartarchive.org).
# sub COVER_ART_ARCHIVE_ID { };
# sub COVER_ART_ARCHIVE_KEY { };
# sub COVER_ART_ARCHIVE_UPLOAD_PREFIXER { shift; sprintf("http://%s.s3.us.archive.org/", shift) };
# sub COVER_ART_ARCHIVE_DOWNLOAD_PREFIX { "http://coverartarchive.org" };

# Add a Google Analytics tracking code to enable Google Analytics tracking.
# sub GOOGLE_ANALYTICS_CODE { '' }

################################################################################
# Sessions (advanced)
################################################################################

# Unless you are installing an MusicBrainz server that needs to be fully r
# redundant/load balanced, you do not need to change anything in this section.

# If you're using multiple front-end webservers make sure they all connect to
# the same memcached server.  Also make sure enough memory is configured for
# memcached so sessions aren't evicted from the cache.
# sub SESSION_STORE { "Session::Store::MusicBrainz" }
# sub SESSION_STORE_ARGS
# {
#     my $self = shift;
#     return {
#         memcached_new_args => {
#             data => $self->MEMCACHED_SERVERS(),
#             namespace => $self->MEMCACHED_NAMESPACE()
#         }
#     }
# }

# MusicBrainz::Server::Wizard saves wizard sessions in memcached,
# seperately from the regular session store.
# sub WIZARD_MEMCACHED
# {
#     my $self = shift;
#     return { servers => $self->MEMCACHED_SERVERS(), namespace => $self->MEMCACHED_NAMESPACE() };
# }

# sub USE_ETAGS { 1 }

# sub CATALYST_DEBUG { 1 }

# If you are developing on MusicBrainz, you should set this to a true value
# This will turn off some optimizations (such as CSS/JS compression) to make
# developing and debuging easier
# sub DEVELOPMENT_SERVER { 1 }

# Please activate the officially approved languages here. Not every .po
# file is active because we might have fully translated languages which
# are not yet properly supported, like right-to-left languages
# sub MB_LANGUAGES {qw()}

# Should the site fall back to browser settings when trying to set a language
# (note: will still only use languages in MB_LANGUAGES)
# sub LANGUAGE_FALLBACK_TO_BROWSER{ 1 }

# Private, please do not change
# sub _RUNNING_TESTS { 0 }

# Set this to an email address and the server will email any bugs to you
# sub EMAIL_BUGS { undef }

################################################################################
# Profiling
################################################################################
# Set these to >0 to enable profiling

# Log if a request in /ws takes more than x seconds
# sub PROFILE_WEB_SERVICE { 0 }

# Log if a request in / (not /ws) takes more than x seconds
# sub PROFILE_SITE { 0 }

# If you want the FastCGI processes to restart, configure this
# sub AUTO_RESTART {
##    return {
##        active => 1,
##        check_each => 10,
##        max_bits => 134217728,
##        min_handled_requests => 100
##    }
# }

# The maximum amount of time a process can be serving a single request
# If undef, the process is never killed
# If set to a positive integer, the process can server a single request
# for MAX_REQUEST_TIME seconds, and if it is still not done the process
# will be killed (and log a message about the request it was serving).
# sub MAX_REQUEST_TIME { undef }

# sub LOGGER_ARGUMENTS {
#     return (
#         outputs => [
#             [ 'Screen', min_level => 'debug', newline => 1 ],
#         ],
#     )
# }

1;
# eof DBDefs.pm


text:
#include "postgres.h"

#include "access/hash.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "access/relation.h"
#include "catalog/partition.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_partitioned_table.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "partitioning/partbounds.h"
#include "rewrite/rewriteHandler.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/partcache.h"
#include "utils/rel.h"
#include "utils/syscache.h"

static List *generate_partition_qual(Relation rel);

/*
 * RelationBuildPartitionKey
 *		Build partition key data of relation, and attach to relcache
 *
 * Partitioning key data is a complex structure; to avoid complicated logic to
 * free individual elements whenever the relcache entry is flushed, we give it
 * its own memory context, a child of CacheMemoryContext, which can easily be
 * deleted on its own.  To avoid leaking memory in that context in case of an
 * error partway through this function, the context is initially created as a
 * child of CurTransactionContext and only re-parented to CacheMemoryContext
 * at the end, when no further errors are possible.  Also, we don't make this
 * context the current context except in very brief code sections, out of fear
 * that some of our callees allocate memory on their own which would be leaked
 * permanently.
 */
void
RelationBuildPartitionKey(Relation relation)
{
	Form_pg_partitioned_table form;
	HeapTuple	tuple;
	bool		isnull;
	int			i;
	PartitionKey key;
	AttrNumber *attrs;
	oidvector  *opclass;
	oidvector  *collation;
	ListCell   *partexprs_item;
	Datum		datum;
	MemoryContext partkeycxt,
				oldcxt;
	int16		procnum;

	tuple = SearchSysCache1(PARTRELID,
							ObjectIdGetDatum(RelationGetRelid(relation)));

	/*
	 * The following happens when we have created our pg_class entry but not
	 * the pg_partitioned_table entry yet.
	 */
	if (!HeapTupleIsValid(tuple))
		return;

	partkeycxt = AllocSetContextCreate(CurTransactionContext,
									   "partition key",
									   ALLOCSET_SMALL_SIZES);
	MemoryContextCopyAndSetIdentifier(partkeycxt,
									  RelationGetRelationName(relation));

	key = (PartitionKey) MemoryContextAllocZero(partkeycxt,
												sizeof(PartitionKeyData));

	/* Fixed-length attributes */
	form = (Form_pg_partitioned_table) GETSTRUCT(tuple);
	key->strategy = form->partstrat;
	key->partnatts = form->partnatts;

	/*
	 * We can rely on the first variable-length attribute being mapped to the
	 * relevant field of the catalog's C struct, because all previous
	 * attributes are non-nullable and fixed-length.
	 */
	attrs = form->partattrs.values;

	/* But use the hard way to retrieve further variable-length attributes */
	/* Operator class */
	datum = SysCacheGetAttr(PARTRELID, tuple,
							Anum_pg_partitioned_table_partclass, &isnull);
	Assert(!isnull);
	opclass = (oidvector *) DatumGetPointer(datum);

	/* Collation */
	datum = SysCacheGetAttr(PARTRELID, tuple,
							Anum_pg_partitioned_table_partcollation, &isnull);
	Assert(!isnull);
	collation = (oidvector *) DatumGetPointer(datum);

	/* Expressions */
	datum = SysCacheGetAttr(PARTRELID, tuple,
							Anum_pg_partitioned_table_partexprs, &isnull);
	if (!isnull)
	{
		char	   *exprString;
		Node	   *expr;

		exprString = TextDatumGetCString(datum);
		expr = stringToNode(exprString);
		pfree(exprString);

		/*
		 * Run the expressions through const-simplification since the planner
		 * will be comparing them to similarly-processed qual clause operands,
		 * and may fail to detect valid matches without this step; fix
		 * opfuncids while at it.  We don't need to bother with
		 * canonicalize_qual() though, because partition expressions should be
		 * in canonical form already (ie, no need for OR-merging or constant
		 * elimination).
		 */
		expr = eval_const_expressions(NULL, expr);
		fix_opfuncids(expr);

		oldcxt = MemoryContextSwitchTo(partkeycxt);
		key->partexprs = (List *) copyObject(expr);
		MemoryContextSwitchTo(oldcxt);
	}

	/* Allocate assorted arrays in the partkeycxt, which we'll fill below */
	oldcxt = MemoryContextSwitchTo(partkeycxt);
	key->partattrs = (AttrNumber *) palloc0(key->partnatts * sizeof(AttrNumber));
	key->partopfamily = (Oid *) palloc0(key->partnatts * sizeof(Oid));
	key->partopcintype = (Oid *) palloc0(key->partnatts * sizeof(Oid));
	key->partsupfunc = (FmgrInfo *) palloc0(key->partnatts * sizeof(FmgrInfo));

	key->partcollation = (Oid *) palloc0(key->partnatts * sizeof(Oid));
	key->parttypid = (Oid *) palloc0(key->partnatts * sizeof(Oid));
	key->parttypmod = (int32 *) palloc0(key->partnatts * sizeof(int32));
	key->parttyplen = (int16 *) palloc0(key->partnatts * sizeof(int16));
	key->parttypbyval = (bool *) palloc0(key->partnatts * sizeof(bool));
	key->parttypalign = (char *) palloc0(key->partnatts * sizeof(char));
	key->parttypcoll = (Oid *) palloc0(key->partnatts * sizeof(Oid));
	MemoryContextSwitchTo(oldcxt);

	/* determine support function number to search for */
	procnum = (key->strategy == PARTITION_STRATEGY_HASH) ?
		HASHEXTENDED_PROC : BTORDER_PROC;

	/* Copy partattrs and fill other per-attribute info */
	memcpy(key->partattrs, attrs, key->partnatts * sizeof(int16));
	partexprs_item = list_head(key->partexprs);
	for (i = 0; i < key->partnatts; i++)
	{
		AttrNumber	attno = key->partattrs[i];
		HeapTuple	opclasstup;
		Form_pg_opclass opclassform;
		Oid			funcid;

		/* Collect opfamily information */
		opclasstup = SearchSysCache1(CLAOID,
									 ObjectIdGetDatum(opclass->values[i]));
		if (!HeapTupleIsValid(opclasstup))
			elog(ERROR, "cache lookup failed for opclass %u", opclass->values[i]);

		opclassform = (Form_pg_opclass) GETSTRUCT(opclasstup);
		key->partopfamily[i] = opclassform->opcfamily;
		key->partopcintype[i] = opclassform->opcintype;

		/* Get a support function for the specified opfamily and datatypes */
		funcid = get_opfamily_proc(opclassform->opcfamily,
								   opclassform->opcintype,
								   opclassform->opcintype,
								   procnum);
		if (!OidIsValid(funcid))
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
					 errmsg("operator class \"%s\" of access method %s is missing support function %d for type %s",
							NameStr(opclassform->opcname),
							(key->strategy == PARTITION_STRATEGY_HASH) ?
							"hash" : "btree",
							procnum,
							format_type_be(opclassform->opcintype))));

		fmgr_info_cxt(funcid, &key->partsupfunc[i], partkeycxt);

		/* Collation */
		key->partcollation[i] = collation->values[i];

		/* Collect type information */
		if (attno != 0)
		{
			Form_pg_attribute att = TupleDescAttr(relation->rd_att, attno - 1);

			key->parttypid[i] = att->atttypid;
			key->parttypmod[i] = att->atttypmod;
			key->parttypcoll[i] = att->attcollation;
		}
		else
		{
			if (partexprs_item == NULL)
				elog(ERROR, "wrong number of partition key expressions");

			key->parttypid[i] = exprType(lfirst(partexprs_item));
			key->parttypmod[i] = exprTypmod(lfirst(partexprs_item));
			key->parttypcoll[i] = exprCollation(lfirst(partexprs_item));

			partexprs_item = lnext(partexprs_item);
		}
		get_typlenbyvalalign(key->parttypid[i],
							 &key->parttyplen[i],
							 &key->parttypbyval[i],
							 &key->parttypalign[i]);

		ReleaseSysCache(opclasstup);
	}

	ReleaseSysCache(tuple);

	/* Assert that we're not leaking any old data during assignments below */
	Assert(relation->rd_partkeycxt == NULL);
	Assert(relation->rd_partkey == NULL);

	/*
	 * Success --- reparent our context and make the relcache point to the
	 * newly constructed key
	 */
	MemoryContextSetParent(partkeycxt, CacheMemoryContext);
	relation->rd_partkeycxt = partkeycxt;
	relation->rd_partkey = key;
}

/*
 * RelationGetPartitionQual
 *
 * Returns a list of partition quals
 */
List *
RelationGetPartitionQual(Relation rel)
{
	/* Quick exit */
	if (!rel->rd_rel->relispartition)
		return NIL;

	return generate_partition_qual(rel);
}

/*
 * get_partition_qual_relid
 *
 * Returns an expression tree describing the passed-in relation's partition
 * constraint.
 *
 * If the relation is not found, or is not a partition, or there is no
 * partition constraint, return NULL.  We must guard against the first two
 * cases because this supports a SQL function that could be passed any OID.
 * The last case can happen even if relispartition is true, when a default
 * partition is the only partition.
 */
Expr *
get_partition_qual_relid(Oid relid)
{
	Expr	   *result = NULL;

	/* Do the work only if this relation exists and is a partition. */
	if (get_rel_relispartition(relid))
	{
		Relation	rel = relation_open(relid, AccessShareLock);
		List	   *and_args;

		and_args = generate_partition_qual(rel);

		/* Convert implicit-AND list format to boolean expression */
		if (and_args == NIL)
			result = NULL;
		else if (list_length(and_args) > 1)
			result = makeBoolExpr(AND_EXPR, and_args, -1);
		else
			result = linitial(and_args);

		/* Keep the lock, to allow safe deparsing against the rel by caller. */
		relation_close(rel, NoLock);
	}

	return result;
}

/*
 * generate_partition_qual
 *
 * Generate partition predicate from rel's partition bound expression. The
 * function returns a NIL list if there is no predicate.
 *
 * We cache a copy of the result in the relcache entry, after constructing
 * it using the caller's context.  This approach avoids leaking any data
 * into long-lived cache contexts, especially if we fail partway through.
 */
static List *
generate_partition_qual(Relation rel)
{
	HeapTuple	tuple;
	MemoryContext oldcxt;
	Datum		boundDatum;
	bool		isnull;
	List	   *my_qual = NIL,
			   *result = NIL;
	Relation	parent;
	bool		found_whole_row;

	/* Guard against stack overflow due to overly deep partition tree */
	check_stack_depth();

	/* If we already cached the result, just return a copy */
	if (rel->rd_partcheckvalid)
		return copyObject(rel->rd_partcheck);

	/* Grab at least an AccessShareLock on the parent table */
	parent = relation_open(get_partition_parent(RelationGetRelid(rel)),
						   AccessShareLock);

	/* Get pg_class.relpartbound */
	tuple = SearchSysCache1(RELOID, RelationGetRelid(rel));
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "cache lookup failed for relation %u",
			 RelationGetRelid(rel));

	boundDatum = SysCacheGetAttr(RELOID, tuple,
								 Anum_pg_class_relpartbound,
								 &isnull);
	if (!isnull)
	{
		PartitionBoundSpec *bound;

		bound = castNode(PartitionBoundSpec,
						 stringToNode(TextDatumGetCString(boundDatum)));

		my_qual = get_qual_from_partbound(rel, parent, bound);
	}

	ReleaseSysCache(tuple);

	/* Add the parent's quals to the list (if any) */
	if (parent->rd_rel->relispartition)
		result = list_concat(generate_partition_qual(parent), my_qual);
	else
		result = my_qual;

	/*
	 * Change Vars to have partition's attnos instead of the parent's. We do
	 * this after we concatenate the parent's quals, because we want every Var
	 * in it to bear this relation's attnos. It's safe to assume varno = 1
	 * here.
	 */
	result = map_partition_varattnos(result, 1, rel, parent,
									 &found_whole_row);
	/* There can never be a whole-row reference here */
	if (found_whole_row)
		elog(ERROR, "unexpected whole-row reference found in partition key");

	/* Assert that we're not leaking any old data during assignments below */
	Assert(rel->rd_partcheckcxt == NULL);
	Assert(rel->rd_partcheck == NIL);

	/*
	 * Save a copy in the relcache.  The order of these operations is fairly
	 * critical to avoid memory leaks and ensure that we don't leave a corrupt
	 * relcache entry if we fail partway through copyObject.
	 *
	 * If, as is definitely possible, the partcheck list is NIL, then we do
	 * not need to make a context to hold it.
	 */
	if (result != NIL)
	{
		rel->rd_partcheckcxt = AllocSetContextCreate(CacheMemoryContext,
													 "partition constraint",
													 ALLOCSET_SMALL_SIZES);
		MemoryContextCopyAndSetIdentifier(rel->rd_partcheckcxt,
										  RelationGetRelationName(rel));
		oldcxt = MemoryContextSwitchTo(rel->rd_partcheckcxt);
		rel->rd_partcheck = copyObject(result);
		MemoryContextSwitchTo(oldcxt);
	}
	else
		rel->rd_partcheck = NIL;
	rel->rd_partcheckvalid = true;

	/* Keep the parent locked until commit */
	relation_close(parent, NoLock);

	/* Return the working copy to the caller */
	return result;
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * A function that compares 2 dates. The comparison also includes the time portion.
 *
 * @param candidate - The candidate date.
 * @param expected - The expected date.
 * @returns - A Boolean value indicating whether the values are equal.
 *
 * @example
 * ```ts-no-run
 * isEqual(new Date(2016, 0, 1), new Date(2016, 0, 1)); // true
 * isEqual(new Date(2016, 0, 1), new Date(2016, 0, 2)); // false
 * isEqual(new Date(2016, 0, 1, 10), new Date(2016, 0, 1, 20)); // false
 * ```
 */
exports.isEqual = function (candidate, expected) {
    if (!candidate && !expected) {
        return true;
    }
    return candidate && expected && candidate.getTime() === expected.getTime();
};


text:
package org.apache.ignite.internal.metric;

import java.util.Arrays;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cluster.ClusterState;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.metric.GridMetricManager;
import org.apache.ignite.internal.processors.metric.MetricRegistry;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import static org.apache.ignite.internal.processors.metric.impl.MetricUtils.cacheMetricsRegistryName;
import static org.apache.ignite.internal.processors.metric.impl.MetricUtils.metricName;

/** */
@RunWith(Parameterized.class)
public class CacheMetricsAddRemoveTest extends GridCommonAbstractTest {
    /** */
    public static final String CACHE_GETS = "CacheGets";

    /** */
    public static final String CACHE_PUTS = "CachePuts";

    /** Cache modes. */
    @Parameterized.Parameters(name = "cacheMode={0},nearEnabled={1}")
    public static Iterable<Object[]> params() {
        return Arrays.asList(
            new Object[] {CacheMode.PARTITIONED, false},
            new Object[] {CacheMode.PARTITIONED, true},
            new Object[] {CacheMode.REPLICATED, false},
            new Object[] {CacheMode.REPLICATED, true}
        );
    }

    /** . */
    @Parameterized.Parameter(0)
    public CacheMode mode;

    /** Use index. */
    @Parameterized.Parameter(1)
    public boolean nearEnabled;

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        return super.getConfiguration(igniteInstanceName)
            .setDataStorageConfiguration(new DataStorageConfiguration()
                .setDataRegionConfigurations(
                    new DataRegionConfiguration().setName("persisted").setPersistenceEnabled(true)));
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        cleanPersistenceDir();

        startGridsMultiThreaded(2);

        startClientGrid(getConfiguration("client"));
    }

    /** */
    @Test
    public void testCacheMetricsAddRemove() throws Exception {
        String cachePrefix = cacheMetricsRegistryName(DEFAULT_CACHE_NAME, false);

        checkMetricsEmpty(cachePrefix);

        createCache();

        checkMetricsNotEmpty(cachePrefix);

        destroyCache();

        checkMetricsEmpty(cachePrefix);
    }

    /** */
    @Test
    public void testCacheMetricsNotRemovedOnStop() throws Exception {
        String cachePrefix = cacheMetricsRegistryName("other-cache", false);

        checkMetricsEmpty(cachePrefix);

        createCache("persisted", "other-cache");

        grid("client").cache("other-cache").put(1L, 1L);

        checkMetricsNotEmpty(cachePrefix);

        //Cache will be stopped during deactivation.
        grid("client").cluster().state(ClusterState.INACTIVE);

        checkMetricsNotEmpty(cachePrefix);

        grid("client").cluster().state(ClusterState.ACTIVE);

        assertEquals(1L, grid("client").cache("other-cache").get(1L));

        checkMetricsNotEmpty(cachePrefix);

        destroyCache();

        checkMetricsEmpty(cachePrefix);
    }

    /** */
    private void destroyCache() throws InterruptedException {
        IgniteEx client = grid("client");

        for (String name : client.cacheNames())
            client.destroyCache(name);

        awaitPartitionMapExchange();
    }

    /** */
    private void createCache() throws InterruptedException {
        createCache(null, null);
    }

    /** */
    private void createCache(@Nullable String dataRegionName, @Nullable String cacheName) throws InterruptedException {
        CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

        if (dataRegionName != null)
            ccfg.setDataRegionName(dataRegionName);

        if (cacheName != null)
            ccfg.setName(cacheName);

        if (nearEnabled)
            ccfg.setNearConfiguration(new NearCacheConfiguration());

        grid("client").createCache(ccfg);

        awaitPartitionMapExchange();
    }

    /** */
    private void checkMetricsNotEmpty(String cachePrefix) {
        for (int i = 0; i < 2; i++) {
            GridMetricManager mmgr = metricManager(i);

            MetricRegistry mreg = mmgr.registry(cachePrefix);

            assertNotNull(mreg.findMetric(CACHE_GETS));
            assertNotNull(mreg.findMetric(CACHE_PUTS));

            if (nearEnabled) {
                mreg = mmgr.registry(metricName(cachePrefix, "near"));

                assertNotNull(mreg.findMetric(CACHE_GETS));
                assertNotNull(mreg.findMetric(CACHE_PUTS));
            }
        }
    }

    /** */
    private void checkMetricsEmpty(String cachePrefix) {
        for (int i = 0; i < 3; i++) {
            GridMetricManager mmgr = metricManager(i);

            MetricRegistry mreg = mmgr.registry(cachePrefix);

            assertNull(mreg.findMetric(metricName(cachePrefix, CACHE_GETS)));
            assertNull(mreg.findMetric(metricName(cachePrefix, CACHE_PUTS)));

            if (nearEnabled) {
                mreg = mmgr.registry(metricName(cachePrefix, "near"));

                assertNull(mreg.findMetric(CACHE_GETS));
                assertNull(mreg.findMetric(CACHE_PUTS));
            }
        }
    }

    /** */
    private GridMetricManager metricManager(int gridIdx) {
        if (gridIdx < 2)
            return grid(0).context().metric();
        else
            return grid("client").context().metric();
    }
}


text:
#include "src/core/ext/transport/chttp2/transport/incoming_metadata.h"

#include <string.h>

#include "src/core/ext/transport/chttp2/transport/internal.h"

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

void grpc_chttp2_incoming_metadata_buffer_init(
    grpc_chttp2_incoming_metadata_buffer *buffer) {
  buffer->deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
}

void grpc_chttp2_incoming_metadata_buffer_destroy(
    grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer) {
  size_t i;
  if (!buffer->published) {
    for (i = 0; i < buffer->count; i++) {
      GRPC_MDELEM_UNREF(exec_ctx, buffer->elems[i].md);
    }
  }
  gpr_free(buffer->elems);
}

void grpc_chttp2_incoming_metadata_buffer_add(
    grpc_chttp2_incoming_metadata_buffer *buffer, grpc_mdelem elem) {
  GPR_ASSERT(!buffer->published);
  if (buffer->capacity == buffer->count) {
    buffer->capacity = GPR_MAX(8, 2 * buffer->capacity);
    buffer->elems =
        gpr_realloc(buffer->elems, sizeof(*buffer->elems) * buffer->capacity);
  }
  buffer->elems[buffer->count++].md = elem;
  buffer->size += GRPC_MDELEM_LENGTH(elem);
}

void grpc_chttp2_incoming_metadata_buffer_replace_or_add(
    grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer,
    grpc_mdelem elem) {
  for (size_t i = 0; i < buffer->count; i++) {
    if (grpc_slice_eq(GRPC_MDKEY(buffer->elems[i].md), GRPC_MDKEY(elem))) {
      GRPC_MDELEM_UNREF(exec_ctx, buffer->elems[i].md);
      buffer->elems[i].md = elem;
      return;
    }
  }
  grpc_chttp2_incoming_metadata_buffer_add(buffer, elem);
}

void grpc_chttp2_incoming_metadata_buffer_set_deadline(
    grpc_chttp2_incoming_metadata_buffer *buffer, gpr_timespec deadline) {
  GPR_ASSERT(!buffer->published);
  buffer->deadline = deadline;
}

void grpc_chttp2_incoming_metadata_buffer_publish(
    grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer,
    grpc_metadata_batch *batch) {
  GPR_ASSERT(!buffer->published);
  buffer->published = 1;
  if (buffer->count > 0) {
    size_t i;
    for (i = 0; i < buffer->count; i++) {
      /* TODO(ctiller): do something better here */
      if (!GRPC_LOG_IF_ERROR("grpc_chttp2_incoming_metadata_buffer_publish",
                             grpc_metadata_batch_link_tail(
                                 exec_ctx, batch, &buffer->elems[i]))) {
        GRPC_MDELEM_UNREF(exec_ctx, buffer->elems[i].md);
      }
    }
  } else {
    batch->list.head = batch->list.tail = NULL;
  }
  batch->deadline = buffer->deadline;
}


text:
typedef void (*show_commit_fn)(struct commit *, void *);
typedef void (*show_object_fn)(struct object *, const struct name_path *, const char *, void *);
void traverse_commit_list(struct rev_info *, show_commit_fn, show_object_fn, void *);

typedef void (*show_edge_fn)(struct commit *);
void mark_edges_uninteresting(struct rev_info *, show_edge_fn);

#endif


text:
Neither the [before](#before) and [after](#after) decorators can actually terminate evaluation without throwing something. Normal execution always results in the base method being evaluated. The `provided` and `excepting` recipes are combinators that produce method decorators that apply a precondition to evaluating the base method body. If the precondition fails, nothing is returned.

The provided combinator turns a function into a method decorator. The function must evaluate to truthy for the base method to be evaluated:

    function provided (predicate) {
      return function(base) {
        return function() {
          if (predicate.apply(this, arguments)) {
            return base.apply(this, arguments);
          }
        };
      };
    };

`provided` can be used to create named decorators like `maybe`:

    var maybe = provided( function (value) {
      return value != null
    });

    SomeModel.prototype.setAttribute = maybe( function (value) {
      this.attribute = value
    });

You can build your own domain-specific decorators:

    var whenNamed = provided( function (record) {
      return record.name && record.name.length > 0
    })

`except` works identically, but with the logic reversed.

    function except (predicate) {
      return function(base) {
        return function() {
          if (!predicate.apply(this, arguments)) {
            return base.apply(this, arguments);
          }
        };
      };
    };

    var exceptAdmin = except( function (user) {
      return user.role.isAdmin()
    });


text:
#include "common.h"
#include "mud/creature.h"
#include "mud/command.h"

/* BEGIN COMMAND
 *
 * name: stop
 *
 * format: stop
 *
 * END COMMAND */

void command_stop(Creature* ch, std::string argv[])
{
	ch->cancelAction();
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.resources.models;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

/** Defines values for ResourcePropertyChangeType. */
public enum ResourcePropertyChangeType {
    /** Enum value Update. */
    UPDATE("Update"),

    /** Enum value Insert. */
    INSERT("Insert"),

    /** Enum value Remove. */
    REMOVE("Remove");

    /** The actual serialized value for a ResourcePropertyChangeType instance. */
    private final String value;

    ResourcePropertyChangeType(String value) {
        this.value = value;
    }

    /**
     * Parses a serialized value to a ResourcePropertyChangeType instance.
     *
     * @param value the serialized value to parse.
     * @return the parsed ResourcePropertyChangeType object, or null if unable to parse.
     */
    @JsonCreator
    public static ResourcePropertyChangeType fromString(String value) {
        ResourcePropertyChangeType[] items = ResourcePropertyChangeType.values();
        for (ResourcePropertyChangeType item : items) {
            if (item.toString().equalsIgnoreCase(value)) {
                return item;
            }
        }
        return null;
    }

    @JsonValue
    @Override
    public String toString() {
        return this.value;
    }
}


text:
require('chai').should();
var expect = require('chai').expect;

// jango
var Jango = require('../dist');

describe('Jango', function () {

  var a = Jango('test'),
      b = Jango({one: 1, two: 2}),
      c = Jango([1, 2, 3]),
      d = Jango({one: {two: 'three'}, a: ['b', 'c']});

  describe('constructor', function () {

    it('should return an instance of jango', function () {
      a.should.be.an.instanceof(Jango);
    });

    it('should set the value correctly', function () {
      a.val().should.equal('test');
    });

    it('should create instances of jango in an object', function () {
      b.get('one').should.be.an.instanceof(Jango);
    });

    it('should create instances of jango in an array', function () {
      c.get(0).should.be.an.instanceof(Jango);
    });

    it('should set the values correctly in an object', function () {
      b.val('one').should.equal(1);
    });

    it('should set the values correctly in an array', function () {
      c.val(0).should.equal(1);
    });

    it('should recursively create nested instances of jango', function () {
      d.get(['one', 'two']).should.be.an.instanceof(Jango);
      d.get(['a', 0]).should.be.an.instanceof(Jango);
    });

    it('should recursively set the values correctly ', function () {
      d.val(['one', 'two']).should.equal('three');
      d.val(['a', 0]).should.equal('b');
    });
  });

  describe('.val', function () {

    it('should return the value', function () {
      a.val().should.equal('test');
    });

    it('should return nested values', function () {
      b.val().should.eql({one: 1, two: 2});
      c.val().should.eql([1, 2, 3]);
    });

    it('should traverse up a tree to return nested values if key is passed', function () {
      b.val('one').should.equal(1);
      c.val(0).should.equal(1);
      d.val(['one', 'two']).should.equal('three');
    });

    it('should return undefined if no value is found', function () {
      expect(a.val('one')).not.to.exist;
    });

    it('should not recursively return values if `shallow` options is passed', function () {
      var b3 = b.val({shallow: true});

      b.get('one').should.equal(b3['one']);
      b.get('two').should.equal(b3['two']);

      var c3 = c.val({shallow: true});

      c.get(0).should.equal(c3[0]);
      c.get(1).should.equal(c3[1]);
      c.get(2).should.equal(c3[2]);
    });
  });

  describe('.get', function () {

    it('should return itself if not passed a key', function () {
      a.get().should.equal(a);
    });

    it('should return an instance of jango if passed a key in the value', function () {
      b.get('one').should.be.an.instanceof(Jango);
      b.val('one').should.equal(1);
    });

    it('should return an instance of jango if passed a nonexistent key', function () {
      expect(b.get('nope')).not.to.exist;
    });

    it('should return a nested instance of jango if passed an array', function () {
      d.get(['one', 'two']).should.be.an.instanceof(Jango);
      d.val(['one', 'two']).should.equal('three');
    });
  });

  describe('.set', function () {

    it('shouldn\'t mutate when setting', function () {
      a.set('blah');
      a.val().should.equal('test');
    });

    it('should convert objects and arrays to instances of jango', function () {
      a.set({one: 1}).get('one').should.be.an.instanceof(Jango);
      a.set([1]).get(0).should.be.an.instanceof(Jango);
    });

    it('should set nested value if passed an array', function () {
      d.set(['one', 'two'], 'three').val(['one', 'two']).should.equal('three');
    });

    it('should return the same instance if setting the same value', function () {
      a.set('test').should.equal(a);
    });

    it('should return the same instance if returning a jango with the same value', function () {
      a.set(Jango('test')).should.equal(a);
    });

    it('should return a new instance if setting a new value', function () {
      a.set('blah').val().should.equal('blah');
      a.set('blah').val().should.not.equal(a);
    });

    it('should return a new instance if setting a jango with a new value', function () {
      a.set(Jango('blah')).val().should.equal('blah');
      a.set(Jango('blah')).val().should.not.equal(a);
    });

    it('should return the same instance if setting same partial value', function () {
      b.set('one', 1).should.equal(b);
      c.set(0, 1).should.equal(c);
      d.set(['one', 'two'], 'three').should.equal(d);
      d.set('one', {two: 'three'}).should.equal(d);
      d.set(['a', 0], 'b').should.equal(d);
    });

    it('should return a new instance if setting a different partial value', function () {
      b.set('one', 2).should.not.equal(b);
      c.set(0, 2).should.not.equal(c);
      d.set(['one', 'two'], 'four').should.not.equal(d);
      d.set('one', {two: 'four'}).should.not.equal(d);
      d.set(['a', 0], 'c').should.not.equal(d);
    });

    it('should return same instances of unchanged keys', function () {
      b.set('one', 2).get('two').should.equal(b.get('two'));
      c.set(0, 2).get(1).should.equal(c.get(1));
    });

    it('should return new instances of changed keys', function () {
      b.set('one', 2).get('one').should.not.equal(b.get('one'));
      c.set(0, 2).get(0).should.not.equal(c.get(0));
    });

    it('should return a new instance if adding a new key', function () {
      b.set('three', 3).val('three').should.equal(3);
      b.set('three', 3).should.not.equal(b);
      c.set(3, 4).val(3).should.equal(4);
      c.set(3, 4).should.not.equal(c);
    });

    it('should overwrite the old value if no key is specified', function () {
      b.set('blah').val().should.equal('blah');
    });
  });

  describe('.merge', function () {

    it('should return the same instance if setting the same value', function () {
      b.merge({one: 1, two: 2}).should.equal(b);
      c.merge([1, 2, 3]).should.equal(c);
      d.merge({one: {two: 'three'}}).should.equal(d);
      d.merge({a: ['b', 'c']}).should.equal(d);
    });

    it('should return the same instance if setting the same partial value', function () {
      b.merge({one: 1}).should.equal(b);
      c.merge([1]).should.equal(c);
    });

    it('should return a new instance if setting a new partial value', function () {
      b.merge({one: 2}).should.not.equal(b);
      b.merge({one: 2}).val('one').should.equal(2);

      c.merge([2]).should.not.equal(c);
      c.merge([2]).val(0).should.equal(2);

      d.merge({one: {two: 'four'}}).should.not.equal(d);
      d.merge({one: {two: 'four'}}).val(['one', 'two']).should.equal('four');
      d.merge({a: ['b', 'd']}).should.not.equal(d);
      d.merge({a: ['b', 'd']}).val(['a', 1]).should.equal('d');
    });

    it('should return the same instance of unchanged keys', function () {
      b.merge({one: 2}).get('two').should.equal(b.get('two'));
      c.merge([2]).get(1).should.equal(c.get(1));
    });

    it('should return a new instance of changed keys', function () {
      b.merge({one: 2}).get('one').should.not.equal(b.get('one'));
      c.merge([2]).get(0).should.not.equal(c.get(0));
    });

    it('should return a new instance if adding a new key', function () {
      b.merge({three: 3}).val('three').should.equal(3);
      b.merge({three: 3}).should.not.equal(b);
      c.merge([1, 2, 3, 4]).val(3).should.equal(4);
      c.merge([1, 2, 3, 4]).should.not.equal(c);
    });

    it('should merge deeply nested jangos', function () {
      var e = Jango({one: Jango({two: Jango({three: Jango('four')}) }) });
      e.merge(e).should.equal(e);
    });
  });

  describe('.filter', function () {

    var f = Jango({obj: {one: 1, two: 2}, arr: [1, 2]});

    it('should pass each child, key and itself to the predicate', function () {

      f.get('obj').filter(function (child, key, self) {
        child.should.equal(f.get(['obj', key]));
        self.should.equal(f.get('obj'));
      });

      f.get('arr').filter(function (child, key, self) {
        child.should.equal(f.get(['arr', key]));
        self.should.equal(f.get('arr'));
      });
    });

    it('should return the same instance if all predicates return true', function () {

      var g = f.get('obj').filter(function (child) { return true; });
      g.should.equal(f.get('obj'));
      g.val('one').should.equal(1);
      g.val('two').should.equal(2);

      var g = f.get('arr').filter(function (child) { return true; });
      g.should.equal(f.get('arr'));
      g.val(0).should.equal(1);
      g.val(1).should.equal(2);
    });

    it('should return a new instance if any value is different', function () {

      var g = f.get('obj').filter(function (child) { return child.val() !== 1; });
      g.should.not.equal(f.get('obj'));
      g.val('two').should.equal(2);
      Object.keys(g.val()).length.should.equal(1);

      g = f.get('arr').filter(function (child) { return child.val() !== 1; });
      g.should.not.equal(f.get('arr'));
      g.val(0).should.equal(2);
      Object.keys(g.val()).length.should.equal(1);
    });
  });

  describe('.map', function () {

    var m = Jango({obj: {one: 1, two: 2}, arr: [1, 2]});

    it('should pass each child, key and itself to the predicate', function () {

      m.get('obj').map(function (child, key, self) {
        child.should.equal(m.get(['obj', key]));
        self.should.equal(m.get('obj'));
      });

      m.get('arr').map(function (child, key, self) {
        child.should.equal(m.get(['arr', key]));
        self.should.equal(m.get('arr'));
      });
    });

    it('should return the same instance if all values are the same', function () {

      var n = m.get('obj').map(function (child) { return child.val(); });
      n.should.equal(m.get('obj'));
      n.get('one').val().should.equal(1);
      n.get('two').val().should.equal(2);

      var n = m.get('obj').map(function (child) { return child });
      n.should.equal(m.get('obj'));
      n.get('one').val().should.equal(1);
      n.get('two').val().should.equal(2);

      var n = m.get('arr').map(function (child) { return child.val(); });
      n.should.equal(m.get('arr'));
      n.get(0).val().should.equal(1);
      n.get(1).val().should.equal(2);

      var n = m.get('arr').map(function (child) { return child });
      n.should.equal(m.get('arr'));
      n.get(0).val().should.equal(1);
      n.get(1).val().should.equal(2);
    });

    it('should return a new instance if any value is different', function () {

      var n = m.get('obj').map(function (child) { return child.val() * 2; });
      n.should.not.equal(m.get('obj'));
      n.get('one').val().should.equal(2);
      n.get('two').val().should.equal(4);

      n = m.get('arr').map(function (child) { return child.val() * 2; });
      n.should.not.equal(m.get('arr'));
      n.get(0).val().should.equal(2);
      n.get(1).val().should.equal(4);
    });
  });
});


text:
using System;
using System.IO;
using System.Security.Cryptography;

using CodeJam.Collections;

using JetBrains.Annotations;

namespace CodeJam.PerfTests.Running.Helpers
{
	///
	/// PDB helpers
	///
	public static class PdbHelpers
	{
		private const string Sha1AlgName = "SHA1";
		private const string Md5AlgName = "Md5";

		[NotNull]
		private static string GetChecksumName(PdbChecksumAlgorithm checksumAlgorithm)
		{
			switch (checksumAlgorithm)
			{
				case PdbChecksumAlgorithm.Md5:
					return Md5AlgName;
				case PdbChecksumAlgorithm.Sha1:
					return Sha1AlgName;
				default:
					throw CodeExceptions.UnexpectedArgumentValue(nameof(checksumAlgorithm), checksumAlgorithm);
			}
		}

		/// Gets checksum for file if it exists.
		/// <param name="file">The file.</param>
		/// <param name="checksumAlgorithm">The checksum algorithm to use.</param>
		/// <returns>Checksum for file or empty byte array if the file does not exist.</returns>
		[NotNull]
		public static byte[] TryGetChecksum([NotNull] string file, PdbChecksumAlgorithm checksumAlgorithm)
		{
			Code.NotNullNorEmpty(file, nameof(file));

			var algName = GetChecksumName(checksumAlgorithm);
			if (!File.Exists(file))
				return Array<byte>.Empty;

			using (var stream = File.OpenRead(file))
			using (var hashAlgorithm = HashAlgorithm.Create(algName))
			{
				// ReSharper disable once PossibleNullReferenceException
				return hashAlgorithm.ComputeHash(stream);
			}
		}

		/// Gets checksum for resource if it exists.
		/// <param name="resourceKey">The resource key.</param>
		/// <param name="checksumAlgorithm">The checksum algorithm to use.</param>
		/// <returns>Checksum for resource or empty byte array if the resource does not exist.</returns>
		[NotNull]
		public static byte[] TryGetChecksum(ResourceKey resourceKey, PdbChecksumAlgorithm checksumAlgorithm)
		{
			Code.AssertArgument(!resourceKey.IsEmpty, nameof(resourceKey), "The resource key should be non empty.");

			var algName = GetChecksumName(checksumAlgorithm);
			using (var stream = resourceKey.TryGetResourceStream())
			{
				if (stream == null)
					return Array<byte>.Empty;

				using (var hashAlgorithm = HashAlgorithm.Create(algName))
				{
					// ReSharper disable once PossibleNullReferenceException
					return hashAlgorithm.ComputeHash(stream);
				}
			}
		}
	}
}


text:
Weatherwax
==========

A WebSharper/Angular framework that uses sitelets to serve Angular templates to a single page app (SPA),
with F# used exclusively to generate both client and server code.


text:
<?php

namespace Antares\Foundation\Http\Controllers\TestCase;

use Mockery as m;
use Antares\Testing\TestCase;
use Illuminate\Container\Container;
use Illuminate\Support\Facades\Facade;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Antares\Foundation\Http\Controllers\BaseController;

class BaseControllerTest extends TestCase
{

    use WithoutMiddleware;

    /**
     * Setup the test environment.
     */
    public function setUp()
    {
        parent::setUp();

        $this->disableMiddlewareForAllTests();

        $_SERVER['StubBaseController@setupFilters'] = false;
    }

    /**
     * Teardown the test environment.
     */
    public function tearDown()
    {
        parent::tearDown();

        unset($_SERVER['StubBaseController@setupFilters']);
    }

    /**
     * Test Antares\Foundation\Http\Controllers\BaseController::missingMethod()
     * action.
     *
     * @test
     */
    public function testMissingMethodAction()
    {
        $app        = new Container();
        $factory    = m::mock('\Illuminate\Contracts\View\Factory');
        $view       = m::mock('\Illuminate\Contracts\View\View');
        $redirector = m::mock('\Illuminate\Routing\Redirector');
        $response   = m::mock('\Illuminate\Routing\ResponseFactory', [$factory, $redirector]);

        $app['Illuminate\Contracts\Routing\ResponseFactory'] = $response;

        Facade::clearResolvedInstances();
        Facade::setFacadeApplication($app);
        Container::setInstance($app);

        $response->shouldReceive('view')->once()
                ->with('antares/foundation::dashboard.missing', [], 404)->andReturn($view);

        $this->assertFalse($_SERVER['StubBaseController@setupFilters']);

        $stub = new StubBaseController();

        $this->assertEquals($view, $stub->missingMethod([]));
        $this->assertTrue($_SERVER['StubBaseController@setupFilters']);
    }

}

class StubBaseController extends BaseController
{

    /**
     * Setup controller filters.
     */
    protected function setupFilters()
    {
        $_SERVER['StubBaseController@setupFilters'] = true;
    }

    public function setupMiddleware()
    {
        ;
    }

}


text:
import * as actions from './actions'
import { getIn } from './utils/immutability'

const actionValues = Object.values(actions)

const fragmentMiddleware = (store) => (next) => (action) => {
  const prevState = store.getState()
  const nextAction = next(action)
  let nextState = store.getState()

  if (actionValues.includes(action.type)) {
    return nextAction
  }

  if (prevState.pages === nextState.pages) {
    return nextAction
  }

  let changedFragments = {}
  let changedKeys = Object.keys(nextState.pages).filter((key) => {
    return prevState.pages[key] !== nextState.pages[key]
  })

  if (changedKeys.length === 0) {
    return nextAction
  }

  changedKeys.forEach((key) => {
    nextState.pages[key].fragments.forEach((fragment) => {
      const { type, path } = fragment
      const nextPage = nextState.pages[key]
      const prevPage = prevState.pages[key]
      let nextFragment, prevFragment

      try {
        prevFragment = getIn(prevPage, path)
        nextFragment = getIn(nextPage, path)
      } catch (err) {
        if (err.name == 'KeyPathError') {
          console.warn(err.message)
        } else {
          throw err
        }
      }

      if (
        nextFragment !== undefined &&
        prevFragment !== undefined &&
        nextFragment !== prevFragment &&
        nextFragment
      ) {
        changedFragments[type] = nextFragment
      }
    })
  })

  if (Object.keys(changedFragments).length === 0) {
    return nextAction
  }

  store.dispatch({
    type: actions.UPDATE_FRAGMENTS,
    payload: {
      changedFragments,
    },
  })

  return nextAction
}

export { fragmentMiddleware }


text:
Maki is a point of interest icon set made especially for use with MapBox maps. For more information on how to use Maki with MapBox, see documentation at http://mapbox.com/tilemill/docs/guides/using-maki-icons/.

I recommend using [Inkscape](http://inkscape.org/) for editing and exporting from the .SVG to take advantage of Inkscape's batch export, as all the icons have unique ID's that Inkscape uses to create file names.

Maki follows these design principles:

- Simple, clear, recognizable
- Three sizes: 12/18/24 px
- Single color, with 1px 30% transparent white outline.
- Based upon internationally recognized symbols when appropriate. Good sources for symbol precedents include [AIGA symbols](http://www.aiga.org/symbol-signs/), and the [Noun Project](http://thenounproject.com/).

To view the backlog of icons that need to be created, visit https://github.com/mapbox/maki/wiki/Maki-Backlog

## Completed icons

### Basic shapes

- solid circle
- stroked circle
- solid square
- stroked square
- solid triangle
- stroked triangle
- solid star
- stroked star
- solid 'x'
- stroked 'x'
- solid marker
- stroked marker

### Social
- amenity='college'
- amenity='library'
- amenity='school'
- amenity='hospital'
- amenity='pharmacy'
- amenity='grave_yard'
- amenity='place_of_worship' religion='christian'
- amenity='place_of_worship' religion='jewish'
- amenity='place_of_worship' religion='muslim'

### Public
- amenity='fire_station'
- amenity='prison'
- amenity='post_office'
- amenity='police'
- amenity='townhall'
- amenity='embassy'

### Transportation
- amenity='bicycle_rental'
- parking lot (international)
- parking garage
- aeroway='helipad'
- aeroway='aerodrome'
- amenity='fuel'

### Commercial
- amenity='bar'
- amenity='restaurant'
- amenity='fast_food'
- amenity='cafe'
- shop
- grocery store
- movie theatre
- amenity='bank' (international)
- amenity='cinema'

### Recreation
- tourism='museum'
- tourism='hotel'
- tourism='zoo'
- leisure='park'
- campsite
- garden
- leisure='pitch' (a general sports icon)
    - sport='american_football'
    - sport='soccer'
    - sport='tennis'
    - sport='baseball'
    - sport='swimming'
    - sport='skiing'
    - sport='golf'
    - sport='cricket'
    - sport='basketball'
- historic='monument'


text:
package oxdoc.util;

import java.io.IOException;

import static oxdoc.util.Utils.checkNotNull;

public class LogFileLogger implements Logger {
  private LogFile logFile;

  public LogFileLogger(LogFile logFile) {
    this.logFile = checkNotNull(logFile);
  }

  @Override
  public void info(String message) {
    try {
      System.out.println(message);
      logFile.writeln(message);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public void warning(String message) {
    try {
      System.out.println("Warning: " + message);
      logFile.writeln("Warning: " + message);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}


text:
<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/polymer/lib/mixins/gesture-event-listeners.html">

<link rel="import" href="../../bower_components/paper-toast/paper-toast.html">

<link rel="import" href="../mixins/redux-mixin.html">
<link rel="import" href="../elements/shared-styles.html">

<dom-module id="toast-element">
  <template>
    <style is="custom-style" include="shared-styles flex flex-alignment"></style>

    <style>
      :host {
        display: block;
      }

      paper-toast {
        user-select: none;
      }

      paper-toast[fit-bottom] {
        width: 100%;
        min-width: 0;
        border-radius: 0;
        margin: 0;
      }

      .toast-action {
        margin-left: 24px;
        color: var(--accent-color);
        text-transform: uppercase;
        font-weight: 600;
        cursor: pointer;
        white-space: nowrap;
        user-select: none;
      }
    </style>

    <paper-toast
      id="toast"
      duration="[[toast.duration]]"
      text="[[toast.message]]"
      opened="[[toast.visible]]"
      on-tap="_handleTap"
      fit-bottom$="[[viewport.isPhone]]"
      layout horizontal justified center
    >

      <span
        class="toast-action"
        hidden$="[[!toast.action]]"
        on-tap="_handleAction"
      >
        [[toast.action.title]]
      </span>

    </paper-toast>

  </template>

  <script>

    class ToastElement extends ReduxMixin(Polymer.GestureEventListeners(Polymer.Element)) {
      static get is() {
        return 'toast-element';
      }

      static get properties() {
        return {
          toast: {
            type: Object,
            statePath: 'toast',
          },
          viewport: {
            type: Object,
            statePath: 'ui.viewport',
          },
        };
      }

      _handleTap() {
        this.toast.action && this.toast.action.callback();
        toastActions.hideToast();
      }

      _handleAction() {
        if (this.toast.action) {
          this.toast.action.callback();
          toastActions.hideToast();
        }
      }
    }

    window.customElements.define(ToastElement.is, ToastElement);

  </script>
</dom-module>


text:
namespace Neo4j.Driver.Internal
{
    internal interface IInternalStatementResultCursor : IStatementResultCursor
    {
        void Discard();
    }
}


text:
TEST_JDK_HOME?=$(JAVA_HOME)
PLUGIN_NAME?=mailer
# Relative path to the WAR file to be used for tests
WAR_PATH?=tmp/jenkins-war-$(JENKINS_VERSION).war
# Extra options to pass to PCT, works only in the local steps
EXTRA_OPTS?=
# Maven executable for local runs. Can be automatically discovered on Linux, but requires manual specification when running on Windows
MVN_EXECUTABLE?=$(shell which mvn)

JENKINS_VERSION=2.164.3

.PHONY: all
all: clean package docker

.PHONY: allNoDocker
allNoDocker: clean package

.PHONY: clean
clean:
	mvn clean

plugins-compat-tester-cli/target/plugins-compat-tester-cli.jar:
	mvn package
.PHONY: package
package: plugins-compat-tester-cli/target/plugins-compat-tester-cli.jar

.PHONY: docker
docker: Dockerfile
	docker build -t jenkins/pct .

tmp:
	mkdir tmp

.PRECIOUS: tmp/jenkins-war-$(JENKINS_VERSION).war
tmp/jenkins-war-$(JENKINS_VERSION).war: tmp
	mvn dependency:copy -Dartifact=org.jenkins-ci.main:jenkins-war:$(JENKINS_VERSION):war -DoutputDirectory=tmp
	touch tmp/jenkins-war-$(JENKINS_VERSION).war

.PHONY: print-java-home
print-java-home:
	echo "Using JAVA_HOME for tests $(TEST_JDK_HOME)"

.PHONY: demo-jdk8
demo-jdk8: plugins-compat-tester-cli/target/plugins-compat-tester-cli.jar $(WAR_PATH) print-java-home
	java -jar plugins-compat-tester-cli/target/plugins-compat-tester-cli.jar \
	     -reportFile $(CURDIR)/out/pct-report.xml \
	     -failOnError \
	     -workDirectory $(CURDIR)/work \
	     -skipTestCache true \
	     -mvn $(MVN_EXECUTABLE) \
	     -war $(CURDIR)/$(WAR_PATH) \
	     -testJDKHome "$(TEST_JDK_HOME)" \
	     -includePlugins $(PLUGIN_NAME) \
	     $(EXTRA_OPTS)

.PHONY: demo-jdk11
demo-jdk11: plugins-compat-tester-cli/target/plugins-compat-tester-cli.jar $(WAR_PATH) print-java-home
	java -jar plugins-compat-tester-cli/target/plugins-compat-tester-cli.jar \
	     -reportFile $(CURDIR)/out/pct-report.xml \
	     -failOnError \
	     -workDirectory $(CURDIR)/work \
	     -skipTestCache true \
	     -mvn $(MVN_EXECUTABLE) \
	     -war $(CURDIR)/$(WAR_PATH) \
	     -testJDKHome "$(TEST_JDK_HOME)" \
	     -includePlugins $(PLUGIN_NAME) \
         $(EXTRA_OPTS)

# We do not automatically rebuild Docker here
.PHONY: demo-jdk11-docker
demo-jdk11-docker: tmp/jenkins-war-$(JENKINS_VERSION).war
	docker run --rm -v maven-repo:/root/.m2 \
	     -v $(CURDIR)/out:/pct/out \
	     -v $(CURDIR)/$(WAR_PATH):/pct/jenkins.war:ro \
	     -e ARTIFACT_ID=$(PLUGIN_NAME) \
	     -e JDK_VERSION=11 \
	     jenkins/pct

.PHONY: demo-jdk11-docker-src
demo-jdk11-docker-src: $(WAR_PATH)
	docker run --rm -v maven-repo:/root/.m2 \
	     -v $(CURDIR)/out:/pct/out \
	     -v $(CURDIR)/work/$(PLUGIN_NAME):/pct/plugin-src:ro \
	     -v $(CURDIR)/$(WAR_PATH):/pct/jenkins.war:ro \
	     -e ARTIFACT_ID=$(PLUGIN_NAME) \
	     -e JDK_VERSION=11 \
	     jenkins/pct


text:
<?php

namespace Accreditamenti\CongressiBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class QuestionarioValutazioneType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('descrizione')
            ->add('data_inizio_compilazione')
            ->add('data_fine_compilazione')
            ->add('accreditamento')
        ;
    }

    public function getName()
    {
        return 'accreditamenti_congressibundle_questionario_valutazione_type';
    }
}


text:
Logging
=======

There are several different processes related to profile installation and MDM command acknowledgement.
The easiest option is to download this :download:`Logging Profile </_static/profiles/MDM Debug Logging.mobileconfig>`
for macOS 10.12 and higher.

MDM Debugging
-------------

Commands::

    sudo touch /var/db/MDM_EnableDebug

In macOS 10.12 you can configure the logging subsystem via a configuration profile (as above) or by using the :command:`log`
utility like so::

    sudo log config --subsystem com.apple.ManagedClient --mode="level:debug,persist:debug"

You will probably want to reset this back to normal so that debug logs are not persisted like so::

    sudo log config --subsystem com.apple.ManagedClient --reset

MCX
---

.. note:: Some parts of ManagedClient don't use Unified Logging so you'll probably need to enable this also.

Log Location
    /Library/Logs/ManagedClient/ManagedClient.log

Commands::

    sudo defaults write /Library/Preferences/com.apple.MCXDebug debugOutput -2
    sudo defaults write /Library/Preferences/com.apple.MCXDebug collateLogs 1

Unified Logging Predicates
--------------------------

Various predicates can be directly entered into the *Console.app* and saved.

.. note:: Sometimes if you search by process name, you get a lot of noise. Example: searching for **mdmclient** forces
    you to wade through a ton of push service notifications.

Some useful predicates:

- ``subsystem:com.apple.ManagedClient`` Messages in this category cover a broad range of profile installation messages.
- ``subsystem:com.apple.securityd`` Interactions with the keychain
- ``category:SCEP.fw`` SCEP network requests only (no warnings on signature verification etc).

Payload specific combinations:

- ``subsystem:com.apple.ManagedClient library:Certificate`` Certificate payload messages


text:
layout: games
title: Games
order: 1
permalink: /games/
---

Games we created so far. Each game is free (as in beer) and [open-source](https://github.com/w84death). We never put any advertising nor IAP in our games.

We made them because is't our hobby not a job. If you like what we made and want to support us check [donation page](/donate).


text:
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';

import { Member } from './team.models';

@Component({
  selector: 'app-member',
  templateUrl: './member.component.html',
  styleUrls: ['./member.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MemberComponent {
  @Input() member: Member;
}


text:
chrome.runtime.sendMessage('Hello', function(response){
  document.write(response);
});


text:
'use strict'

//------------------------------------------------------------------------------
// Rule Translation Definition
//------------------------------------------------------------------------------

module.exports = {
  name: 'indent',
  truthy: function(__current__, value) {
    return [2, value, {'SwitchCase': 1}]
  }
};