text:
#include "ParameterBlockType.h"
#include "ParameterBlock.h"

#define base CTypeElement

CParameterBlockType::CParameterBlockType(const std::string& strName) : base(strName)
{
}

std::string CParameterBlockType::getKind() const
{
    return "ParameterBlock";
}

bool CParameterBlockType::childrenAreDynamic() const
{
    return true;
}

CInstanceConfigurableElement* CParameterBlockType::doInstantiate() const
{
    return new CParameterBlock(getName(), this);
}

void CParameterBlockType::populate(CElement* pElement) const
{
    uint32_t uiArrayLength = getArrayLength();

    if (uiArrayLength) {

        // Create child elements
        size_t uiChild;

        for (uiChild = 0; uiChild < uiArrayLength; uiChild++) {

            CParameterBlock* pChildParameterBlock = new CParameterBlock(toString(uiChild), this);

            pElement->addChild(pChildParameterBlock);

            base::populate(pChildParameterBlock);
        }
    } else {
        // Regular block
        base::populate(pElement);
    }
}


text:
module Cul
  module Fedora
    class Server
      attr_reader :riurl, :riquery

      def initialize(*args)
        options = args.extract_options!
        @riurl = options[:riurl] || raise(ArgumentError, "Must provide riurl argument")
        @riquery = options[:riquery] || raise(ArgumentError, "Must provide riquery argument")
        @hc = options[:http_client]
      end

      def item(uri)
        Item.new(:server => self, :uri => uri)
      end

      def request(options= {})
        http_client.get_content(*request_path(options))
      end

      def request_path(options = {})
        sdef = options.delete(:sdef).to_s
        pid = options.delete(:pid).to_s
        request = options.delete(:request).to_s
        method = (options.delete(:method) || "/get").to_s
        raise(ArgumentError, "request necessary") if request.empty?

        sdef = "/" + sdef unless sdef.empty?
        pid = "/" + pid unless pid.empty?
        request = "/" + request.to_s

        uri = @riurl + method + pid + sdef + request
        query = options

        return [uri, query]
      end

      def inspect
        '#<Cul::Fedora::Server:' + self.object_id.to_s + ' @riurl="' + @riurl + '">'
      end

      private

      def http_client
        @hc ||= HTTPClient.new()
        @hc
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package server

import (
	"fmt"
	"net/http"
	"path/filepath"
	"strconv"

	"github.com/dimfeld/httptreemux"
	"github.com/kabukky/journey/database"
	"github.com/kabukky/journey/filenames"
	"github.com/kabukky/journey/structure/methods"
	"github.com/kabukky/journey/templates"
)

func indexHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
	number := params["number"]
	if number == "" {
		// Render index template (first page)
		err := templates.ShowIndexTemplate(w, r, 1)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		return
	}
	page, err := strconv.Atoi(number)
	if err != nil || page <= 1 {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	// Render index template
	err = templates.ShowIndexTemplate(w, r, page)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	return
}

func authorHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
	slug := params["slug"]
	function := params["function"]
	number := params["number"]
	if function == "" {
		// Render author template (first page)
		err := templates.ShowAuthorTemplate(w, r, slug, 1)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		return
	} else if function == "rss" {
		// Render author rss feed
		err := templates.ShowAuthorRss(w, slug)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		return
	}
	page, err := strconv.Atoi(number)
	if err != nil || page <= 1 {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	// Render author template
	err = templates.ShowAuthorTemplate(w, r, slug, page)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	return
}

func tagHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
	slug := params["slug"]
	function := params["function"]
	number := params["number"]
	if function == "" {
		// Render tag template (first page)
		err := templates.ShowTagTemplate(w, r, slug, 1)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		return
	} else if function == "rss" {
		// Render tag rss feed
		err := templates.ShowTagRss(w, slug)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		return
	}
	page, err := strconv.Atoi(number)
	if err != nil || page <= 1 {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	// Render tag template
	err = templates.ShowTagTemplate(w, r, slug, page)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	return
}

func postHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
	slug := params["slug"]
	if slug == "" {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	} else if slug == "rss" {
		// Render index rss feed
		err := templates.ShowIndexRss(w)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		return
	}

	// Render post template
	err := templates.ShowPostTemplate(w, r, slug)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	return
}

func postEditHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
	slug := params["slug"]

	if slug == "" {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	// Redirect to edit
	post, err := database.RetrievePostBySlug(slug)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	url := fmt.Sprintf("/admin/#/edit/%d", post.Id)
	http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

func assetsHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
	// Read lock global blog
	methods.Blog.RLock()
	defer methods.Blog.RUnlock()
	http.ServeFile(w, r, filepath.Join(filenames.ThemesFilepath, methods.Blog.ActiveTheme, "assets", params["filepath"]))
	return
}

func imagesHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
	http.ServeFile(w, r, filepath.Join(filenames.ImagesFilepath, params["filepath"]))
	return
}

func publicHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {
	http.ServeFile(w, r, filepath.Join(filenames.PublicFilepath, params["filepath"]))
	return
}

func InitializeBlog(router *httptreemux.TreeMux) {
	// For index
	router.GET("/", indexHandler)
	router.GET("/:slug/edit", postEditHandler)
	router.GET("/:slug/", postHandler)
	router.GET("/page/:number/", indexHandler)
	// For author
	router.GET("/author/:slug/", authorHandler)
	router.GET("/author/:slug/:function/", authorHandler)
	router.GET("/author/:slug/:function/:number/", authorHandler)
	// For tag
	router.GET("/tag/:slug/", tagHandler)
	router.GET("/tag/:slug/:function/", tagHandler)
	router.GET("/tag/:slug/:function/:number/", tagHandler)
	// For serving asset files
	router.GET("/assets/*filepath", assetsHandler)
	router.GET("/images/*filepath", imagesHandler)
	router.GET("/content/images/*filepath", imagesHandler) // This is here to keep compatibility with Ghost
	router.GET("/public/*filepath", publicHandler)
}


text:
- [TB3_WAFFLE_SLAM.bag](https://github.com/ROBOTIS-GIT/bags)
- Commands for download:
```bash
roscd turtlebot3_slam/bag
wget https://github.com/ROBOTIS-GIT/bags/blob/master/TB3_WAFFLE_SLAM.bag
```


text: module.exports = require("npm:escape-html@1.0.2/index");


text:
namespace switches {

// All switches in alphabetical order. The switches should be documented
// alongside the definition of their values in the .cc file.
GAMEPAD_FEATURES_EXPORT extern const char kEnableGamepadButtonAxisEvents[];
GAMEPAD_FEATURES_EXPORT extern const char kGamepadPollingInterval[];
GAMEPAD_FEATURES_EXPORT extern const char kRestrictGamepadAccess[];

}  // namespace switches

#endif  // DEVICE_GAMEPAD_PUBLIC_CPP_GAMEPAD_SWITCHES_H_


text:
export template <class T>
class vnl_svd
{
 public:
  //: The singular values of a matrix of complex<T> are of type T, not complex<T>
  typedef typename vnl_numeric_traits<T>::abs_t singval_t;

  //:
  // Construct a vnl_svd<T> object from $m \times n$ matrix $M$.  The
  // vnl_svd<T> object contains matrices $U$, $W$, $V$ such that
  // $U W V^\top = M$.
  //
  // Uses linpack routine DSVDC to calculate an ``economy-size'' SVD
  // where the returned $U$ is the same size as $M$, while $W$
  // and $V$ are both $n \times n$.  This is efficient for
  // large rectangular solves where $m > n$, typical in least squares.
  //
  // The optional argument zero_out_tol is used to mark the zero singular
  // values: If nonnegative, any s.v. smaller than zero_out_tol in
  // absolute value is set to zero.  If zero_out_tol is negative, the
  // zeroing is relative to |zero_out_tol| * sigma_max();

  vnl_svd(vnl_matrix<T> const &M, double zero_out_tol = 0.0);
 ~vnl_svd() {}

  // Data Access---------------------------------------------------------------

  //: find weights below threshold tol, zero them out, and update W_ and Winverse_
  void            zero_out_absolute(double tol = 1e-8); //sqrt(machine epsilon)

  //: find weights below tol*max(w) and zero them out
  void            zero_out_relative(double tol = 1e-8); //sqrt(machine epsilon)
  int             singularities () const { return W_.rows() - rank(); }
  unsigned int    rank () const { return rank_; }
  singval_t       well_condition () const { return sigma_min()/sigma_max(); }

  //: Calculate determinant as product of diagonals in W.
  singval_t       determinant_magnitude () const;
  singval_t       norm() const;

  //: Return the matrix U.
  vnl_matrix<T>      & U()       { return U_; }

  //: Return the matrix U.
  vnl_matrix<T> const& U() const { return U_; }

  //: Return the matrix U's (i,j)th entry (to avoid svd.U()(i,j); ).
  T U(int i, int j) const { return U_(i,j); }

  //: Get at DiagMatrix (q.v.) of singular values, sorted from largest to smallest
  vnl_diag_matrix<singval_t>       & W()             { return W_; }

  //: Get at DiagMatrix (q.v.) of singular values, sorted from largest to smallest
  vnl_diag_matrix<singval_t> const & W() const       { return W_; }
  vnl_diag_matrix<singval_t>       & Winverse()      { return Winverse_; }
  vnl_diag_matrix<singval_t> const & Winverse() const { return Winverse_; }
  singval_t                   & W(int i, int j) { return W_(i,j); }
  singval_t                   & W(int i)        { return W_(i,i); }
  singval_t     sigma_max() const { return W_(0,0); }       // largest
  singval_t     sigma_min() const { return W_(n_-1,n_-1); } // smallest

  //: Return the matrix V.
  vnl_matrix<T>      & V()       { return V_; }

  //: Return the matrix V.
  vnl_matrix<T> const& V() const { return V_; }

  //: Return the matrix V's (i,j)th entry (to avoid svd.V()(i,j); ).
  T V(int i, int j) const { return V_(i,j); }

  //:
  inline vnl_matrix<T> inverse () const { return pinverse(); }

  //: pseudo-inverse (for non-square matrix) of desired rank.
  vnl_matrix<T> pinverse (unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1

  //: Calculate inverse of transpose, using desired rank.
  vnl_matrix<T> tinverse (unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1

  //: Recompose SVD to U*W*V', using desired rank.
  vnl_matrix<T> recompose (unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1

  //: Solve the matrix equation M X = B, returning X
  vnl_matrix<T> solve (vnl_matrix<T> const& B) const;

  //: Solve the matrix-vector system M x = y, returning x.
  vnl_vector<T> solve (vnl_vector<T> const& y) const;
  void          solve (T const *rhs, T *lhs) const; // min ||A*lhs - rhs||

  //: Solve the matrix-vector system M x = y.
  // Assuming that the singular values W have been preinverted by the caller.
  void solve_preinverted(vnl_vector<T> const& rhs, vnl_vector<T>* out) const;

  //: Return N such that M * N = 0
  vnl_matrix<T> nullspace() const;

  //: Return N such that M' * N = 0
  vnl_matrix<T> left_nullspace() const;

  //: Return N such that M * N = 0
  vnl_matrix<T> nullspace(int required_nullspace_dimension) const;

  //: Implementation to be done yet; currently returns left_nullspace(). - PVR.
  vnl_matrix<T> left_nullspace(int required_nullspace_dimension) const;

  //: Return the rightmost column of V.
  //  Does not check to see whether or not the matrix actually was rank-deficient -
  // the caller is assumed to have examined W and decided that to his or her satisfaction.
  vnl_vector<T> nullvector() const;

  //: Return the rightmost column of U.
  //  Does not check to see whether or not the matrix actually was rank-deficient.
  vnl_vector<T> left_nullvector() const;

  bool valid() const { return valid_; }

 private:

  int m_, n_;              // Size of M, local cache.
  vnl_matrix<T> U_;        // Columns Ui are basis for range of M for Wi != 0
  vnl_diag_matrix<singval_t> W_;// Singular values, sorted in decreasing order
  vnl_diag_matrix<singval_t> Winverse_;
  vnl_matrix<T> V_;       // Columns Vi are basis for nullspace of M for Wi = 0
  unsigned rank_;
  bool have_max_;
  singval_t max_;
  bool have_min_;
  singval_t min_;
  double last_tol_;
  bool valid_;        // false if the NETLIB call failed.

  // Disallow assignment.
  vnl_svd(vnl_svd<T> const &) { }
  vnl_svd<T>& operator=(vnl_svd<T> const &) { return *this; }
};

template <class T>
inline
vnl_matrix<T> vnl_svd_inverse(vnl_matrix<T> const& m)
{
  return vnl_svd<T>(m).inverse();
}

export template <class T>
vcl_ostream& operator<<(vcl_ostream&, vnl_svd<T> const& svd);

#endif // vnl_svd_h_


text:
"""
    A graphical user interface (PySide) on top of the FireWorks workflow engine.

    @author: Johan Hidding
    @organisation: Netherlands eScience Center (NLeSC)
    @contact: j.hidding@esciencecenter.nl
"""

import sys, os
from PySide import QtGui, QtCore
from PySide.QtCore import Qt

from .nodebox import NodeBox
#from .sourceview import SourceView

class NodeView(QtGui.QGraphicsView):
    def __init__(self, scene):
        super(NodeView, self).__init__(scene)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.show()

class NodeScene(QtGui.QGraphicsScene):
    def __init__(self, data_model):
        super(NodeScene, self).__init__()
        self.nodes = [NodeBox(n, self) for i, n in data_model.all_nodes()]

    def noodletPressed(self, i, s):
        pass
        #print("{0}-{1} pressed".format(i, s))

    def noodletReleased(self, i, s):
        pass
        #print("{0}-{1} released".format(i, s))

class NoodlesWindow(QtGui.QMainWindow):
    def __init__(self, data_model):
        super(NoodlesWindow, self).__init__()

        self.data_model = data_model
        self.initUI()

    def initUI(self):
        style = str(open("static/qt-style.css", "r").read())
        self.nodeScene = NodeScene(self.data_model)
        self.nodeView = NodeView(self.nodeScene)

        self.nodeView.setStyleSheet(style)

        #self.sourceView = SourceView()

        self.tabWidget = QtGui.QTabWidget()
        self.tabWidget.addTab(self.nodeView, "Graph view")
        #self.tabWidget.addTab(self.sourceView, "Source view")
        self.setCentralWidget(self.tabWidget)

        self.setGeometry(300, 300, 1024, 600)
        self.setWindowTitle('Noodles')
        self.setWindowIcon(QtGui.QIcon('static/noodles-icon.png'))

        self.statusBar().showMessage('Ready')

        exitAction = QtGui.QAction(QtGui.QIcon.fromTheme('application-exit'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAction)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        self.nodeRepository = QtGui.QToolBox()
        self.flowNodeList = QtGui.QListWidget()
        self.compositeNodeList = QtGui.QListWidget()
        self.libraryNodeList = QtGui.QListWidget()
        self.nodeRepository.addItem(self.flowNodeList, "flow control")
        self.nodeRepository.addItem(self.libraryNodeList, "library nodes")
        self.nodeRepository.addItem(self.compositeNodeList, "composite nodes")
        dockWidget = QtGui.QDockWidget("Noodles node repository")
        dockWidget.setWidget(self.nodeRepository)
        self.addDockWidget(Qt.RightDockWidgetArea, dockWidget)

        self.show()

    def closeEvent(self, event):
        pass
#        reply = QtGui.QMessageBox.question(self, 'Message',
#            "Are you sure to quit?", QtGui.QMessageBox.Yes |
#            QtGui.QMessageBox.No, QtGui.QMessageBox.No)

#        if reply == QtGui.QMessageBox.Yes:
#            event.accept()
#        else:
#            event.ignore()

        #self.sourceView.backend.stop()

def main(model):
    app = QtGui.QApplication(sys.argv)

#    Qode.backend.CodeCompletionWorker.providers.append(
#        backend.DocumentWordsProvider())
#    Qode.backend.serve_forever()

    win = NoodlesWindow(model)
    sys.exit(app.exec_())


text:
'use strict';

const Command = require('../../Command.js');
const EnableUsageEmbed = require('../../embeds/EnableUsageEmbed.js');
const EnableInfoEmbed = require('../../embeds/EnableInfoEmbed.js');

class Disable extends Command {
  constructor(bot) {
    super(bot, 'settings.disable', 'disable', 'Disable a command.');
    this.usages = [
      { description: 'Disable a command for a role in a channel or channels', parameters: ['command id> in <channel> for <role|user'] },
    ];
    this.regex = new RegExp(`^${this.call}(?:\\s+(\\w*\\.*\\w*\\.*\\w*\\*?)(?:\\s+in\\s+((?:\\<\\#)?\\d+(?:\\>)?|here|\\*)(?:\\s+for\\s((?:\\<\\@\\&?)?\\d+(?:\\>)?|\\*))?)?)?`,
      'i');
    this.blacklistable = false;
    this.requiresAuth = true;
  }

  run(message) {
    const params = message.strippedContent.match(this.regex);
    if (!params[1]) {
      this.messageManager.embed(message, new EnableUsageEmbed(this.bot, null, 0), true, false);
    } else {
      params.splice(0, 1);
      const commands = this.getCommandsToEnable(params[0]);
      let channels = [];

      if (params[1]) {
        channels = this.getChannels(message.mentions.channels.length > 0
          ? message.mentions.channels : params[1], message);
      } else {
        channels = [message.channel];
      }

      let target = {};
      if (params[2] ||
        message.mentions.roles.array().length > 0 || message.mentions.users.array().length > 0) {
        target = this.getTarget(params[2], message.mentions ? message.mentions.roles : [],
          message.mentions ? message.mentions.users : [], message);
      } else {
        target = message.guild.roles.find('name', '@everyone');
      }
      const infoEmbed = new EnableInfoEmbed(this.bot, 0, [commands, channels, target.toString()]);
      const promises = [];
      this.bot.settings.getChannelResponseToSettings(message.channel)
        .then((respondToSettings) => {
          if (respondToSettings) {
            this.messageManager.embed(message, infoEmbed, true, false);
          }
        });
      commands.forEach((command) => {
        channels.forEach((channel) => {
          if (target.type === 'Role') {
            promises.push(this.bot.settings
              .setChannelPermissionForRole(channel, target, command, 0));
          } else {
            promises.push(this.bot.settings
              .setChannelPermissionForMember(channel, target, command, 0));
          }
        });
      });
      promises.forEach((promise) => {
        promise.catch(this.logger.error);
      });
    }
  }

  /**
   * Get the list of commands based on input
   * @param {string} commandIdParam parameter for determining commands
   * @returns {Array<string>} command ids to enable
   */
  getCommandsToEnable(commandIdParam) {
    const commandsToEnable = [];
    const commandRegex = new RegExp(commandIdParam.replace('.', '\\.').replace('*', '.*'), 'ig');
    this.bot.commandHandler.commands.forEach((command) => {
      if (commandRegex.test(command.id) && command.blacklistable) {
        commandsToEnable.push(command.id);
      }
    });
    return commandsToEnable;
  }

  /**
   * Get the list of channels to enable commands in based on the parameters
   * @param {string|Array<Channel>} channelsParam parameter for determining channels
   * @param {Message} message Discord message to get information on channels
   * @returns {Array<string>} channel ids to enable commands in
   */
  getChannels(channelsParam, message) {
    let channels = [];
    if (typeof channelsParam === 'string') {
      // handle it for strings
      if (channelsParam !== '*' && channelsParam !== 'here') {
        channels.push(this.bot.client.channels.get(channelsParam.trim()));
      } else if (channelsParam === '*') {
        channels = channels.concat(message.guild.channels.array().filter(channel => channel.type === 'text'));
      } else if (channelsParam === 'here') {
        channels.push(message.channel);
      }
    } else {
      channels.concat(channelsParam);
    }
    return channels;
  }

  /**
   * Get the target role or user from the parameter string
   *    or role mentions or user mentions, preferring the latter 2.
   * @param {string} targetParam string from the command to determine the user or role
   * @param {Array<Role>} roleMentions role mentions from the command
   * @param {Array<User>} userMentions user mentions from the command
   * @param {Message} message message to get information on users and roles
   * @returns {Role|User} target or user to disable commands for
   */
  getTarget(targetParam, roleMentions, userMentions, message) {
    let target;
    if (roleMentions.array().length > 0) {
      target = roleMentions.array()[0];
      target.type = 'Role';
    } else if (userMentions.array().length > 0) {
      target = userMentions.array()[0];
      target.type = 'User';
    } else {
      const userTarget = this.bot.client.users.get(targetParam);
      const roleTarget = message.guild.roles.get(targetParam);
      if (targetParam === '*') {
        target = message.guild.roles.find('name', '@everyone');
        target.type = 'Role';
      } else if (roleTarget) {
        target = roleTarget;
        target.type = 'Role';
      } else if (userTarget) {
        target = userTarget;
        target.type = 'User';
      } else {
        target = '';
      }
    }
    return target;
  }
}

module.exports = Disable;


text:
// Authors="Daniel Jonas Møller, Anders Eggers-Krag" License="New BSD License http://sqline.codeplex.com/license"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sqline.ClientFramework.ProviderModel.SqlServer;

namespace Sqline.ClientFramework.ProviderModel {
	public class Provider {
		public static /*IProvider*/ SqlServerProvider Current = new SqlServerProvider("", ""); //HACK: Needs refactoring
	}
}


text:
"""A collection of functional primitives"""
from functools import wraps, partial
from functools import reduce as _reduce
from inspect import getargspec

def curry(fun):
    """
    A working but dirty version of a currying function/decorator.
    """
    def _internal_curry(fun, original=None, given=0):
        if original is None:
            original = fun
        spec = getargspec(original)
        opt = len(spec.defaults or [])
        needed = len(spec.args) - given - opt
        @wraps(fun)
        def internal(*args, **kwargs):
            """The internal currying function"""
            if len(args) >= needed:
                return fun(*args, **kwargs)
            else:
                return _internal_curry(wraps(fun)(partial(fun, *args, **kwargs)),
                                       original,
                                       given=len(args))
        return internal
    return _internal_curry(fun)

@curry
def map(fun, values):
    """
    A function that maps a function to a list of values and returns the new generator.

    Complexity: O(n*k) where k is the complexity of the given function
    params:
        fun: the function that should be applied
        values: the list of values we should map over
    returns:
        the new generator
    """
    return (fun(value) for value in values)

@curry
def filter(fun, values):
    """
    A function that filters a list of values by a predicate function and returns
    a generator.

    Complexity: O(n*k) where k is the complexity of the given function
    params:
        fun: the fucntion that should be applied
        values: the list of values we should filter
    returns:
        the new generator
    """
    return (value for value in values if fun(value))

@curry
def reduce(fun, init, values=None):
    """
    A function that reduces a list to a single value using a given function.

    Complexity: O(n*k) where k is the complexity of the given function
    params:
        fun: the function that should be applied
        values: the list of values we should reduce
    returns:
        the reduced value
    """
    if values is None:
        return _reduce(fun, init)
    else:
        return _reduce(fun, values, init)

@curry
def apply(fun, args, kwargs=None):
    """
    applies a list of arguments (and an optional dict of keyword arguments)
    to a function.

    Complexity: O(k) where k is the complexity of the given function
    params:
        fun: the function that should be applied
        args: the list of values we should reduce
    returns:
        the reduced value
    """
    if kwargs is None:
        kwargs = {}
    return fun(*args, **kwargs)

def pipe(*funs):
    """
    composes a bunch of functions. They will be applied one after the other.

    Complexity: depends on the given functions
    params:
        *funs: the functions that should be chained
    returns: the chained function
    """
    def internal(*args, **kwargs):
        """The internal piping function"""
        return reduce(lambda acc, fun: fun(acc),
                      funs[0](*args, **kwargs),
                      funs[1:])
    return internal

def compose(*funs):
    """
    composes a bunch of functions. They will be applied in reverse order
    (so this function is the reverse of pipe).

    Complexity: depends on the given functions
    params:
        *funs: the functions that should be chained
    returns: the chained function
    """
    return apply(pipe, reversed(funs))

def starpipe(*funs):
    """
    composes a bunch of functions. They will be applied one after the other.
    The arguments will be passed as star args.

    Complexity: depends on the given functions
    params:
        *funs: the functions that should be chained
    returns: the chained function
    """
    def internal(*args, **kwargs):
        """The internal piping function"""
        return reduce(lambda acc, fun: fun(*acc),
                      funs[0](*args, **kwargs),
                      funs[1:])
    return internal

def starcompose(*funs):
    """
    composes a bunch of functions. They will be applied in reverse order
    (so this function is the reverse of starpipe). Like in starpipe, arguments
    will be passed as starargs.

    Complexity: depends on the given functions
    params:
        *funs: the functions that should be chained
    returns: the chained function
    """
    return apply(starpipe, reversed(funs))

def identity(value):
    """
    The identity function. Takes a value and returns it.

    Complexity: O(1)
    params:
        value: the value
    returns: the value
    """
    return value

@curry
def tap(fun, value):
    """
    A function that takes a function and a value, applies the function
    to the value and returns the value.

    Complexity: O(k) where k is the complexity of the given function
    params:
        fun: the function
        value: the value
    returns: the value
    """
    fun(value)
    return value

def constantly(value):
    """
    A generator that returns the given value forever.

    Complexity: O(1)
    params:
        value: the value to return
    returns: an infinite generator of the value
    """
    while True:
        yield value

def delay(fun, *args, **kwargs):
    """
    A function that takes a function and its arguments and delays its execution
    until it is needed. It also caches the executed return value and prevents
    it from being executed again (always returning the first result).

    params:
        fun: the function
        args: the function's args
        kwargs: the function's keyword arguments
    returns: the function result
    """
    # this is a horrible hack around Python 2.x's lack of nonlocal
    _int = ["__delay__unset"]
    @wraps(fun)
    def internal():
        """The internal delay function"""
        if _int[0] == "__delay__unset":
            _int[0] = fun(*args, **kwargs)
        return _int[0]
    return internal

@curry
def flip(fun, first, second, *args):
    """
    Takes a function and applies its arguments in reverse order.

    params:
        fun: the function
        first: the first argument
        second: the second argument
        args: the remaining args (this weird first, second, args thing
              is there to prevent preemptive passing of arguments)
    returns: the result of the function fun
    """
    return apply(fun, reversed(args + (first, second)))


text:
ACCEPTED

#### According to
IRMNG Homonym List

#### Published in
Handb. Naturges. , 1850, 617.

#### Original name
null

### Remarks
null


text:
set -xe

### The dir for the package script
MY_DIR=$( dirname $0 )
cd $MY_DIR
rm -fr *.deb

### Name of the package, project, etc
NAME=krux-tcp-stream-kafka-producer

### The directory that the build is done in
TARGET=target

### package version
### XXX surely there's a maven command or something?
VERSION=$(grep version pom.xml | head -1 | perl -pe 's/[^\d.]//g')
PACKAGE_VERSION=$VERSION~krux$( date -u +%Y%m%d%H%M )
PACKAGE_NAME=$NAME

### Rename jar for packaging
mv "${TARGET}/krux-tcp-stream-kafka-producer-$VERSION-full.jar" "${TARGET}/krux-tcp-stream-kafka-producer-full.jar"

### List of files to package
FILES=krux-tcp-stream-kafka-producer-full.jar

### Where this package will be installed
DEST_DIR="/usr/local/${NAME}/"

### Where the sources live
SOURCE_DIR="${MY_DIR}/${TARGET}"

# run fpm
/usr/local/bin/fpm -s dir -t deb -a all -n $PACKAGE_NAME -v $PACKAGE_VERSION --prefix $DEST_DIR -C $SOURCE_DIR $FILES


text:
using System;
using System.IO;
using GroupDocs.Conversion.Options.Convert;

namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage
{
    /// <summary>
    /// This example demonstrates how to convert VSX file into HTML format.
    /// For more details about Vector Scalar Extension (.vsx) to Hyper Text Markup Language (.html) conversion please check this documentation article
    /// https://docs.groupdocs.com/conversion/net/convert-vsx-to-html
    /// </summary>
    internal static class ConvertVsxToHtml
    {
        public static void Run()
        {
            string outputFolder = Constants.GetOutputDirectoryPath();
            string outputFile = Path.Combine(outputFolder, "vsx-converted-to.html");

            // Load the source VSX file
            using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_VSX))
            {
                var options = new MarkupConvertOptions();
                // Save converted HTML file
                converter.Convert(outputFile, options);
            }

            Console.WriteLine("\nConversion to html completed successfully. \nCheck output in {0}", outputFolder);
        }
    }
}


text:
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <!-- A minimal Flowplayer setup to get you started -->
  <!--
		include flowplayer JavaScript file that does
		Flash embedding and provides the Flowplayer API.
	-->
  <script type="text/javascript" src="flowplayer-3.2.13.min.js"></script>
  <title>FlowPlayer Flash</title>
</head>
<body>
  <!-- this A tag is where your Flowplayer will be placed. it can be anywhere -->
	<a
		 href="http://video-js.zencoder.com/oceans-clip.mp4"
		 style="display:block;width:520px;height:330px"
		 id="player">
	</a>

	<!-- this will install flowplayer inside previous A- tag. -->
  <script>
		flowplayer("player", "flowplayer-3.2.18.swf");
	</script>
</body>
</html>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>onl.area51.filesystem</groupId>
        <artifactId>filesystem-parent</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>filesystem-cdi</artifactId>
    <packaging>jar</packaging>

    <name>Filesystem CDI Extension</name>

    <description>
        CDI Extension to support Filesystems.

        Currently this supports an overlay which can issue a CDI event when a path is updated
    </description>

    <dependencies>
        <dependency>
            <groupId>onl.area51.filesystem</groupId>
            <artifactId>filesystem-core</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <version>2.0-EDR1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
</project>


text:
/**
 * @abstract BaseSyntax
 */
export default
class BaseSyntax {

  /**
   * The constructor of BaseSyntax
   *
   * @param {String} type
   */
    constructor(type) {
    this.type = type;
  }

}


text:
package com.splunk.shuttl.server.distributed;

import java.util.List;

import com.amazonaws.util.json.JSONObject;

public class SearchPeerResponse {

	public List<JSONObject> jsons;
	public List<RuntimeException> exceptions;

	public SearchPeerResponse(List<JSONObject> jsons,
			List<RuntimeException> exceptions) {
		this.jsons = jsons;
		this.exceptions = exceptions;
	}
}


text:
Generate the lyrics of the song 'I Know an Old Lady Who Swallowed a Fly'.

While you could copy/paste the lyrics,
or read them from a file, this problem is much more
interesting if you approach it algorithmically.

This is a [cumulative song](http://en.wikipedia.org/wiki/Cumulative_song) of unknown origin.

This is one of many common variants.

```text
I know an old lady who swallowed a fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a spider.
It wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a bird.
How absurd to swallow a bird!
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a cat.
Imagine that, to swallow a cat!
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a dog.
What a hog, to swallow a dog!
She swallowed the dog to catch the cat.
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a goat.
Just opened her throat and swallowed a goat!
She swallowed the goat to catch the dog.
She swallowed the dog to catch the cat.
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a cow.
I don't know how she swallowed a cow!
She swallowed the cow to catch the goat.
She swallowed the goat to catch the dog.
She swallowed the dog to catch the cat.
She swallowed the cat to catch the bird.
She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.
She swallowed the spider to catch the fly.
I don't know why she swallowed the fly. Perhaps she'll die.

I know an old lady who swallowed a horse.
She's dead, of course!
```

## Setup

Go through the project setup instructions for Xcode using Swift:

http://exercism.io/languages/swift
http://exercism.io/languages/swift/tests

Notably from the source directory:

`swift test` runs tests
`swift package generate-xcodeproj` creates an Xcode project

## Source

Wikipedia [http://en.wikipedia.org/wiki/There_Was_an_Old_Lady_Who_Swallowed_a_Fly](http://en.wikipedia.org/wiki/There_Was_an_Old_Lady_Who_Swallowed_a_Fly)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddEnemyStatuses extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('enemy_statuses', function (Blueprint $table) {
            $table->integer('enemy_id');
            $table->string('status_name');
            $table->string('status_description');
        });
    }
    public function down(){

    }

}


text:
package com.tngtech.jgiven.report.impl;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Optional;
import com.tngtech.jgiven.impl.Config;
import com.tngtech.jgiven.report.analysis.CaseArgumentAnalyser;
import com.tngtech.jgiven.report.json.ScenarioJsonWriter;
import com.tngtech.jgiven.report.model.ReportModel;
import com.tngtech.jgiven.report.text.PlainTextReporter;

public class CommonReportHelper {
    private static final Logger log = LoggerFactory.getLogger( CommonReportHelper.class );

    public void finishReport( ReportModel model ) {
        if( !Config.config().isReportEnabled() ) {
            return;
        }

        if( model == null || model.getScenarios().isEmpty() ) {
            return;
        }

        new CaseArgumentAnalyser().analyze( model );

        if( Config.config().textReport() ) {
            new PlainTextReporter().write( model ).flush();
        }

        Optional<File> optionalReportDir = Config.config().getReportDir();
        if( optionalReportDir.isPresent() ) {
            File reportDir = optionalReportDir.get();
            if( !reportDir.exists() && !reportDir.mkdirs() ) {
                log.error( "Could not create report directory " + reportDir );
            }
            File reportFile = new File( reportDir, model.getClassName() + ".json" );
            log.debug( "Writing scenario report to file " + reportFile.getAbsolutePath() );
            new ScenarioJsonWriter( model ).write( reportFile );
        }
    }
}


text:
<link rel="import" href="../components/polymer/polymer.html">
<link rel="import" href="../post-service/post-service.html">

<polymer-element name="post-list" attributes="show">
  <template>

{{post.number}}

        photos where uploaded by
        {{post.username}}

    <content></content>

  </template>

</polymer-element>


text:
require 'apivore'

RSpec.configure do |config|
end

require 'fixtures/application.rb'
require 'fixtures/controllers.rb'
require 'rspec/rails'


text:
package remote

import (
	"context"
	"strings"
	"testing"

	"github.com/hashicorp/terraform/backend"
	"github.com/hashicorp/terraform/config/module"
	"github.com/hashicorp/terraform/terraform"
	"github.com/mitchellh/cli"
)

func testOperationPlan() *backend.Operation {
	return &backend.Operation{
		Type: backend.OperationTypePlan,
	}
}

func TestRemote_planBasic(t *testing.T) {
	b := testBackendDefault(t)

	mod, modCleanup := module.TestTree(t, "./test-fixtures/plan")
	defer modCleanup()

	op := testOperationPlan()
	op.Module = mod
	op.Workspace = backend.DefaultStateName

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("error starting operation: %v", err)
	}

	<-run.Done()
	if run.Err != nil {
		t.Fatalf("error running operation: %v", run.Err)
	}

	output := b.CLI.(*cli.MockUi).OutputWriter.String()
	if !strings.Contains(output, "1 to add, 0 to change, 0 to destroy") {
		t.Fatalf("missing plan summery in output: %s", output)
	}
}

func TestRemote_planWithPlan(t *testing.T) {
	b := testBackendDefault(t)

	mod, modCleanup := module.TestTree(t, "./test-fixtures/plan")
	defer modCleanup()

	op := testOperationPlan()
	op.Module = mod
	op.Plan = &terraform.Plan{}
	op.Workspace = backend.DefaultStateName

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("error starting operation: %v", err)
	}
	<-run.Done()

	if run.Err == nil {
		t.Fatalf("expected a plan error, got: %v", run.Err)
	}
	if !strings.Contains(run.Err.Error(), "saved plan is currently not supported") {
		t.Fatalf("expected a saved plan error, got: %v", run.Err)
	}
}

func TestRemote_planWithPath(t *testing.T) {
	b := testBackendDefault(t)

	mod, modCleanup := module.TestTree(t, "./test-fixtures/plan")
	defer modCleanup()

	op := testOperationPlan()
	op.Module = mod
	op.PlanOutPath = "./test-fixtures/plan"
	op.Workspace = backend.DefaultStateName

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("error starting operation: %v", err)
	}
	<-run.Done()

	if run.Err == nil {
		t.Fatalf("expected a plan error, got: %v", run.Err)
	}
	if !strings.Contains(run.Err.Error(), "generated plan is currently not supported") {
		t.Fatalf("expected a generated plan error, got: %v", run.Err)
	}
}

func TestRemote_planWithTarget(t *testing.T) {
	b := testBackendDefault(t)

	mod, modCleanup := module.TestTree(t, "./test-fixtures/plan")
	defer modCleanup()

	op := testOperationPlan()
	op.Module = mod
	op.Targets = []string{"null_resource.foo"}
	op.Workspace = backend.DefaultStateName

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("error starting operation: %v", err)
	}
	<-run.Done()

	if run.Err == nil {
		t.Fatalf("expected a plan error, got: %v", run.Err)
	}
	if !strings.Contains(run.Err.Error(), "targeting is currently not supported") {
		t.Fatalf("expected a targeting error, got: %v", run.Err)
	}
}

func TestRemote_planNoConfig(t *testing.T) {
	b := testBackendDefault(t)

	op := testOperationPlan()
	op.Module = nil
	op.Workspace = backend.DefaultStateName

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("error starting operation: %v", err)
	}
	<-run.Done()

	if run.Err == nil {
		t.Fatalf("expected a plan error, got: %v", run.Err)
	}
	if !strings.Contains(run.Err.Error(), "configuration files found") {
		t.Fatalf("expected configuration files error, got: %v", run.Err)
	}
}

func TestRemote_planDestroy(t *testing.T) {
	b := testBackendDefault(t)

	mod, modCleanup := module.TestTree(t, "./test-fixtures/plan")
	defer modCleanup()

	op := testOperationPlan()
	op.Destroy = true
	op.Module = mod
	op.Workspace = backend.DefaultStateName

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("error starting operation: %v", err)
	}

	<-run.Done()
	if run.Err != nil {
		t.Fatalf("unexpected plan error: %v", run.Err)
	}
}

func TestRemote_planDestroyNoConfig(t *testing.T) {
	b := testBackendDefault(t)

	op := testOperationPlan()
	op.Destroy = true
	op.Module = nil
	op.Workspace = backend.DefaultStateName

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("error starting operation: %v", err)
	}

	<-run.Done()
	if run.Err != nil {
		t.Fatalf("unexpected plan error: %v", run.Err)
	}
}


text:
using SharpDX.Direct3D11;

#if !NETFX_CORE
namespace HelixToolkit.Wpf.SharpDX
#else
#if CORE
namespace HelixToolkit.SharpDX.Core
#else
namespace HelixToolkit.UWP
#endif
#endif
{
    namespace Shaders
    {
        using Model;
        /// <summary>
        ///
        /// </summary>
        public static class DefaultBlendStateDescriptions
        {
            public readonly static BlendStateDescription BSAlphaBlend;
            public readonly static BlendStateDescription BSSourceAlways;
            public readonly static BlendStateDescription NoBlend;
            public readonly static BlendStateDescription BSOverlayBlending;
            public readonly static BlendStateDescription AdditiveBlend;
            public readonly static BlendStateDescription BSScreenDupCursorBlend;
            public readonly static BlendStateDescription BSOITBlend = new BlendStateDescription() { IndependentBlendEnable = true };
            public readonly static BlendStateDescription BSMeshOITBlendQuad;
            public readonly static BlendStateDescription VolumeBlending;
            public readonly static BlendStateDescription BSGlowBlending;

            static DefaultBlendStateDescriptions()
            {
                BSAlphaBlend.RenderTarget[0] = new RenderTargetBlendDescription()
                {
                    AlphaBlendOperation = BlendOperation.Add,
                    BlendOperation = BlendOperation.Add,
                    SourceBlend = BlendOption.SourceAlpha,
                    DestinationBlend = BlendOption.InverseSourceAlpha,

                    SourceAlphaBlend = BlendOption.SourceAlpha,
                    DestinationAlphaBlend = BlendOption.DestinationAlpha,
                    IsBlendEnabled = true,
                    RenderTargetWriteMask = ColorWriteMaskFlags.All
                };

                BSSourceAlways.RenderTarget[0] = new RenderTargetBlendDescription()
                {
                    AlphaBlendOperation = BlendOperation.Add,
                    BlendOperation = BlendOperation.Add,
                    DestinationBlend = BlendOption.Zero,
                    SourceBlend = BlendOption.One,
                    DestinationAlphaBlend = BlendOption.Zero,
                    SourceAlphaBlend = BlendOption.One,
                    IsBlendEnabled = false,
                    RenderTargetWriteMask = ColorWriteMaskFlags.All
                };

                NoBlend.RenderTarget[0] = new RenderTargetBlendDescription() { IsBlendEnabled = false };
                BSOverlayBlending.RenderTarget[0] = new RenderTargetBlendDescription()
                {
                    IsBlendEnabled = true,
                    SourceBlend = BlendOption.One,
                    DestinationBlend = BlendOption.One,
                    BlendOperation = BlendOperation.Add,
                    SourceAlphaBlend = BlendOption.Zero,
                    DestinationAlphaBlend = BlendOption.One,
                    AlphaBlendOperation = BlendOperation.Add,
                    RenderTargetWriteMask = ColorWriteMaskFlags.All
                };

                AdditiveBlend.RenderTarget[0] = new RenderTargetBlendDescription()
                {
                    IsBlendEnabled = true,
                    SourceBlend = BlendOption.One,
                    DestinationBlend = BlendOption.One,
                    BlendOperation = BlendOperation.Add,
                    SourceAlphaBlend = BlendOption.One,
                    DestinationAlphaBlend = BlendOption.One,
                    AlphaBlendOperation = BlendOperation.Add,
                    RenderTargetWriteMask = ColorWriteMaskFlags.All
                };

                BSScreenDupCursorBlend.RenderTarget[0] = new RenderTargetBlendDescription()
                {
                    SourceBlend = BlendOption.SourceAlpha,
                    DestinationBlend = BlendOption.InverseSourceAlpha,
                    BlendOperation = BlendOperation.Add,
                    SourceAlphaBlend = BlendOption.One,
                    DestinationAlphaBlend = BlendOption.Zero,
                    AlphaBlendOperation = BlendOperation.Add,
                    RenderTargetWriteMask = ColorWriteMaskFlags.All,
                    IsBlendEnabled = true
                };

                BSOITBlend.RenderTarget[0] = new RenderTargetBlendDescription()
                {
                    IsBlendEnabled = true,
                    SourceBlend = BlendOption.One,
                    DestinationBlend = BlendOption.One,
                    BlendOperation = BlendOperation.Add,
                    SourceAlphaBlend = BlendOption.One,
                    DestinationAlphaBlend = BlendOption.One,
                    AlphaBlendOperation = BlendOperation.Add,
                    RenderTargetWriteMask = ColorWriteMaskFlags.All
                };
                BSOITBlend.RenderTarget[1] = new RenderTargetBlendDescription()
                {
                    IsBlendEnabled = true,
                    SourceBlend = BlendOption.Zero,
                    DestinationBlend = BlendOption.InverseSourceAlpha,
                    BlendOperation = BlendOperation.Add,
                    SourceAlphaBlend = BlendOption.Zero,
                    DestinationAlphaBlend = BlendOption.InverseSourceAlpha,
                    AlphaBlendOperation = BlendOperation.Add,
                    RenderTargetWriteMask = ColorWriteMaskFlags.Alpha
                };

                BSMeshOITBlendQuad.RenderTarget[0] = new RenderTargetBlendDescription()
                {
                    IsBlendEnabled = true,
                    SourceBlend = BlendOption.InverseSourceAlpha,
                    DestinationBlend = BlendOption.SourceAlpha,
                    BlendOperation = BlendOperation.Add,
                    SourceAlphaBlend = BlendOption.InverseSourceAlpha,
                    DestinationAlphaBlend = BlendOption.DestinationAlpha,
                    AlphaBlendOperation = BlendOperation.Add,
                    RenderTargetWriteMask = ColorWriteMaskFlags.Red | ColorWriteMaskFlags.Green | ColorWriteMaskFlags.Blue
                };

                VolumeBlending.RenderTarget[0] = new RenderTargetBlendDescription()
                {
                    AlphaBlendOperation = BlendOperation.Add,
                    BlendOperation = BlendOperation.Add,
                    SourceBlend = BlendOption.SourceAlpha,
                    DestinationBlend = BlendOption.InverseSourceAlpha,

                    SourceAlphaBlend = BlendOption.InverseSourceAlpha,
                    DestinationAlphaBlend = BlendOption.Zero,
                    IsBlendEnabled = true,
                    RenderTargetWriteMask = ColorWriteMaskFlags.All
                };

                BSGlowBlending.RenderTarget[0] = new RenderTargetBlendDescription()
                {
                    BlendOperation = BlendOperation.Add,
                    SourceBlend = BlendOption.One,
                    DestinationBlend = BlendOption.InverseSourceAlpha,

                    SourceAlphaBlend = BlendOption.SourceAlpha,
                    DestinationAlphaBlend = BlendOption.DestinationAlpha,
                    AlphaBlendOperation = BlendOperation.Add,
                    IsBlendEnabled = true,
                    RenderTargetWriteMask = ColorWriteMaskFlags.All
                };
            }
        }
        /// <summary>
        ///
        /// </summary>
        public static class DefaultDepthStencilDescriptions
        {
            /// <summary>
            /// The DSS depth less
            /// </summary>
            public readonly static DepthStencilStateDescription DSSDepthLess = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = false
            };
            /// <summary>
            /// The DSS depth less equal
            /// </summary>
            public readonly static DepthStencilStateDescription DSSDepthLessEqual = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.LessEqual,
                IsStencilEnabled = false
            };
            /// <summary>
            /// The DSS less no write
            /// </summary>
            public readonly static DepthStencilStateDescription DSSLessNoWrite = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = false
            };
            /// <summary>
            /// The DSS less equal no write
            /// </summary>
            public readonly static DepthStencilStateDescription DSSLessEqualNoWrite = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.LessEqual,
                IsStencilEnabled = false
            };
            /// <summary>
            /// The DSS greater no write
            /// </summary>
            public readonly static DepthStencilStateDescription DSSGreaterNoWrite = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Greater
            };
            /// <summary>
            /// The DSS equal no write
            /// </summary>
            public readonly static DepthStencilStateDescription DSSEqualNoWrite = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Equal
            };
            /// <summary>
            /// The DSS clip plane backface
            /// </summary>
            public readonly static DepthStencilStateDescription DSSClipPlaneBackface = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Less,
                StencilWriteMask = 0xFF,
                StencilReadMask = 0,
                BackFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Replace,
                    Comparison = Comparison.Always,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                },
                FrontFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Never,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                }
            };

            /// <summary>
            /// The DSS mesh outline pass1
            /// </summary>
            public readonly static DepthStencilStateDescription DSSMeshOutlineP1 = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false,
                IsStencilEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Always,
                StencilWriteMask = 0xFF,
                StencilReadMask = 0,
                BackFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Never,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                },
                FrontFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Replace,
                    Comparison = Comparison.Always,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                }
            };

            /// <summary>
            /// The DSS mesh outline pass1
            /// </summary>
            public readonly static DepthStencilStateDescription DSSEffectMeshXRayP1 = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false,
                IsStencilEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Always,
                StencilWriteMask = 0xFF,
                StencilReadMask = 0,
                BackFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Never,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                },
                FrontFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Increment,
                    Comparison = Comparison.Always,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                }
            };

            public readonly static DepthStencilStateDescription DSSEffectMeshXRayGridP1 = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false,
                IsStencilEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Always,
                StencilWriteMask = 0xFF,
                StencilReadMask = 0,
                BackFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Never,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                },
                FrontFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Replace,
                    Comparison = Comparison.Always,
                    DepthFailOperation = StencilOperation.Zero,
                    FailOperation = StencilOperation.Zero
                }
            };
            public readonly static DepthStencilStateDescription DSSEffectMeshXRayGridP2 = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.LessEqual,
                StencilWriteMask = 0xFF,
                StencilReadMask = 0,
                BackFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Never,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                },
                FrontFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Zero,
                    Comparison = Comparison.Equal,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Zero
                }
            };
            public readonly static DepthStencilStateDescription DSSEffectMeshXRayGridP3 = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false,
                IsStencilEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.NotEqual,
                StencilWriteMask = 0,
                StencilReadMask = 0xFF,
                BackFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Never,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                },
                FrontFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                }
            };
            /// <summary>
            /// The DSS mesh outline pass1
            /// </summary>
            public readonly static DepthStencilStateDescription DSSEffectMeshXRayP2 = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Greater,
                StencilWriteMask = 0,
                StencilReadMask = 0xFF,
                BackFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Never,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                },
                FrontFace = new DepthStencilOperationDescription()
                {
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal,
                    DepthFailOperation = StencilOperation.Keep,
                    FailOperation = StencilOperation.Keep
                }
            };
            /// <summary>
            /// The DSS clip plane fill quad
            /// </summary>
            public readonly static DepthStencilStateDescription DSSOutlineFillQuad = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false,
                IsStencilEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Always,
                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison = Comparison.Never,
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep
                },
                StencilReadMask = 0xFF,
                StencilWriteMask = 0
            };

            /// <summary>
            /// The DSS clip plane fill quad
            /// </summary>
            public readonly static DepthStencilStateDescription DSSClipPlaneFillQuad = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false,
                IsStencilEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Less,
                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison = Comparison.Never,
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep
                },
                StencilReadMask = 0xFF,
                StencilWriteMask = 0
            };
            /// <summary>
            /// The DSS depth always no stencil
            /// </summary>
            public readonly static DepthStencilStateDescription DSSDepthAlwaysNoStencil = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthComparison = Comparison.Always,
                IsStencilEnabled = false,
            };
            /// <summary>
            /// The DSS no depth no stencil
            /// </summary>
            public readonly static DepthStencilStateDescription DSSNoDepthNoStencil = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.Always,
                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison = Comparison.Always,
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep
                },
                StencilReadMask = 0,
                StencilWriteMask = 0
            };

            public readonly static DepthStencilStateDescription DSSVolumeBackFace = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Zero,
                    Comparison = Comparison.Always
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison = Comparison.Always,
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Zero
                },
                StencilReadMask = 0x00,
                StencilWriteMask = 0xFF
            };

            public readonly static DepthStencilStateDescription DSSVolumeFrontFace = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison = Comparison.Never,
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Zero
                },
                StencilReadMask = 0xFF,
                StencilWriteMask = 0x00
            };
        }

        /// <summary>
        ///
        /// </summary>
        public static class DefaultRasterDescriptions
        {
            /// <summary>
            /// The solid no msaa RasterizerState
            /// </summary>
            public readonly static RasterizerStateDescription RSSolidNoMSAA = new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.Back,
                DepthBias = -5,
                DepthBiasClamp = -10,
                SlopeScaledDepthBias = +0,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
                IsAntialiasedLineEnabled = false,
            };

            /// <summary>
            /// The skybox RasterizerState
            /// </summary>
            public readonly static RasterizerStateDescription RSSkybox = new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = +0,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
                IsAntialiasedLineEnabled = false,
                IsDepthClipEnabled = false
            };

            public readonly static RasterizerStateDescription RSSkyDome = new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = +0,
                IsFrontCounterClockwise = false,
                IsMultisampleEnabled = false,
                IsAntialiasedLineEnabled = false,
                IsDepthClipEnabled = false
            };

            public readonly static RasterizerStateDescription RSOutline = new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = +0,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
                IsAntialiasedLineEnabled = false,
            };

            public readonly static RasterizerStateDescription RSPlaneGrid = new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                DepthBias = 10,
                DepthBiasClamp = 1000,
                SlopeScaledDepthBias = 0,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
                IsAntialiasedLineEnabled = false,
                IsDepthClipEnabled = true,
                IsScissorEnabled = true
            };

            public readonly static RasterizerStateDescription RSSpriteCW = new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsFrontCounterClockwise = false,
                IsMultisampleEnabled = false,
                IsAntialiasedLineEnabled = false,
                IsDepthClipEnabled = false,
                IsScissorEnabled = true
            };

            public readonly static RasterizerStateDescription RSVolume = new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = +0,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
                IsAntialiasedLineEnabled = false,
            };

            public readonly static RasterizerStateDescription RSVolumeCubeFront = new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.Back,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = +0,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
                IsAntialiasedLineEnabled = false,
            };

            public readonly static RasterizerStateDescription RSVolumeCubeBack = new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.Front,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = +0,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
                IsAntialiasedLineEnabled = false,
            };
#if !WINDOWS_UWP
            /// <summary>
            /// The screen duplication RasterizerState
            /// </summary>
            public readonly static RasterizerStateDescription RSScreenDuplication = new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = +0,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
                IsAntialiasedLineEnabled = false,
                IsScissorEnabled = true
            };
#endif
        }
    }
}


text:
#include "common.h"
#include "logmanager.h"
#include <cstdarg>

namespace Tsuki {
    class Debug
    {
    public:
        typedef enum {
            NORMAL,
            WARNING,
            CRITICAL,
            FATAL
        } type_t;

        inline Debug(type_t type=NORMAL) : m_type(type), os(*new std::ostream(LogManager::instance()->getDefaultLog().rdbuf())) { writePrefix(); }
        inline ~Debug() { os << std::endl; delete &os; if(m_type == FATAL) raise(SIGABRT); }

        template<class T>
        Debug &operator <<(const T &t) {
             os << t;
             return *this;
        }

        Debug &operator<<(std::ostream& ( *pf )(std::ostream&)) {
            os << pf;
            return *this;
        }
    protected:
        void writePrefix() {
            switch(m_type) {
            case NORMAL:
                os.write("[Debug] ", 8);
                break;
            case WARNING:
                os.write("[Warning] ", 10);
                break;
            case CRITICAL:
                os.write("[Critical] ", 11);
                break;
            case FATAL:
                os.write("[Fatal] ", 8);
                break;
            }
        }

        type_t m_type;
        std::ostream &os;
    };

    extern int _debug(Debug::type_t type, const char *format, va_list args);

    inline Debug debug() { return Debug(Debug::NORMAL); }
    extern int debug(const char *format, ...);

    inline Debug warning() { return Debug(Debug::WARNING); }
    extern int warning(const char *format, ...);

    inline Debug critical() { return Debug(Debug::CRITICAL); }
    extern int critical(const char *format, ...);

    inline Debug fatal() { return Debug(Debug::FATAL); }
    extern int fatal(const char *format, ...);

    #ifndef NOASSERTIONS
        #define ASSERT(expr) if(expr) { } else { \
            fatal("ASSERTION \"%s\" is false in [%s:%d]", #expr, __FILE__, __LINE__); }
    #else
    #define ASSERT(expr)
    #endif
}

#endif // DEBUG_H


text:
description: Stream a tar file to stdout containing all UCP data volumes.
keywords:
- docker, ucp, backup, restore
title: docker/ucp backup
---

Stream a tar file to stdout containing all UCP data volumes.

## Usage

```none
docker run --rm -i \
  --name ucp \
  -v /var/run/docker.sock:/var/run/docker.sock \
  docker/ucp \
  backup [command options] > backup.tar
```

## Description

This utility will dump out a tar file containing all the contents of the
volumes used by UCP on this node.  This can be used to make periodic
backups suitable for use in the 'restore' command.

When backing up an HA cluster, take backups of all controllers one at
a time, in quick succession, and keep track of the exact time when you
performed each backup.  You will need this timestamp information if you
restoring multiple controllers together.

WARNING

* During the backup, all UCP containers will be temporarily stopped
on this node to prevent data corruption.
* This backup will contain private keys and other sensitive information
and should be stored securely.  You may use the '--passphrase' flag to enable
built-in PGP compatible encryption.

## Options

| Option              | Description                                                                      |
|:--------------------|:---------------------------------------------------------------------------------|
| `--debug, -D`       | Enable debug mode                                                                |
| `--jsonlog`         | Produce json formatted output for easier parsing                                 |
| `--id`              | The ID of the UCP instance to backup                                             |
| `--root-ca-only`    | Backup only the root CA certificates and keys from this controller node          |
| `--passphrase`      | Encrypt the tar file with the provided passphrase [$UCP_PASSPHRASE]              |
| `--interactive, -i` | Enable interactive mode. You will be prompted to enter all required information. |


text:
package director

import (
	"net/http"

	bosherr "github.com/cloudfoundry/bosh-utils/errors"
)

type CPIConfig struct {
	Properties string
}

func (d DirectorImpl) LatestCPIConfig() (CPIConfig, error) {
	resps, err := d.client.CPIConfigs()
	if err != nil {
		return CPIConfig{}, err
	}

	if len(resps) == 0 {
		return CPIConfig{}, bosherr.Error("No CPI config")
	}

	return resps[0], nil
}

func (d DirectorImpl) UpdateCPIConfig(manifest []byte) error {
	return d.client.UpdateCPIConfig(manifest)
}

func (c Client) CPIConfigs() ([]CPIConfig, error) {
	var resps []CPIConfig

	err := c.clientRequest.Get("/cpi_configs?limit=1", &resps)
	if err != nil {
		return resps, bosherr.WrapErrorf(err, "Finding CPI configs")
	}

	return resps, nil
}

func (c Client) UpdateCPIConfig(manifest []byte) error {
	path := "/cpi_configs"

	setHeaders := func(req *http.Request) {
		req.Header.Add("Content-Type", "text/yaml")
	}

	_, _, err := c.clientRequest.RawPost(path, manifest, setHeaders)
	if err != nil {
		return bosherr.WrapErrorf(err, "Updating CPI config")
	}

	return nil
}


text:
def read_prism_file(filename):
    # <header1>  <header2>
    # <values>   <values>
    # ...
    from genomicode import genesetlib

    MATRIX = []
    for x in genesetlib.read_gmx(filename, allow_duplicates=True):
        name, description, genes = x
        x = [description] + genes
        x = [float(x) for x in x]
        values = x
        x = name, values
        MATRIX.append(x)
    return MATRIX

def main():
    import os
    import argparse

    from genomicode import jmath
    #from genomicode import AnnotationMatrix
    #from genomicode import colorlib
    #from genomicode import pcalib
    from genomicode import hashlib

    parser = argparse.ArgumentParser(description="")
    parser.add_argument(
        "datafile", help="Tab-delimited text file in Prism format.  "
        "Each column is a series.  First row is header.")
    parser.add_argument(
        "plot_file", help="Name of image file, e.g. outfile.png.  "
        "Will generate PNG format by default.  If this file name ends with "
        ".pdf, will generate a PDF file instead.")

    group = parser.add_argument_group(title="General Appearance")
    group.add_argument(
        "--no_box", action="store_true",
        help="Turn off the box around the plot.")
    group.add_argument(
        "--height", type=int, help="Height (in pixels) of the plot.")
    group.add_argument(
        "--width", type=int, help="Width (in pixels) of the plot.")
    group.add_argument(
        "--mar_left", default=1.0, type=float,
        help="Scale margin at left of plot.  Default 1.0 (no scaling).")
    group.add_argument(
        "--mar_bottom", default=1.0, type=float,
        help="Scale margin at bottom of plot.  Default 1.0.")

    group = parser.add_argument_group(title="Plot Labels")
    group.add_argument("--title", help="Put a title on the plot.")
    group.add_argument("--xlab", help="Label the X-axis.")
    group.add_argument("--ylab", help="Label the Y-axis.")

    group = parser.add_argument_group(title="Legend")
    group.add_argument(
        "--add_legend", action="store_true", help="Add a legend to the plot.")
    group.add_argument(
        "--legend_inset", type=float, default=0.05,
        help="")
    LEGEND_LOCATIONS = [
        "bottomright", "bottom", "bottomleft", "left", "topleft", "top",
        "topright", "right", "center",]
    group.add_argument(
        "--legend_loc", choices=LEGEND_LOCATIONS,
        help="Where to draw the legend.")

    group = parser.add_argument_group(title="Point Appearance")
    group.add_argument(
        "--scale_points", default=1.0, type=float,
        help="Scale the size of the points.  Default 1.0")
    group.add_argument(
        "--default_color",
        help="Default color of points.  Format: #000000.")

    # Parse the input arguments.
    args = parser.parse_args()
    if not os.path.exists(args.datafile):
        parser.error("File not found: %s" % args.datafile)
    if args.width is not None:
        assert args.width > 10, "too small"
        assert args.width < 4096*16, "width too big"
    if args.height is not None:
        assert args.height > 10, "too small"
        assert args.height < 4096*16, "height too big"
    assert args.mar_bottom > 0 and args.mar_bottom < 10
    assert args.mar_left > 0 and args.mar_left < 10

    assert args.legend_inset >= 0 and args.legend_inset < 10
    if args.legend_loc is None:
        args.legend_loc = "bottomright"
    assert args.scale_points > 0 and args.scale_points < 20

    if args.default_color:
        assert len(args.default_color) == 7
        assert args.default_color[0] == "#"

    # Read the data file.
    # List of (name, values).
    MATRIX = read_prism_file(args.datafile)

    height = args.height or 2400
    width = args.width or 3200

    # Pull out the values and colors for the plot.
    default_color = "#000000"
    if args.default_color:
        default_color = args.default_color

    # Start R and set up the environment.
    R = jmath.start_R()
    R("library(beeswarm)")

    main = jmath.R_var("NA")
    if args.title:
        main = args.title
    sub = ""
    xlab = ""
    if args.xlab:
        xlab = args.xlab
    ylab = ""
    if args.xlab:
        ylab = args.ylab

    lwd_box = 2
    lwd_axis = 2
    #lwd_regr = 3
    cex = 1.0 * args.scale_points
    cex_lab = 1.5
    cex_main = 2.0
    cex_sub = 1.0

    bm_type = "png16m"
    if args.plot_file.lower().endswith(".pdf"):
        bm_type = "pdfwrite"
    jmath.R_fn(
        "bitmap", args.plot_file, type=bm_type,
        height=height, width=width, units="px", res=300)

    # Set the margins.
    x = 5*1.2*args.mar_bottom, 4*1.2*args.mar_left, 4, 2
    mar = [x+0.1 for x in x]
    jmath.R_fn("par", mar=mar, RETVAL="op")

    R("X <- list()")
    for title, values in MATRIX:
        title_h = hashlib.hash_var(title)
        jmath.R_equals(values, "x")
        R('X[["%s"]] <- x' % title_h)

    keywds = {
        "cex.axis" : cex_lab,   # Y-axis
        "cex.names" : cex_lab,  # X-axis
        }
    jmath.R_fn(
        "beeswarm", jmath.R_var("X"),
        main="", xlab="", ylab="", pch=19, cex=cex,
        #axes=jmath.R_var("FALSE"),
        RETVAL="x", **keywds)
    # Make plot area solid white.
    #jmath.R('usr <- par("usr")')
    #jmath.R('rect(usr[1], usr[3], usr[2], usr[4], col="#FFFFFF")')
    #jmath.R_fn(
    #    "hist", jmath.R_var("X"), plot=jmath.R_var("FALSE"),
    #    main=main, xlab="", ylab="", axes=jmath.R_var("FALSE"),
    #    add=jmath.R_var("TRUE"))

    # Calculate correlation, and other statistics.
    # TODO: Should calculate this for each series.
    #r = jmath.R("cor(X, Y)")
    #p_value = jmath.R("cor.test(X, Y)$p.value")
    #r = r[0]
    #p_value = p_value[0]
    #print "R = %.2f" % r
    #print "p = %.2g" % p_value

    if not args.no_box:
        jmath.R_fn("box", lwd=lwd_box)
    jmath.R_fn(
        "title", main=main, sub=sub, xlab=xlab, ylab=ylab,
        **{ "cex.lab" : cex_lab, "cex.main" : cex_main, "cex.sub" : cex_sub })
    R("par(op)")
    jmath.R_fn("dev.off")

    # Print out some statistics.
    #means = []
    #for (title, values) in MATRIX:
    #    m = jmath.mean(values)
    #    means.append(m)
    #header = "Classes", "Means", "p-value"

if __name__ == '__main__':
    main()


text:
namespace chromeos {

// BlueZ predates the common D-Bus Properties API (though it inspired it),
// override dbus::PropertySet to generate the correct method call to get
// all properties, conenect to the correct signal and parse it correctly.
class BluetoothPropertySet : public dbus::PropertySet {
 public:
  BluetoothPropertySet(dbus::ObjectProxy* object_proxy,
                       const std::string& interface,
                       const PropertyChangedCallback& callback)
      : dbus::PropertySet(object_proxy, interface, callback) {}

  // dbus::PropertySet override.
  //
  // Call after construction to connect property change notification
  // signals. Sub-classes may override to use different D-Bus signals.
  virtual void ConnectSignals() OVERRIDE;

  // dbus::PropertySet override.
  //
  // Requests an updated value from the remote object incurring a round-trip.
  virtual void Get(dbus::PropertyBase* property,
                   GetCallback callback) OVERRIDE;

  // dbus::PropertySet override.
  //
  // Queries the remote object for values of all properties and updates
  // initial values.
  virtual void GetAll() OVERRIDE;

  // dbus::PropertySet override.
  //
  // Requests that the remote object change the property to its new value.
  virtual void Set(dbus::PropertyBase* property,
                   SetCallback callback) OVERRIDE;

  // dbus::PropertySet override.
  //
  // Method connected by ConnectSignals() and called by dbus:: when
  // a property is changed.
  virtual void ChangedReceived(dbus::Signal* signal) OVERRIDE;
};

}  // namespace chromeos

#endif  // CHROMEOS_DBUS_BLUETOOTH_PROPERTY_H_


text:
"""\
==============
Tk integration
==============

Simple components providing a basic way to integrate Tk windows as Kamaelia
components.
"""


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Algolog. Stud. 38-39: 208.

#### Original name
null

### Remarks
null


text:
package io.bogar.ecdtool.ui;

import io.bogar.ecdtool.bl.BL;
import io.bogar.ecdtool.bl.MainAction;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

public class StartWindow extends JDialog implements ActionListener {

	private BL bl;
	private ECDToolUI ui;

	private static final String S_SEPARATE = "Separate files per track";
	private static final String S_MONOLITHIC = "One file per album";
	private static final String S_RENAME = "Just rename files";
	private static final String S_RECOMPRESS = "[Re]encode to FLAC";
	private static final String S_UNCOMPRESS = "Save to WAVE";

	private JButton okButton;
	private JButton cancelButton;
	private JButton buttonOutDir;
	private JTextField textOutDir;

	JRadioButton jrSeparate;
	JRadioButton jrMonolithic;
	JRadioButton jrRename;
	JRadioButton jrReCompress;
	JRadioButton jrUnCompress;

	private File currentDirectory = null;

	public StartWindow(ECDToolUI ui, BL bl) {
		super(ui, true);
		this.bl = bl;
		this.ui = ui;
		currentDirectory = new File(bl.getLastSaveDir());
		init();
	}

	private void init() {
		setTitle("Save with offset " + bl.getOffsetCorrection());
		Container c = getContentPane();
		c.setLayout(new BorderLayout());
		JPanel panel = new JPanel();
		panel.setLayout(new GridBagLayout());
		// offset correction
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.gridx = 0;
		constraints.gridy = 0;
		constraints.anchor = GridBagConstraints.CENTER;

		JPanel panelMS = new JPanel();
		panelMS.setLayout(new GridLayout(2,1));
		TitledBorder titledbms = BorderFactory.createTitledBorder("Mode");
		panelMS.setBorder(titledbms);

		boolean mono = bl.isSaveMonolithic() && (bl.getOffsetCorrection()<=0);

		jrSeparate = new JRadioButton(S_SEPARATE);
		jrSeparate.setActionCommand(S_SEPARATE);
		jrSeparate.setSelected(!mono);
		jrSeparate.addActionListener(this);
		jrSeparate.setEnabled(bl.getOffsetCorrection()<=0);
		jrMonolithic = new JRadioButton(S_MONOLITHIC);
		jrMonolithic.setActionCommand(S_MONOLITHIC);
		jrMonolithic.setSelected(mono);
		jrMonolithic.addActionListener(this);
		jrMonolithic.setEnabled(bl.getOffsetCorrection()<=0);
		ButtonGroup monosep = new ButtonGroup();
		monosep.add(jrSeparate);
		monosep.add(jrMonolithic);

		panelMS.add(jrSeparate);
		panelMS.add(jrMonolithic);

		panel.add(panelMS, constraints);

		JPanel panelAction = new JPanel();
		panelAction.setLayout(new GridLayout(3,1));
		TitledBorder titledbAction = BorderFactory.createTitledBorder("Action");
		panelAction.setBorder(titledbAction);

		jrRename=new JRadioButton(S_RENAME);
		jrRename.setEnabled(bl.getOffsetCorrection()==0);
		jrRename.setSelected(jrRename.isEnabled() && bl.getMainAction().equals(MainAction.RENAME));
		jrRename.addActionListener(this);
		panelAction.add(jrRename);

		if (jrRename.isSelected()) {
			jrSeparate.setEnabled(false);
			jrMonolithic.setEnabled(false);
		}

		jrReCompress = new JRadioButton(S_RECOMPRESS);
		jrReCompress.setSelected(!jrRename.isSelected() && bl.getMainAction().equals(MainAction.RECOMPRESS));
		jrReCompress.addActionListener(this);
		panelAction.add(jrReCompress);

		jrUnCompress = new JRadioButton(S_UNCOMPRESS);
		jrUnCompress.setSelected(!jrRename.isSelected() && bl.getMainAction().equals(MainAction.UNCOMPRESS));
		jrUnCompress.addActionListener(this);
		panelAction.add(jrUnCompress);

		constraints.gridx=1;
		panel.add(panelAction, constraints);
		constraints.gridx=0;
		constraints.gridy++;

		ButtonGroup what = new ButtonGroup();
		what.add(jrRename);
		what.add(jrReCompress);
		what.add(jrUnCompress);

		JPanel panelOutDir = new JPanel();
		TitledBorder titledbDir = BorderFactory.createTitledBorder("Output Directory");
		panelOutDir.setBorder(titledbDir);
		buttonOutDir = new JButton("Set");
		buttonOutDir.addActionListener(this);
		buttonOutDir.setEnabled(!bl.getMainAction().equals(MainAction.RENAME));
		panelOutDir.add(buttonOutDir);
		String outDir = bl.getMainAction().equals(MainAction.RENAME) ? bl.getLastOpenDir() : bl.getLastSaveDir();
		textOutDir = new JTextField(outDir);
		textOutDir.setColumns(64);
		textOutDir.setEditable(false);
		panelOutDir.add(textOutDir);

		constraints.gridwidth=2;
		panel.add(panelOutDir, constraints);
		c.add(panel, BorderLayout.CENTER);

		JPanel bottomPanel = new JPanel();
		okButton = new JButton("OK");
		bottomPanel.add(okButton);
		cancelButton = new JButton("Cancel");
		bottomPanel.add(cancelButton);

		c.add(bottomPanel, BorderLayout.SOUTH);

		okButton.addActionListener(this);
		cancelButton.addActionListener(this);
		pack();
		setLocation(300,300);
	}

	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		if (source.equals(okButton)) {
			bl.setSaveMonolithic(jrMonolithic.isSelected());
			if (jrRename.isSelected()) {
				bl.setMainAction(MainAction.RENAME);
			} else if (jrReCompress.isSelected()) {
				bl.setMainAction(MainAction.RECOMPRESS);
			} else if (jrUnCompress.isSelected()) {
				bl.setMainAction(MainAction.UNCOMPRESS);
			}
			bl.setLastSaveDir(currentDirectory.getAbsolutePath());
			Thread t = new DoTheDirtyJob(ui, bl);
			t.start();
			dispose();
		} else if (source.equals(cancelButton)) {
			dispose();
		} else if (source.equals(buttonOutDir)) {
			JFileChooser chooser = new JFileChooser();
			if (bl.getLastSaveDir() != null) {
				chooser.setCurrentDirectory(new File(bl.getLastSaveDir()));
			}
			//chooser.setDialogType(JFileChooser.SAVE_DIALOG);
			chooser.setDialogTitle("Please select the output directory");
			chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			int result = chooser.showSaveDialog(this);

			if (result == JFileChooser.CANCEL_OPTION)
				return;

			currentDirectory = chooser.getSelectedFile();
			textOutDir.setText(currentDirectory.getAbsolutePath());
		} else if (source.equals(jrRename)) {
			buttonOutDir.setEnabled(false);
			textOutDir.setText(bl.getLastOpenDir());
			jrSeparate.setEnabled(false);
			jrMonolithic.setEnabled(false);
		} else if (source.equals(jrReCompress) || source.equals(jrUnCompress)) {
			buttonOutDir.setEnabled(true);
			textOutDir.setText(currentDirectory.getAbsolutePath());
			jrSeparate.setEnabled(true);
			jrMonolithic.setEnabled(true);
		}

	}

}


text:
<?php

namespace Imponeer\Properties\Tests\Types;

use Imponeer\Properties\PropertiesInterface;
use Imponeer\Properties\Tests\TestTypeAbstract;

class StringTypeTest extends TestTypeAbstract
{

	/**
	 * Tests if initial was null
	 */
	public function testIfInitialWasNull()
	{
		$this->assertInternalType('null', $this->mock->v, 'DTYPE_STRING must have null unconverted');
	}

	/**
	 * Test conversions when setting var
	 */
	public function testConversions()
	{
		foreach ($this->test_data as $v) {
			if (is_object($v) && ($v instanceof \Closure)) {
				continue;
			}
			$this->mock->v = $v;
			$this->assertInternalType('string', $this->mock->v, 'DTYPE_STRING must convert all data (' . var_export(['original' => $v, 'cleaned' => $this->mock->v], true) . ')');
		}
	}

	/**
	 * @inheritdoc
	 */
	protected function getDataType()
	{
		return PropertiesInterface::DTYPE_STRING;
	}
}


text:
set -e
mydir=`dirname "$0"`
mydir=`realpath "$mydir"`

echo "\n\n\tRestarting https://knetminer.com/Fusarium_culmorum\n"

. "$mydir/../_utils.sh"

cd "$HOME/software/knetminer/docker"

container_id=fcul_2020oxl-mem20g
dataset_dir="$HOME/data/fcul"
clean_flag="$1"

prepare_docker "$container_id" "$dataset_dir" "$clean_flag"

export DOCKER_OPTS="-it --restart unless-stopped"
./docker-run.sh --dataset-id fungi/fculmorum --dataset-dir "$dataset_dir" \
  --container-name "$container_id" --host-port 8083 --container-memory 20G --detach


text:
idle.land
=========

A Meteor web interface for Idle Lands.

To install:
* install [meteor](http://docs.meteor.com/)
* clone the repository
* run `meteor update`
* run `./run.sh`
* go to `localhost:3000`


text:
package mx.itam.metodos.bf;

import mx.itam.metodos.common.IntArrayWritable;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class BFLMDriver extends Configured implements Tool {

  public static final String N = "n";
  public static final String P = "p";
  public static final String OUT_PATH = "out-path";

  @Override
  public int run(String[] args) throws Exception {
    Configuration conf = getConf();
    Path data = new Path(args[0]);
    int rows = Integer.parseInt(args[2]);
    conf.setInt(N, rows);
    float err = Float.parseFloat(args[3]);
    conf.setFloat(P, err);
    conf.set(OUT_PATH, args[4]);
    String suffix = String.format("%s", rows);
    Path out = new Path(args[1] + "-" + suffix);
    out.getFileSystem(conf).delete(out, true);
    return (computeNGrams(data, out, conf)) ? 0 : 1;
  }

  private static boolean computeNGrams(Path data, Path out, Configuration conf)
          throws Exception {
    Job job = new Job(conf, "compute-ngrams");
    job.setJarByClass(BFLMDriver.class);
    job.setMapperClass(TrainBFMapper.class);
    job.setMapOutputKeyClass(NullWritable.class);
    job.setMapOutputValueClass(IntArrayWritable.class);
    job.setReducerClass(TrainBFReducer.class);
    job.setNumReduceTasks(1);
    job.setOutputKeyClass(NullWritable.class);
    job.setOutputValueClass(NullWritable.class);
    job.setInputFormatClass(TextInputFormat.class);
    job.setOutputFormatClass(TextOutputFormat.class);
    FileInputFormat.setInputPaths(job, data);
    FileOutputFormat.setOutputPath(job, out);
    return job.waitForCompletion(true);
  }

  public static void main(String[] args) throws Exception {
    int res = ToolRunner.run(new Configuration(), new BFLMDriver(), args);
    System.exit(res);
  }
}


text:
<?php
// Adapters to authenticate with
$dbAdapter = new Zend_Auth_Adapter_DbTable($db, 'users');
$dbAdapter->setIdentityColumn('username')
          ->setCredentialColumn('password')
          ->setIdentity('john')
          ->setCredential('xxx');

$ldapAdpater = new Zend_Auth_Adapter_Ldap(array(), 'john', 'xxx');

// Setup chain adapter
$chain = new Zym_Auth_Adapter_Chain();
$chain->addAdapter($dbAdapter)
      ->addAdapter($ldapAdpater);

// Authenticate with Zend_Auth to persist
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($chain);

// Did we pass?
if ($result->isValid()) {
    // Get the successful adapter
    $successAdapter = $chain->getLastSuccessfulAdapter();
    if ($successAdapter === $dbAdapter) {
        // Do something like store user info in session
    } else if ($successAdapter === $ldapAdpater) {
        // Do something like store user info in session
    }
}


text:
var ecc = require("./index.js");
var key1 = new ecc.ECKey(ecc.ECCurves.secp160r1);
var key2 = new ecc.ECKey(ecc.ECCurves.secp160r1);
console.log(key1.deriveSharedSecret(key2));
var key3 = new ecc.ECKey(ecc.ECCurves.secp160r1,key1.PrivateKey);
var key4 = new ecc.ECKey(ecc.ECCurves.secp160r1,key2.PublicKey,true);
console.log(key3.deriveSharedSecret(key4));

var key1 = new ecc.ECKey(ecc.ECCurves.secp256r1);
var key2 = new ecc.ECKey(ecc.ECCurves.secp256r1);
console.log(key1.deriveSharedSecret(key2));
var key3 = new ecc.ECKey(ecc.ECCurves.secp256r1,key1.PrivateKey);
var key4 = new ecc.ECKey(ecc.ECCurves.secp256r1,key2.PublicKey,true);
console.log(key3.deriveSharedSecret(key4));