text:
'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
    errorHandler = require('../errors'),
    mongoose = require('mongoose'),
    passport = require('passport'),
    sanitizeHtml = require('sanitize-html'),
    async = require('async'),
    config = require('../../../config/config'),
    nodemailer = require('nodemailer'),
    crypto = require('crypto'),
    User = mongoose.model('User'),
    Contact = mongoose.model('Contact'),
    lwip = require('lwip'),
    mkdirp = require('mkdirp'),
    fs = require('fs');

/* This declares to JSHint that 'settings' is a global variable: */
/* global settings:false */

// Fields to send publicly about any user profile
// to make sure we're not sending unsecure content (eg. passwords)
// Pick here fields to send
exports.userProfileFields = [
                    'id',
                    'displayName',
                    'username',
                    'displayUsername',
                    'gender',
                    'tagline',
                    'description',
                    'locationFrom',
                    'locationLiving',
                    'languages',
                    'birthdate',
                    'seen',
                    'created',
                    'updated',
                    'avatarSource',
                    'avatarUploaded',
                    'emailHash', // MD5 hashed email to use with Gravatars
                    'additionalProvidersData.facebook.id', // For FB avatars
                    'additionalProvidersData.facebook.link', // For FB profile links
                    'additionalProvidersData.twitter.screen_name', // For Twitter profile links
                    'additionalProvidersData.github.login' // For GitHub profile links
                    ].join(' ');

// Restricted set of profile fields when only really "miniprofile" is needed
exports.userMiniProfileFields = 'id displayName username displayUsername avatarSource avatarUploaded emailHash additionalProvidersData.facebook.id';

/**
 * Rules for sanitizing user description coming in and out
 * @link https://github.com/punkave/sanitize-html
 */
var userSanitizeOptions = {
    allowedTags: [ 'p', 'br', 'b', 'i', 'em', 'strong', 'a', 'li', 'ul', 'ol', 'blockquote', 'code', 'pre' ],
    allowedAttributes: {
      'a': [ 'href' ],
      // We don't currently allow img itself, but this would make sense if we did:
      //'img': [ 'src' ]
    },
    selfClosing: [ 'img', 'br' ],
    // URL schemes we permit
    allowedSchemes: [ 'http', 'https', 'ftp', 'mailto', 'tel' ]
  };

/**
 * Upload user avatar
 */

exports.upload = function (req, res) {
  var userId = req.user._id;
  var options = {
    tmpDir:  __dirname + '/../../../public/modules/users/img/profile/uploads/'+userId+'/tmp/',
    uploadDir: __dirname + '/../../../public/modules/users/img/profile/uploads/'+userId+'/avatar/',
    uploadUrl: '/modules/users/img/profile/uploads/'+userId+'/avatar/',
    acceptFileTypes:  /\.(gif|jpe?g|png|GIF|JPE?G|PNG)/i,
    inlineFileTypes:  /\.(gif|jpe?g|png|GIF|JPE?G|PNG)/i,
    imageTypes:  /\.(gif|jpe?g|png|GIF|JPE?G|PNG)/i,
    minFileSize:  1,
    maxFileSize:  10000000, //10MB
    storage: {
      type: 'local'
    },
    useSSL: config.https
  };
  var uploader = require('blueimp-file-upload-expressjs')(options);
  // Make tmp directory
  mkdirp(options.tmpDir, function (err) {
    // Make upload directory
    mkdirp(options.uploadDir, function (err) {
      //Make the upload
      uploader.post(req, res, function (obj) {

        if(obj.files[0].error) {
          console.log(obj.files[0].error);
          res.status(400).send(obj.files[0].error);
        }
        else {
          //Process images
          async.waterfall([
            //Open the image
            function(done) {
              lwip.open(options.uploadDir + '/' + obj.files[0].name, function(err, image){
                done(err, image);
              });
            },
            //Create orginal jpg file
            function(image, done) {
              image.batch()
              .writeFile(options.uploadDir + 'original.jpg', 'jpg', {quality: 90}, function(err, image, res){
                done(err, image);
              });
            },
            //Delete the uploaded file
            function(image, done) {
              fs.unlink(options.uploadDir + '/' + obj.files[0].name, function (err) {
                done(err, image);
              });
            },
            //Make the thumbnails
            function(image, done) {

              // Note that each spawns these functions in order but they are processed asynchronously
              _.each([512, 256, 128, 64, 32], function(size, index, list) {

                lwip.open(options.uploadDir + 'original.jpg', function(err, image){
                  if(!err) {
                    var square = Math.min(image.width(), image.height());
                    image.batch()
                    .crop(square, square)
                    .resize(size, size)
                    .writeFile(options.uploadDir + size +'.jpg', 'jpg', {quality: 90}, function(err, image){

                      // Shorten list so we can keep track on processed count (doesn't keep track on WHICH sizes has been processed)
                      list.pop();

                      // Finish on errors & when list is empty (=all sizes done)
                      if(err || list.length === 0) {
                        done(err);
                      }
                    });
                  }
                  else {
                    done(err);
                  }
                });
              });

            },
            //Send response
            function(done) {
              res.send(JSON.stringify(obj));
            }
          ], function(err) {
            if (err) {
              return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
              });
            }
          });
        }
      });

    });
  });
};

/**
* Update
*/
exports.update = function(req, res) {
  async.waterfall([

  // Generate random token
  function(done) {
    // Generate only if email changed
    if(req.body.email !== req.user.email) {
      crypto.randomBytes(20, function(err, buffer) {
        var token = buffer.toString('hex');
        done(err, token, req.body.email);
      });
    }
    // Email didn't change, just continue
    else {
      done(null, false, false);
    }
  },

  // Update user
  function(token, email, done) {

    // Init Variables
    var user = req.user;
    var message = null;

    // For security measurement remove these from the req.body object
    // Users aren't allowed to modify these directly
    delete req.body.seen;
    delete req.body.roles;
    delete req.body.email;
    delete req.body.public;
    delete req.body.created;
    delete req.body.username;
    delete req.body.emailToken;
    delete req.body.emailTemporary;
    delete req.body.salt;
    delete req.body.password;
    delete req.body.resetPasswordToken;
    delete req.body.resetPasswordExpires;

    if (user) {
      // Merge existing user
      user = _.extend(user, req.body);
      user.updated = Date.now();
      user.displayName = user.firstName + ' ' + user.lastName;

      // This is set only if user edited also email
      if(token && email) {
        user.emailToken = token;
        user.emailTemporary = email;
      }

      // Sanitize user description
      user.description = sanitizeHtml(user.description, userSanitizeOptions);

      user.save(function(err) {
        if (!err) {
          req.login(user, function(err) {
            if (err) {
              done(err);
            } else {
              delete user.emailToken;
              res.json(user);
            }
          });
        }
        done(err, token, user);
      });
    } else {
      done(new Error('User is not signed in'));
    }

  },

  // Prepare TEXT mail
  function(token, user, done) {

    // If no token, user didn't change email = pass this phase
    if(token) {

      var url = (config.https ? 'https' : 'http') + '://' + req.headers.host;
      var renderVars = {
        url: url,
        name: user.displayName,
        email: user.emailTemporary,
        urlConfirm: url + '/#!/confirm-email/' + token
      };

      res.render('email-templates-text/email-confirmation', renderVars, function(err, emailPlain) {
        done(err, emailPlain, user, renderVars);
      });
    }
    else {
      done(null, false, false, false);
    }
  },

  // Prepare HTML mail
  function(emailPlain, user, renderVars, done) {

    // If no emailPlain, user didn't change email = pass this phase
    if(emailPlain) {
      res.render('email-templates/email-confirmation', renderVars, function(err, emailHTML) {
        done(err, emailHTML, emailPlain, user);
      });
    }
    else {
      done(null, false, false, false);
    }
  },

  // If valid email, send confirm email using service
  function(emailHTML, emailPlain, user, done) {

    // If no emailHTML, user didn't change email = pass this phase
    if(emailHTML) {
      var smtpTransport = nodemailer.createTransport(config.mailer.options);
      var mailOptions = {
        to: user.displayName + ' <' + user.emailTemporary + '>',
        from: 'Trustroots <' + config.mailer.from + '>',
        subject: 'Confirm email change',
        text: emailPlain,
        html: emailHTML
      };
      smtpTransport.sendMail(mailOptions, function(err) {
        smtpTransport.close(); // close the connection pool
        done(err);
      });
    }
    else {
      done(null);
    }
  },

  ], function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }
  });
};

/**
 * Show the profile of the user
 */
exports.getUser = function(req, res) {
  res.json(req.user || null);
};

/**
 * Show the mini profile of the user
 * Pick only certain fields from whole profile @link http://underscorejs.org/#pick
 */
exports.getMiniUser = function(req, res) {
  res.json( req.user || null );
};

/**
 * List of public profiles
 */
exports.list = function(req, res) {

  // If user who is loading is hidden, don't show anything
  if(!req.user || !req.user.public) {
    return res.status(400).send('No access.');
  }

  User.find({public: true}).sort('-created').exec(function(err, users) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(users);
    }
  });
};

/**
 * Mini profile middleware
 */
exports.userMiniByID = function(req, res, next, id) {

  User.findById(id, exports.userMiniProfileFields + ' languages public').exec(function(err, user) {

    // Something went wrong
    if (err) {
      return next(err);
    }
    // No such user
    else if (!user) {
      return next(new Error('Failed to load user ' + id));
    }
    // User's own profile
    else if( (user && req.user) && (user._id.toString() === req.user._id.toString())) {
      req.user = user;
      next();
    }
    // If user to be loaded is hidden OR user who is loading is hidden, don't show anything
    else if(!user.public || !req.user.public) {
      return next(new Error('Failed to load user ' + id));
    }
    else {
      // This isn't needed at frontend
      delete user.public;

      req.user = user;
      next();
    }

  });
};

/**
 * Profile middleware
 */
exports.userByUsername = function(req, res, next, username) {

  async.waterfall([

    // Find user
    function(done) {
      User.findOne({
          username: username.toLowerCase()
      }, exports.userProfileFields + ' public').exec(function(err, user) {

        // Something went wrong or no such user
        if (err) {
          done(err);
        }
        else if(!user) {
          done(new Error('Failed to load user ' + username));
        }
        // User's own profile
        else if( (user && req.user) && (user._id.toString() === req.user._id.toString()) ) {
          done(err, user.toObject());
        }
        // If user to be loaded is hidden OR user who is loading is hidden, don't show anything
        else if( (user && user.public === false) || (req.user && req.user.public === false) ) {
          done(new Error('Failed to load user ' + username));
        }
        else {
          // This isn't needed at frontend
          delete user.public;

          // Transform user into object so that we can add new fields to it
          done(err, user.toObject());
        }

      });
    },

    // Check if logged in user has left contact request for this profile
    function(user, done) {

      // User isn't currently logged in?
      if(!req.user) {
        done(null, user);
      }
      // User's own profile?
      else if(user._id.toString() === req.user.id) {
        user.contact = false;
        done(null, user);
      }
      // Check for connection
      else {
        Contact.findOne(
          {
            users: { $all: [ user._id.toString(), req.user.id ] }
          }
        ).exec(function(err, contact) {
          user.contact = (contact) ? contact._id : false;
          done(err, user);
        });
      }
    },

    // Sanitize & return user
    function(user, done) {

      if(user.description) user.description = sanitizeHtml(user.description, userSanitizeOptions);

      req.user = user;
      next();
    }

  ], function(err) {
    if (err) return next(err);
  });

};


text:
require 'rexml/document'

# SimpleXML like xml parser. Written by leon breet from the ruby on rails Mailing list
class XmlNode #:nodoc:
  attr :node

  def initialize(node, options = {})
    @node = node
    @children = {}
    @raise_errors = options[:raise_errors]
  end

  def self.from_xml(xml_or_io)
    document = REXML::Document.new(xml_or_io)
    if document.root
      XmlNode.new(document.root)
    else
      XmlNode.new(document)
    end
  end

  def node_encoding
    @node.encoding
  end

  def node_name
    @node.name
  end

  def node_value
    @node.text
  end

  def node_value=(value)
    @node.text = value
  end

  def xpath(expr)
    matches = nil
    REXML::XPath.each(@node, expr) do |element|
      matches ||= XmlNodeList.new
      matches << (@children[element] ||= XmlNode.new(element))
    end
    matches
  end

  def method_missing(name, *args)
    name = name.to_s
    nodes = nil
    @node.each_element(name) do |element|
      nodes ||= XmlNodeList.new
      nodes << (@children[element] ||= XmlNode.new(element))
    end
    nodes
  end

  def <<(node)
    if node.is_a? REXML::Node
      child = node
    elsif node.respond_to? :node
      child = node.node
    end
    @node.add_element child
    @children[child] ||= XmlNode.new(child)
  end

  def [](name)
    @node.attributes[name.to_s]
  end

  def []=(name, value)
    @node.attributes[name.to_s] = value
  end

  def to_s
    @node.to_s
  end

  def to_i
    to_s.to_i
  end
end

class XmlNodeList < Array #:nodoc:
  def [](i)
    i.is_a?(String) ? super(0)[i] : super(i)
  end

  def []=(i, value)
    i.is_a?(String) ? self[0][i] = value : super(i, value)
  end

  def method_missing(name, *args)
    name = name.to_s
    self[0].__send__(name, *args)
  end
end

redpajama_set_name: RedPajamaGithub


text:
<!--
Description: entry author uri
Expect:      not bozo and entries[0]['author_detail']['url'] == 'http://example.com/'
-->
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<entry>
  <author>
    <name>Example author</name>
    <email>me@example.com</email>
    <uri>http://example.com/</uri>
  </author>
</entry>
</feed>


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Auxiliary Arithmetic Algorithms: vector_space_range.hpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Auxiliary Arithmetic Algorithms

Main Page

Classes

Files

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

File List

File Members

Functions

vector_space_range.hpp File Reference

#include <algorithm>

#include "traits.hpp"

Go to the source code of this file.

Functions

template<typename IteratorIn1 , typename IteratorIn2 , typename IteratorOut , check_sum< value_type_i< IteratorIn1 >, value_type_i< IteratorIn2 >, value_type_i< IteratorOut >>  = 0>

void 	add (IteratorIn1 left_begin, IteratorIn1 left_end, IteratorIn2 right_begin, IteratorOut out_begin)

template<typename ElementIn , typename IteratorIn , typename IteratorOut , check_sum< ElementIn, value_type_i< IteratorIn >, value_type_i< IteratorOut >>  = 0>

void 	add (const ElementIn &left, IteratorIn right_begin, IteratorIn right_end, IteratorOut out_begin)

template<typename IteratorIn , typename ElementIn , typename IteratorOut , check_sum< value_type_i< IteratorIn >, ElementIn, value_type_i< IteratorOut >>  = 0>

void 	add (IteratorIn left_begin, IteratorIn left_end, const ElementIn &right, IteratorOut out_begin)

template<typename IteratorIn1 , typename IteratorIn2 , typename IteratorOut , check_difference< value_type_i< IteratorIn1 >, value_type_i< IteratorIn2 >, value_type_i< IteratorOut >>  = 0>

void 	subtract (IteratorIn1 left_begin, IteratorIn1 left_end, IteratorIn2 right_begin, IteratorOut out_begin)

template<typename ElementIn , typename IteratorIn , typename IteratorOut , check_difference< ElementIn, value_type_i< IteratorIn >, value_type_i< IteratorOut >>  = 0>

void 	subtract (const ElementIn &left, IteratorIn right_begin, IteratorIn right_end, IteratorOut out_begin)

template<typename IteratorIn , typename ElementIn , typename IteratorOut , check_difference< value_type_i< IteratorIn >, ElementIn, value_type_i< IteratorOut >>  = 0>

void 	subtract (IteratorIn left_begin, IteratorIn left_end, const ElementIn &right, IteratorOut out_begin)

template<typename IteratorIn1 , typename IteratorIn2 , typename IteratorOut , check_product< value_type_i< IteratorIn1 >, value_type_i< IteratorIn2 >, value_type_i< IteratorOut >>  = 0>

void 	multiply (IteratorIn1 left_begin, IteratorIn1 left_end, IteratorIn2 right_begin, IteratorOut out_begin)

template<typename ElementIn , typename IteratorIn , typename IteratorOut , check_product< ElementIn, value_type_i< IteratorIn >, value_type_i< IteratorOut >>  = 0>

void 	multiply (const ElementIn &left, IteratorIn right_begin, IteratorIn right_end, IteratorOut out_begin)

template<typename IteratorIn , typename ElementIn , typename IteratorOut , check_product< value_type_i< IteratorIn >, ElementIn, value_type_i< IteratorOut >>  = 0>

void 	multiply (IteratorIn left_begin, IteratorIn left_end, const ElementIn &right, IteratorOut out_begin)

template<typename IteratorIn1 , typename IteratorIn2 , typename IteratorOut , check_ratio< value_type_i< IteratorIn1 >, value_type_i< IteratorIn2 >, value_type_i< IteratorOut >>  = 0>

void 	divide (IteratorIn1 left_begin, IteratorIn1 left_end, IteratorIn2 right_begin, IteratorOut out_begin)

template<typename ElementIn , typename IteratorIn , typename IteratorOut , check_ratio< ElementIn, value_type_i< IteratorIn >, value_type_i< IteratorOut >>  = 0>

void 	divide (const ElementIn &left, IteratorIn right_begin, IteratorIn right_end, IteratorOut out_begin)

template<typename IteratorIn , typename ElementIn , typename IteratorOut , check_ratio< value_type_i< IteratorIn >, ElementIn, value_type_i< IteratorOut >>  = 0>

void 	divide (IteratorIn left_begin, IteratorIn left_end, const ElementIn &right, IteratorOut out_begin)

Function Documentation

template<typename IteratorIn1 , typename IteratorIn2 , typename IteratorOut , check_sum< value_type_i< IteratorIn1 >, value_type_i< IteratorIn2 >, value_type_i< IteratorOut >>  = 0>

          void add
          (
          IteratorIn1
          left_begin,

          IteratorIn1
          left_end,

          IteratorIn2
          right_begin,

          IteratorOut
          out_begin

          )

template<typename ElementIn , typename IteratorIn , typename IteratorOut , check_sum< ElementIn, value_type_i< IteratorIn >, value_type_i< IteratorOut >>  = 0>

          void add
          (
          const ElementIn &
          left,

          IteratorIn
          right_begin,

          IteratorIn
          right_end,

          IteratorOut
          out_begin

          )

template<typename IteratorIn , typename ElementIn , typename IteratorOut , check_sum< value_type_i< IteratorIn >, ElementIn, value_type_i< IteratorOut >>  = 0>

          void add
          (
          IteratorIn
          left_begin,

          IteratorIn
          left_end,

          const ElementIn &
          right,

          IteratorOut
          out_begin

          )

template<typename IteratorIn1 , typename IteratorIn2 , typename IteratorOut , check_ratio< value_type_i< IteratorIn1 >, value_type_i< IteratorIn2 >, value_type_i< IteratorOut >>  = 0>

          void divide
          (
          IteratorIn1
          left_begin,

          IteratorIn1
          left_end,

          IteratorIn2
          right_begin,

          IteratorOut
          out_begin

          )

template<typename ElementIn , typename IteratorIn , typename IteratorOut , check_ratio< ElementIn, value_type_i< IteratorIn >, value_type_i< IteratorOut >>  = 0>

          void divide
          (
          const ElementIn &
          left,

          IteratorIn
          right_begin,

          IteratorIn
          right_end,

          IteratorOut
          out_begin

          )

template<typename IteratorIn , typename ElementIn , typename IteratorOut , check_ratio< value_type_i< IteratorIn >, ElementIn, value_type_i< IteratorOut >>  = 0>

          void divide
          (
          IteratorIn
          left_begin,

          IteratorIn
          left_end,

          const ElementIn &
          right,

          IteratorOut
          out_begin

          )

template<typename IteratorIn1 , typename IteratorIn2 , typename IteratorOut , check_product< value_type_i< IteratorIn1 >, value_type_i< IteratorIn2 >, value_type_i< IteratorOut >>  = 0>

          void multiply
          (
          IteratorIn1
          left_begin,

          IteratorIn1
          left_end,

          IteratorIn2
          right_begin,

          IteratorOut
          out_begin

          )

template<typename ElementIn , typename IteratorIn , typename IteratorOut , check_product< ElementIn, value_type_i< IteratorIn >, value_type_i< IteratorOut >>  = 0>

          void multiply
          (
          const ElementIn &
          left,

          IteratorIn
          right_begin,

          IteratorIn
          right_end,

          IteratorOut
          out_begin

          )

template<typename IteratorIn , typename ElementIn , typename IteratorOut , check_product< value_type_i< IteratorIn >, ElementIn, value_type_i< IteratorOut >>  = 0>

          void multiply
          (
          IteratorIn
          left_begin,

          IteratorIn
          left_end,

          const ElementIn &
          right,

          IteratorOut
          out_begin

          )

template<typename IteratorIn1 , typename IteratorIn2 , typename IteratorOut , check_difference< value_type_i< IteratorIn1 >, value_type_i< IteratorIn2 >, value_type_i< IteratorOut >>  = 0>

          void subtract
          (
          IteratorIn1
          left_begin,

          IteratorIn1
          left_end,

          IteratorIn2
          right_begin,

          IteratorOut
          out_begin

          )

template<typename ElementIn , typename IteratorIn , typename IteratorOut , check_difference< ElementIn, value_type_i< IteratorIn >, value_type_i< IteratorOut >>  = 0>

          void subtract
          (
          const ElementIn &
          left,

          IteratorIn
          right_begin,

          IteratorIn
          right_end,

          IteratorOut
          out_begin

          )

template<typename IteratorIn , typename ElementIn , typename IteratorOut , check_difference< value_type_i< IteratorIn >, ElementIn, value_type_i< IteratorOut >>  = 0>

          void subtract
          (
          IteratorIn
          left_begin,

          IteratorIn
          left_end,

          const ElementIn &
          right,

          IteratorOut
          out_begin

          )

vector_space_range.hpp

Generated by

     1.8.11


text:
package com.amazonaws.services.cloudsearchdomain.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.cloudsearchdomain.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * SuggestStatus JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SuggestStatusJsonUnmarshaller implements Unmarshaller<SuggestStatus, JsonUnmarshallerContext> {

    public SuggestStatus unmarshall(JsonUnmarshallerContext context) throws Exception {
        SuggestStatus suggestStatus = new SuggestStatus();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("timems", targetDepth)) {
                    context.nextToken();
                    suggestStatus.setTimems(context.getUnmarshaller(Long.class).unmarshall(context));
                }
                if (context.testExpression("rid", targetDepth)) {
                    context.nextToken();
                    suggestStatus.setRid(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return suggestStatus;
    }

    private static SuggestStatusJsonUnmarshaller instance;

    public static SuggestStatusJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new SuggestStatusJsonUnmarshaller();
        return instance;
    }
}


text:
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "phcharacter.h"
#include "Physics.h"
#include "ExtendedGeom.h"
#include "PHCapture.h"
#include "entity_alive.h"
#include "phmovementcontrol.h"
#include "../skeletoncustom.h"
#include "characterphysicssupport.h"
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////

void CPHCapture::CreateBody()
{
	m_body= dBodyCreate(0);
	m_island.AddBody(m_body);
	dMass m;
	dMassSetSphere(&m,1.f,1000000.f);
	dMassAdjust(&m,100000.f);
	dBodySetMass(m_body,&m);
	dBodySetGravityMode(m_body,0);
}

CPHCapture::~CPHCapture()
{

	Deactivate();
}
void CPHCapture::PhDataUpdate(dReal /**step/**/)
{
	if(b_failed) return;
	switch(e_state)
	{
	case cstPulling:  PullingUpdate();
		break;
	case cstCaptured: CapturedUpdate();
		break;
	case cstReleased: ReleasedUpdate();
		break;
	default: NODEFAULT;
	}
}

void CPHCapture::PhTune(dReal /**step/**/)
{
	if(b_failed) return;
	//if(!m_taget_object->PPhysicsShell())	{
	//	b_failed=true;
	//	return;			//. hack
	//}
	bool act_capturer=m_character->CPHObject::is_active();
	bool act_taget=m_taget_object->PPhysicsShell()->isEnabled();
	b_disabled=!act_capturer&&!act_taget;
	if(act_capturer)
	{
		m_taget_element->Enable();
	}
	if(act_taget)
	{
		m_character->Enable();
	}
	switch(e_state)
	{
	case cstPulling:  ;
		break;
	case cstCaptured:
		{
				if(b_disabled) dBodyDisable(m_body);
				else
				{
					m_character->Island().Merge(&m_island);
					m_taget_element->PhysicsShell()->PIsland()->Merge(&m_island);
				}
		}
		break;
	case cstReleased: ;
		break;
	default: NODEFAULT;
	}

}

void CPHCapture::PullingUpdate()
{
	if(!m_taget_element->isActive()||Device.dwTimeGlobal-m_time_start>m_capture_time)
	{
		Release();
		return;
	}

	Fvector dir;
	Fvector capture_bone_position;
	CObject* object=smart_cast<CObject*>(m_character->PhysicsRefObject());
	capture_bone_position.set(m_capture_bone->mTransform.c);
	object->XFORM().transform_tiny(capture_bone_position);
	m_taget_element->GetGlobalPositionDynamic(&dir);
	dir.sub(capture_bone_position,dir);
	float dist=dir.magnitude();
	if(dist>m_pull_distance)
	{
		Release();
		return;
	}
	dir.mul(1.f/dist);
	if(dist<m_capture_distance)
	{
		m_back_force=0.f;

		m_joint=dJointCreateBall(0,0);
		m_island.AddJoint(m_joint);
		m_ajoint=dJointCreateAMotor(0,0);
		m_island.AddJoint(m_ajoint);
		dJointSetAMotorMode (m_ajoint, dAMotorEuler);
		dJointSetAMotorNumAxes (m_ajoint, 3);

		CreateBody();
		dBodySetPosition(m_body,capture_bone_position.x,capture_bone_position.y,capture_bone_position.z);
		dJointAttach(m_joint,m_body,m_taget_element->get_body());
		dJointAttach(m_ajoint,m_body,m_taget_element->get_body());
		dJointSetFeedback (m_joint, &m_joint_feedback);
		dJointSetFeedback (m_ajoint, &m_joint_feedback);
		dJointSetBallAnchor(m_joint,capture_bone_position.x,capture_bone_position.y,capture_bone_position.z);

		dJointSetAMotorAxis (m_ajoint, 0, 1, dir.x, dir.y, dir.z);

		if(dir.x>EPS)
		{
			if(dir.y>EPS)
			{
				float mag=dir.x*dir.x+dir.y*dir.y;
				dJointSetAMotorAxis (m_ajoint, 2, 2, -dir.y/mag, dir.x/mag, 0.f);
			}
			else if(dir.z>EPS)
			{
				float mag=dir.x*dir.x+dir.z*dir.z;
				dJointSetAMotorAxis (m_ajoint, 2, 2, -dir.z/mag,0.f,dir.x/mag);
			}
			else
			{
				dJointSetAMotorAxis (m_ajoint, 2, 2, 1.f,0.f,0.f);
			}
		}
		else
		{
			if(dir.y>EPS)
			{

				if(dir.z>EPS)
				{
					float mag=dir.y*dir.y+dir.z*dir.z;
					dJointSetAMotorAxis (m_ajoint, 2, 2,0.f,-dir.z/mag,dir.y/mag);
				}
				else
				{
					dJointSetAMotorAxis (m_ajoint, 2, 2, 0.f,1.f,0.f);
				}
			}
			else
			{
				dJointSetAMotorAxis (m_ajoint, 2, 2, 0.f,0.f,1.f);
			}
		}
		//float hi=-M_PI/2.f,lo=-hi;
		//dJointSetAMotorParam(m_ajoint,dParamLoStop ,lo);
		//dJointSetAMotorParam(m_ajoint,dParamHiStop ,hi);
		//dJointSetAMotorParam(m_ajoint,dParamLoStop2 ,lo);
		//dJointSetAMotorParam(m_ajoint,dParamHiStop2 ,hi);
		//dJointSetAMotorParam(m_ajoint,dParamLoStop3 ,lo);
		//dJointSetAMotorParam(m_ajoint,dParamHiStop3 ,hi);

		dJointSetAMotorParam(m_ajoint,dParamFMax ,m_capture_force*0.2f);
		dJointSetAMotorParam(m_ajoint,dParamVel  ,0.f);

		dJointSetAMotorParam(m_ajoint,dParamFMax2 ,m_capture_force*0.2f);
		dJointSetAMotorParam(m_ajoint,dParamVel2  ,0.f);

		dJointSetAMotorParam(m_ajoint,dParamFMax3 ,m_capture_force*0.2f);
		dJointSetAMotorParam(m_ajoint,dParamVel3  ,0.f);

///////////////////////////////////
		float sf=0.1f,df=10.f;

		float erp=ERP(world_spring*sf,world_damping*df);
		float cfm=CFM(world_spring*sf,world_damping*df);
		dJointSetAMotorParam(m_ajoint,dParamStopERP ,erp);
		dJointSetAMotorParam(m_ajoint,dParamStopCFM ,cfm);

		dJointSetAMotorParam(m_ajoint,dParamStopERP2 ,erp);
		dJointSetAMotorParam(m_ajoint,dParamStopCFM2 ,cfm);

		dJointSetAMotorParam(m_ajoint,dParamStopERP3 ,erp);
		dJointSetAMotorParam(m_ajoint,dParamStopCFM3 ,cfm);
		/////////////////////////////////////////////////////////////////////
		///dJointSetAMotorParam(m_joint1,dParamFudgeFactor ,0.1f);
		//dJointSetAMotorParam(m_joint1,dParamFudgeFactor2 ,0.1f);
		//dJointSetAMotorParam(m_joint1,dParamFudgeFactor3 ,0.1f);
		/////////////////////////////////////////////////////////////////////////////
		sf=0.1f,df=10.f;
		erp=ERP(world_spring*sf,world_damping*df);
		cfm=CFM(world_spring*sf,world_damping*df);
		dJointSetAMotorParam(m_ajoint,dParamCFM ,cfm);
		dJointSetAMotorParam(m_ajoint,dParamCFM2 ,cfm);
		dJointSetAMotorParam(m_ajoint,dParamCFM3 ,cfm);

///////////////////////////

		//dJointSetAMotorParam(m_ajoint,dParamLoStop ,0.f);
		//dJointSetAMotorParam(m_ajoint,dParamHiStop ,0.f);

		m_taget_element->set_DynamicLimits();
		//m_taget_object->PPhysicsShell()->set_JointResistance()
		e_state=cstCaptured;
		return;
	}
	m_taget_element->applyForce(dir,m_pull_force);
}

void CPHCapture::CapturedUpdate()
{
	m_island.Unmerge();
	if(m_character->CPHObject::is_active())
	{
		m_taget_element->Enable();
	}

	if(!m_taget_element->isActive()||dDOT(m_joint_feedback.f2,m_joint_feedback.f2)>m_capture_force*m_capture_force)
	{
		Release();
		return;
	}

	float mag=dSqrt(dDOT(m_joint_feedback.f1,m_joint_feedback.f1));

	//m_back_force=m_back_force*0.999f+ ((mag<m_capture_force/5.f) ? mag : (m_capture_force/5.f))*0.001f;
	//
	if(b_character_feedback&&mag>m_capture_force/2.2f)
	{
		float f=mag/(m_capture_force/15.f);
		m_character->ApplyForce(m_joint_feedback.f1[0]/f,m_joint_feedback.f1[1]/f,m_joint_feedback.f1[2]/f);
	}

	Fvector capture_bone_position;
	CObject* object=smart_cast<CObject*>(m_character->PhysicsRefObject());
	capture_bone_position.set(m_capture_bone->mTransform.c);
	object->XFORM().transform_tiny(capture_bone_position);
	dBodySetPosition(m_body,capture_bone_position.x,capture_bone_position.y,capture_bone_position.z);
}

void CPHCapture::ReleasedUpdate()
{
	if(b_disabled) return;
	if(!b_collide)
	{
		b_failed=true;
		m_taget_element->Enable();
	}
	b_collide=false;
}

void CPHCapture::ReleaseInCallBack()
{
	//	if(!b_failed) return;
	b_collide=true;
}

void CPHCapture::object_contactCallbackFun(bool& do_colide,bool bo1,dContact& c,SGameMtl * /*material_1*/,SGameMtl * /*material_2*/)
{

	dxGeomUserData *l_pUD1 = NULL;
	dxGeomUserData *l_pUD2 = NULL;
	l_pUD1 = retrieveGeomUserData(c.geom.g1);
	l_pUD2 = retrieveGeomUserData(c.geom.g2);

	if(! l_pUD1) return;
	if(!l_pUD2) return;

	CEntityAlive* capturer=smart_cast<CEntityAlive*>(l_pUD1->ph_ref_object);
	if(capturer)
	{
		CPHCapture* capture=capturer->character_physics_support()->movement()->PHCapture();
		if(capture)
		{
			if(capture->m_taget_element->PhysicsRefObject()==l_pUD2->ph_ref_object)
			{
				do_colide = false;
				capture->m_taget_element->Enable();
				if(capture->e_state==CPHCapture::cstReleased) capture->ReleaseInCallBack();
			}

		}

	}

	capturer=smart_cast<CEntityAlive*>(l_pUD2->ph_ref_object);
	if(capturer)
	{
		CPHCapture* capture=capturer->character_physics_support()->movement()->PHCapture();
		if(capture)
		{
			if(capture->m_taget_element->PhysicsRefObject()==l_pUD1->ph_ref_object)
			{
				do_colide = false;
				capture->m_taget_element->Enable();
				if(capture->e_state==CPHCapture::cstReleased) capture->ReleaseInCallBack();
			}

		}

	}
}
void CPHCapture::net_Relcase(CObject* O)
{
	if(static_cast<CObject*>(m_taget_object)==O)
	{
		Deactivate();
	}
}


text:
<?php
namespace Faker\Tests\Writer;

use Faker\Project,
    Faker\Components\Writer\Encoding,
    Faker\Tests\Base\AbstractProject;

class EncodingTest extends AbstractProject
{

    public function testValidateEncoding()
    {
        $encoder = new Encoding('UTF-8','UTF-8');

        $this->assertTrue($encoder->validateEncoding());
    }

    /**
      *  Great if this threw an exception but the in encoding is ignored by mb_convert_encoding
      *  it will fall back to system default.
      */
    public function testEncodingBadIn()
    {
        $encoder = new Encoding('aaa','UTF-8');
    }

    /**
      *  @expectedException \Faker\Components\Writer\Exception
      *  @expectedExceptionMessage writer::__construct out encoding aaa OR in encoding UTF-8 is invalid
      */
    public function testEncodingBadOut()
    {
        $encoder = new Encoding('UTF-8','aaa');

    }

    public function testEncoding()
    {
        $encoder = new Encoding('ASCII','UTF-8');

        $out = $encoder->encode('my test ascii string');

        $this->assertTrue(mb_check_encoding($out,'UTF-8'));

    }

    public function testEncodingPropertites()
    {
        $encoder = new Encoding('UTF-8','UTF-8');

        $out = $encoder->setInEncoding('ascii')->encode('my test ascii string');

        $this->assertTrue(mb_check_encoding($out,'UTF-8'));

        $encoder = new Encoding('UTF-8','ASCII');

        $out = $encoder->setOutEncoding('ascii')->encode('my test ascii string');

        $this->assertTrue(mb_check_encoding($out,'ASCII'));

    }

}
/* End of File */


text:
/**
 * The central event bus for the application.
 *
 * You can subscribe to an event topic using
 *
 * ```javascript
 * require('app/event/bus').on('user:created', function(user) {
 *     alert('You created the user '+user.name);
 * });
 * ```
 *
 * and send events using
 * ```javascript
 * require('app/event/bus').emit('user:created', { name: 'jide.js' });
 * ```
 */
define(['jidejs/base/EventEmitter'], function(EventEmitter) {
    return new EventEmitter();
});


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>no node integration</title>
  </head>
  <body>
    no node integration
  </body>
</html>


text:
<!DOCTYPE html>

The word "PASS" should be seen below.

    SSPA


text:
package testutils

import (
	"testing"

	"github.com/apache/thrift/lib/go/thrift"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestNewZipkinThriftUDPClient(t *testing.T) {
	_, _, err := NewZipkinThriftUDPClient("1.2.3:0")
	assert.Error(t, err)

	_, cl, err := NewZipkinThriftUDPClient("127.0.0.1:12345")
	require.NoError(t, err)
	cl.Close()
}

func TestNewJaegerThriftUDPClient(t *testing.T) {
	compactFactory := thrift.NewTCompactProtocolFactory()

	_, _, err := NewJaegerThriftUDPClient("1.2.3:0", compactFactory)
	assert.Error(t, err)

	_, cl, err := NewJaegerThriftUDPClient("127.0.0.1:12345", compactFactory)
	require.NoError(t, err)
	cl.Close()
}


text:
import {Column, Entity, ManyToMany, PrimaryGeneratedColumn} from "../../../src/index";
import {PostCategory} from "./PostCategory";
import {PostAuthor} from "./PostAuthor";
import {ManyToOne} from "../../../src/decorator/relations/ManyToOne";
import {JoinTable} from "../../../src/decorator/relations/JoinTable";

@Entity("sample5_post")
export class Post {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    title: string;

    @Column()
    text: string;

    @ManyToOne(type => PostAuthor, post => post.posts, {
        cascade: true
    })
    author: PostAuthor;

    @ManyToMany(type => PostCategory, category => category.posts, {
        cascade: true
    })
    @JoinTable()
    categories: PostCategory[] = [];

}


text:
pypif.obj.common.scalar module
==============================

.. automodule:: pypif.obj.common.scalar
    :members:
    :undoc-members:
    :show-inheritance:


text:
$(function() {
	// Filters out any *real* keystroke that does not match the regex
	$('#roomURLInput').on('keypress', function (event) {
		var regex = new RegExp("[a-zA-Z0-9_]+");
		var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);

		if (!regex.test(key)) {
		   event.preventDefault();
		   return false;
		}
	});
	// Adds or removes error messages, depending on the contents of roomURLInput. Updated every key-press.
	$('#roomURLInput').on('input', function (event) {
		var string = $( "#roomURLInput" ).val();
		//If the field is blank, DON'T show an error. The user is probably still thinking of a name.
		if (string == "") {
			$("#URLInputError").text("");
		}
		else {
			var URLTestStatus = testURL(string);
			$("#URLInputError").text(URLTestStatus);
		}
	});
	//Do a final check when the user tries to submit the form.  If it fails, display the error and don't submit it.
	$('#optionsList').submit(function() {
		var string = $( "#roomURLInput" ).val();
        var URLTestStatus = testURL(string);
		if (URLTestStatus === "") {
			return true;
		} else if ($("#optionsList input[name='private']:checked").val() == 1) {
			return true;
		} else {
			$("#URLInputError").text(URLTestStatus);
			return false;
		}

    });
});

// Tests if a given URL String is a legitimate one. Returns "" if okay, otherwise it will return a description of the problem.
function testURL(urlString) {
	var status = "";
	var inactive = 0;
	if (!/^[a-zA-Z][\w]*$/.test(urlString)) {
		status = "Room URLs must begin with a letter.";
	}
	if (urlString.length == 32) {
		status = "Room URLs have a 32 character limit.";
	}
	if (urlString === "") {
		status = "Room URLs cannot be blank.";
	}
	return status;

};


text:
<!-- toc -->
- [Summary](#summary)
- [Motivation](#motivation)
  - [Goals](#goals)
- [Proposal](#proposal)
  - [Risks and Mitigations](#risks-and-mitigations)
- [Design Details](#design-details)
  - [Graduation Criteria](#graduation-criteria)
    - [Alpha](#alpha)
    - [Beta](#beta)
- [Production Readiness Review Questionnaire](#production-readiness-review-questionnaire)
  - [Feature Enablement and Rollback](#feature-enablement-and-rollback)
  - [Rollout, Upgrade and Rollback Planning](#rollout-upgrade-and-rollback-planning)
  - [Monitoring Requirements](#monitoring-requirements)
  - [Dependencies](#dependencies)
- [Implementation History](#implementation-history)
- [Drawbacks](#drawbacks)
- [Alternatives](#alternatives)
<!-- /toc -->

## Summary

*Note: This KEP is primarily for tracking purposes. The code for this feature is
all out-of-tree, but the using the k8s.io API group requires API review. Most
sections of this KEP will be marked as not applicable.*

This KEP aims to transition [Gateway API](https://gateway-api.sigs.k8s.io) from
an experimental API (x-k8s.io) to an official one (k8s.io) as part of the
v1alpha2 release. The APIs will continue to be represented as CRDs, but will be
subject to the standard [Kubernetes API review
process](https://github.com/kubernetes/community/blob/master/sig-architecture/api-review-process.md).

## Motivation

Although Gateway API started as an experimental API, we are preparing a v1alpha2
release that we believe will be a significant step towards stabilizing the API.
The number of [implementations of the
API](https://gateway-api.sigs.k8s.io/implementations/) continues to
grow, and we believe that transitioning to an official Kubernetes API will help
provide greater quality and stability going forward.

### Goals

* Formalize transition of Gateway API from x-k8s.io API group to k8s.io.
* Organize full Kubernetes API reviews as part of the transition.

## Proposal

This is a large API, it would not be practical to include it within this KEP.
Instead, the API review process will happen through a separate PR or set of PRs
on the [Gateway API repo](https://github.com/kubernetes-sigs/gateway-api).
Subproject maintainers will review PRs and API-changes on a per patch basis,
while upstream k8s api-reviewers will review API changes on a release by release
basis. In addition to this, subproject maintainers could involve k8s
api-reviewers on a case-by-case as needed.

### Risks and Mitigations

N/A

## Design Details

N/A

### Graduation Criteria

#### Alpha

- Approval from subproject owners + KEP reviewers

#### Beta

- v1alpha2 APIs are implemented by several implementations
- Approval from subproject owners + KEP reviewers
- Initial conformance tests are in place
- Validating webhook for advanced validation
- We know users of the API are deploying apps with this API and exercising most
  of the API surface

## Production Readiness Review Questionnaire

### Feature Enablement and Rollback

###### How can this feature be enabled / disabled in a live cluster?

N/A

###### Does enabling the feature change any default behavior?

No

###### Can the feature be disabled once it has been enabled (i.e. can we roll back the enablement)?

N/A

###### What happens if we reenable the feature if it was previously rolled back?

N/A

###### Are there any tests for feature enablement/disablement?

N/A

### Rollout, Upgrade and Rollback Planning

###### How can a rollout or rollback fail? Can it impact already running workloads?

N/A

###### What specific metrics should inform a rollback?

N/A

###### Were upgrade and rollback tested? Was the upgrade->downgrade->upgrade path tested?

N/A

###### Is the rollout accompanied by any deprecations and/or removals of features, APIs, fields of API types, flags, etc.?

No

### Monitoring Requirements

###### How can an operator determine if the feature is in use by workloads?

N/A

###### How can someone using this feature know that it is working for their instance?

N/A

###### What are the reasonable SLOs (Service Level Objectives) for the enhancement?

N/A

###### What are the SLIs (Service Level Indicators) an operator can use to determine the health of the service?

N/A

###### Are there any missing metrics that would be useful to have to improve observability of this feature?

N/A

### Dependencies

###### Does this feature depend on any specific services running in the cluster?

No

## Implementation History

* November 2020 - v1alpha1@0.1.0 released
* February 2021 - v1alpha1@0.2.0 released
* April 2021 - v1alpha1@0.3.0 released

## Drawbacks

Transitioning to a new API group will mean that resources in each group will be
entirely unique. If users have both new and old APIs installed, even a simple
operation like `kubectl get gateway` would only return results from one of the
installed API groups. This is unfortunate, but represents a reason to make this
change before the API becomes more stable and has a larger userbase.

## Alternatives

This API could stay as an experimental API indefinitely, but that would be very
confusing for users.


text:
using System;

namespace Archimedes.Patterns
{
    /// <summary>
    /// Provides static builder methods for optional wrappers
    /// </summary>
    public static class Optional
    {
        #region Static Builder

        /// <summary>
        /// Builds an optional with the given value, which must not be null
        /// </summary>
        /// <typeparam name="TN"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">Thrown if the value was null</exception>
        public static Optional<TN> Of<TN>(TN value)
        {
            if (value == null) throw new ArgumentNullException("value");
            return new Optional<TN>(value);
        }

        /// <summary>
        /// Builds an optional which has the given value if not null, or is empty otherwise.
        /// </summary>
        /// <typeparam name="TN"></typeparam>
        /// <param name="nullable"></param>
        /// <returns></returns>
        public static Optional<TN> OfNullable<TN>(TN nullable)
        {
            return nullable != null ? Of(nullable) : new Optional<TN>();
        }

        /// <summary>
        /// Returns a Optional which does not contain a value.
        /// </summary>
        /// <returns></returns>
        public static Optional<TN> Empty<TN>()
        {
            return new Optional<TN>();
        }

        #endregion
    }

    /// <summary>
    /// A immutable (thus thread save) container-object which may or may not contain a non-null value.
    ///
    /// If a value is present (not null), IsPresent will return true and Value will return the value.
    /// Invoking  the Value property causes an exception.
    ///
    /// Use the static builder methods to create instances of this class.
    ///
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public struct Optional<T>
    {
        #region Fields

        private readonly T _value;
        private readonly bool _hasValue;

        #endregion

        #region Internal Constructors

        /// <summary>
        /// Creates a new Optional - use the static builder functions
        /// </summary>
        /// <param name="value"></param>
        internal Optional(T value)
        {
            _value = value;
            _hasValue = true;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the value if available, otherwise throws <see cref="InvalidOperationException "/>
        /// </summary>
        /// <returns></returns>
        public T Value
        {
            get
            {
                if (!IsPresent) throw new InvalidOperationException("You invoked Value on an Optional<T> which values is NOT present. Use IsPresent to check or any of the 'OrElse' methods!");
                return _value;
            }
        }

        /// <summary>
        /// Checks if the value is present, i.e. the value is not null.
        /// Note that this does not guarantee that the value is NOT null!
        /// </summary>
        public bool IsPresent
        {
            get
            {
                return _hasValue && _value != null;
            }
        }

        #endregion

        #region Functional Programming

        /// <summary>
        /// Returns the value if available, or else the provided value as fall-back.
        /// </summary>
        /// <param name="elseValue"></param>
        /// <returns></returns>
        public T OrElse(T elseValue)
        {
            if (IsPresent) return Value;
            return elseValue;
        }

        /// <summary>
        /// Returns the value if available, or else the provided value as fall-back.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="elseProvider"></param>
        /// <returns></returns>
        public T OrElse(Func<T> elseProvider)
        {
            if (IsPresent) return Value;
            return elseProvider();
        }

        /// <summary>
        /// Returns the value if available, otherwise throws the provided exception
        /// </summary>
        /// <param name="elseProvider"></param>
        /// <returns></returns>
        public T OrElseThrow(Func<Exception> elseProvider)
        {
            if (IsPresent) return Value;
            throw elseProvider();
        }

        /// <summary>
        /// Returns the value if available, or else the default value of the type -
        /// Which is null for all classes, and empty/zero for all structures.
        /// </summary>
        /// <returns></returns>
        public T OrDefault()
        {
            if (IsPresent) return Value;
            return default(T);
        }

        /// <summary>
        /// Maps this value if present, using the given mapper function.
        /// Otherwise, an empty optional is returned.
        /// </summary>
        /// <typeparam name="TOut">The output type of the maping function</typeparam>
        /// <param name="mapper"></param>
        /// <returns></returns>
        public Optional<TOut> Map<TOut>(Func<T, TOut> mapper)
        {
            if (IsPresent)
            {
                return Optional.OfNullable(mapper(Value));
            }

            return Optional.Empty<TOut>();
        }

        /// <summary>
        /// If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional.
        /// This method is similar to Map(Function), but the provided mapper is one whose result is already an Optional.
        /// </summary>
        /// <typeparam name="TOut">The output type of the maping function</typeparam>
        /// <param name="mapper"></param>
        /// <returns></returns>
        public Optional<TOut> FlatMap<TOut>(Func<T, Optional<TOut>> mapper)
        {
            if (IsPresent)
            {
                return mapper(Value);
            }
            return Optional.Empty<TOut>();
        }

        /// <summary>
        /// If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public Optional<T> Filter(Predicate<T> predicate)
        {
            if (IsPresent)
            {
                if (predicate(Value))
                {
                    return this;
                }
            }
            return Optional.Empty<T>();
        }

        /// <summary>
        /// If a value is present, invoke the specified action with the value, otherwise do nothing.
        /// </summary>
        /// <param name="consumer"></param>
        public void IfPresent(Action<T> consumer)
        {
            if (IsPresent)
            {
                consumer(Value);
            }
        }

        /// <summary>
        /// Forces this optional to be casted
        /// </summary>
        /// <typeparam name="TNew"></typeparam>
        /// <returns></returns>
        public Optional<TNew> CastTo<TNew>()
        {
            return Map(val => (TNew)(object)val);
        }

        #endregion

        public override string ToString()
        {
            return IsPresent ? Value + "" : "{Empty-Optional}";
        }
    }
}


text:
Weapons::Weapons(GameLoop &game)
  : gameloop(game)
{
  this->fmap.clear();
  this->fmap[POUNCH] = &Weapons::pounch;
  this->fmap[FINGER] = &Weapons::finger;
  this->fmap[BASEBALL] = &Weapons::baseball;
  this->fmap[JUMPTHOUGHTWALL] = &Weapons::jumpThoughtWall;
  this->fmap[UZI] = &Weapons::uzi;
  this->fmap[SHOOTGUN] = &Weapons::shootgun;
  this->fmap[BAZOOKA] = &Weapons::bazooka;
  this->fmap[DYNAMIT] = &Weapons::dynamit;
  this->fmap[GRENADE] = &Weapons::grenade;
  this->fmap[DRILL] = &Weapons::drill;
}

Weapons::~Weapons()
{

}

bool Weapons::getCanUsWeapon() const
{
  return (this->_canUseWeapon);
}

void Weapons::setCanUseWeapon(bool can)
{
  this->_canUseWeapon = can;
}

void Weapons::attack()
{
  if (this->gameloop.getWormsPlayer() < 0 || this->gameloop.getWormsPlayer() >= this->gameloop.listPlayers.size())
    return;

  int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0];
  int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1];
  WeaponsType tmpWeaponType = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getWeaponsType();
  int nb_player = this->gameloop.getWormsPlayer();

  std::cout << "attack ! (type: " << tmpWeaponType << ") for player: " << nb_player << std::endl;

  (this->*fmap[tmpWeaponType])();
}

std::vector<int> Weapons::getIaHit(int x, int y, int nb_player, int right)
{
  if (nb_player < 0 || nb_player >= this->gameloop.listPlayers.size())
  {
    std::vector<int> tmpNull;
    return (tmpNull);
  }

  int idTeam = this->gameloop.listPlayers[nb_player][0];
  int idWorms = this->gameloop.listPlayers[nb_player][1];

  int x1;
  int x2;
  int y1 = y - (this->gameloop.getHeightWorms() * 2);
  int y2 = y + (this->gameloop.getHeightWorms() * 2);
  if (right == 1)
  {
    x1 = x + (this->gameloop.getWidthWorm() / 2);
    x2 = x + (this->gameloop.getWidthWorm() * 2);
  }
  else
  {
    x1 = x - (this->gameloop.getWidthWorm() * 2);
    x2 = x + (this->gameloop.getWidthWorm() / 2);
  }
  std::vector<int> allWormsTouch = this->gameloop.allWormsInBox(x1, y1, x2, y2);
  return (allWormsTouch);
}

bool Weapons::pounchHit(int damage, float velocity, int angle)
{
  if (this->gameloop.getWormsPlayer() < 0 || this->gameloop.getWormsPlayer() >= this->gameloop.listPlayers.size())
    return (false);

  int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0];
  int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1];

  int x1;
  int x2;
  int y1 = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y - (this->gameloop.getHeightWorms() * 2);
  int y2 = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y + (this->gameloop.getHeightWorms() * 2);
  if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT)
  {
    x1 = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x + (this->gameloop.getWidthWorm() / 2);
    x2 = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x + (this->gameloop.getWidthWorm() * 2);
  }
  else
  {
    x1 = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x - (this->gameloop.getWidthWorm() * 2);
    x2 = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x + (this->gameloop.getWidthWorm() / 2);
  }
  std::vector<int> allWormsTouch = this->gameloop.allWormsInBox(x1, y1, x2, y2);
  if (allWormsTouch.size() == 0)
    return (false);
  printList(allWormsTouch, " ");
  int i = 0;
  while (i < allWormsTouch.size())
  {
    std::cout << "to pounch: " << allWormsTouch[i] << std::endl;
    if (allWormsTouch[i] < 0 || allWormsTouch[i] >= this->gameloop.listPlayers.size())
    {
      ++i;
      continue;
    }
    int tmpIdTeam = this->gameloop.listPlayers[allWormsTouch[i]][0];
    int tmpIdWorms = this->gameloop.listPlayers[allWormsTouch[i]][1];
    if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT)
    {
      this->gameloop.getWormsFromGameLoop(tmpIdTeam, tmpIdWorms).setVelocity(velocity, 90 - angle);
      this->gameloop.getWormsFromGameLoop(tmpIdTeam, tmpIdWorms).takeDamage(damage);
    }
    else
    {
      this->gameloop.getWormsFromGameLoop(tmpIdTeam, tmpIdWorms).setVelocity(velocity, 90 + angle);
      this->gameloop.getWormsFromGameLoop(tmpIdTeam, tmpIdWorms).takeDamage(damage);
    }
    ++i;
  }
  return (true);
}

void Weapons::pounch()
{
  std::cout << "pounch !" << std::endl;
  if (!this->pounchHit(25, 15.0, 20))
    return;
  this->_canUseWeapon = false;
}

void Weapons::finger()
{
    std::cout << "finger !" << std::endl;
    if (!this->pounchHit(3, 10.0, 20))
      return;
    this->_canUseWeapon = false;
}

void Weapons::baseball()
{
    std::cout << "baseball !" << std::endl;
    if (!this->pounchHit(30, 27.0, 40))
      return;
    this->_canUseWeapon = false;
}

void Weapons::jumpThoughtWall()
{
  if (this->gameloop.getWormsPlayer() < 0 || this->gameloop.getWormsPlayer() >= this->gameloop.listPlayers.size())
    return;
  if (this->jumpi != JUMP_NONE)
  {
    std::cout << "FUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU" << std::endl;
    return;
  }

  int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0];
  int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1];

  std::cout << "mega jump !" << std::endl;
  float velocityJump = 30.0;
  int angleRightJump = 60.0;
  int angleLeftJump = 120.0;

  if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT)
    this->gameloop.getWormsFromGameLoop(idTeam, idWorms).setVelocity(velocityJump, angleRightJump);
  else
    this->gameloop.getWormsFromGameLoop(idTeam, idWorms).setVelocity(velocityJump, angleLeftJump);

  this->jumpi = JUMP_START;
  this->_canUseWeapon = false;
}

void Weapons::activeParachute()
{
  int nb_player = this->gameloop.getWormsPlayer();
  if (nb_player < 0 || nb_player >= this->gameloop.listPlayers.size())
  {
    std::cout << "active para what ??" << std::endl;
    return ;
  }
  if (this->jumpi == JUMP_FIST_FALL)
  {
    std::cout << "set parachute !" << std::endl;
    //TODO: change obj player to PARACHUTE

    this->jumpi = JUMP_FALL;
  }
  else if (this->jumpi == JUMP_NONE)
  {
    std::cout << "set normal !" << std::endl;
    //TODO: change obj player to NORMAL

  }
}

void Weapons::uzi()
{
  std::cout << "uzi !" << std::endl;
  this->numberAction = 0;
  this->numberMaxAction = 30;
  this->speed = 15;
  this->ray = 2;
  //this->_canUseWeapon = false;
}

void Weapons::drill()
{
  std::cout << "drill !" << std::endl;
  this->numberAction = 0;
  this->numberMaxAction = 20;
  this->speed = 5;
  this->ray = 5;
}

void Weapons::shootgun()
{
  std::cout << "shootgun !" << std::endl;
  this->numberAction = 0;
  this->numberMaxAction = 2;
  this->speed = 12;
  this->ray = 15;
  //this->_canUseWeapon = false;
}

void Weapons::setPosOfCursor()
{
  if (this->gameloop.getWormsPlayer() < 0 || this->gameloop.getWormsPlayer() >= this->gameloop.listPlayers.size())
    return;

    int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0];
    int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1];

  int x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x;
  int y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y;

  float xx = x;
  float yy = y;

  float vel = 50.0;
  //int angle =  this->gameloop._currentAngle;
  int angle = 0;
  if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT)
    angle = 90 - this->gameloop._tmpAngle;
  else
    angle = 90 + this->gameloop._tmpAngle;

  float xvel = cos(angle / 180.0 * M_PI) * vel;
  float yvel = - sin(angle / 180.0 * M_PI) * vel;
  xx += xvel;
  yy += yvel;

  std::cout << "pos of worms: " << x << ":" << y << std::endl;
  std::cout << "pos Cursor: " << xx << ":" << yy << std::endl;
  //x = (int)xx;
  //y = (int)yy;
  this->xPos = (int)xx;
  this->yPos = (int)yy;
  this->setPosCursor = true;
}

void Weapons::addAngleCursor(int add)
{
  if (this->gameloop.getWormsPlayer() < 0 || this->gameloop.getWormsPlayer() >= this->gameloop.listPlayers.size())
    return;
  int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0];
  int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1];
  add *= -1;
  this->gameloop._tmpAngle += add;
  if (this->gameloop._tmpAngle < 0)
    this->gameloop._tmpAngle = 0;
  else if (this->gameloop._tmpAngle > 180)
    this->gameloop._tmpAngle = 180;

  std::cout << "angle: " << this->gameloop._tmpAngle << std::endl;
  this->gameloop._aff_cursor = true;
  this->setPosOfCursor();
}

void Weapons::affWeaponCursor(bool aff)
{
  this->gameloop._aff_cursor = aff;
  if (this->gameloop.getWormsPlayer() < 0 || this->gameloop.getWormsPlayer() >= this->gameloop.listPlayers.size()
      || !aff || !this->getCanUsWeapon())
  {
    std::cout << "hide cursor" << std::endl;
    this->xPos = 2000;
    this->yPos = 2000;
    this->setPosCursor = true;
    return;
  }
  std::cout << "display cursor" << std::endl;
  int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0];
  int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1];
  this->setPosOfCursor();
}

void Weapons::bazooka()
{
  std::cout << "bazooka !" << std::endl;
  this->ray = 50;
}

void Weapons::dynamit()
{
  std::cout << "dynamit !" << std::endl;
  this->_canUseWeapon = false;
}

void Weapons::grenade()
{
  std::cout << "grenade !" << std::endl;
  this->_canUseWeapon = false;
}


text:
/**
 * Convenience module for all of the Enums that we use around the JVM.
 * TODO(jvilk): There are a number of other Enums scattered about the code that I should
 * put into this module.
 */
define(
  function() {
    "use strict";

    var Enum = {};

    /**
     * Maps colors to CSS classes for console text.
     */
    Enum.textColorClass = {
      WHITE : 'whiteConsoleText',
      RED : 'redConsoleText',
      YELLOW : 'yellowConsoleText'
    };

    /**
     * Input modes for our console.
     */
    Enum.consoleInputMode = {
      NONE : 0,
      BY_LINE : 1,
      BY_CHAR : 2
    };

    /**
     * Character codes for special characters.
     */
    Enum.controlCharacter = {
      LEFT : 37, //
      RIGHT : 39, //
      HOME : 36, //
      END : 35, //
      UP : 38, //
      DOWN : 40, //
      BACKSPACE : 8, //
      ENTER : 13, //
      TAB : 9 //
    };

    /**
     * Represents the ConstantPool tags from Table 4.3 in the JVM7 spec.
     */
    Enum.constantPoolTag = {
      CLASS : 7,
      FIELDREF : 9,
      METHODREF : 10,
      INTERFACEMETHODREF : 11,
      STRING : 8,
      INTEGER : 3,
      FLOAT : 4,
      LONG : 5,
      DOUBLE : 6,
      NAMEANDTYPE : 12,
      UTF8 : 1,
      METHODHANDLE : 15,
      METHODTYPE : 16,
      INVOKEDYNAMIC : 18
    };

    /**
     * See Table 5.1: Bytecode Behaviors for Method Handles
     */
    Enum.referenceKind = {
      GETFIELD : 1,
      GETSTATIC : 2,
      PUTFIELD : 3,
      PUTSTATIC : 4,
      INVOKEVIRTUAL : 5,
      INVOKESTATIC : 6,
      INVOKESPECIAL : 7,
      NEWINVOKESPECIAL : 8,
      INVOKEINTERFACE : 9
    };

    /**
     * Used around the code to represent all possible data types in the JVM.
     * PRIMITIVE is used inside the Java Array class specifically.
     * TODO(jvilk): This should probably be refactored out later for something more space efficient.
     */
    Enum.dataType = {
      INTEGER: "int",
      DOUBLE: "double",
      FLOAT: "float",
      CHAR: "char",
      SHORT: "short",
      BYTE: "byte",
      BOOLEAN: "boolean",
      LONG: "long",
      VOID: "void",
      OBJECT: "object",
      ARRAY: "array",
      PRIMITIVE: "primitive"
    };

    return Enum;
  }
);


text:
import {createSelector} from 'reselect';
import {getStackEditing, getCurrentStack} from '../stacks/selectors';

export function getServers(state) {
  return state.servers.map;
}

function mapStackServers({servers: serverIds}, servers) {
  return serverIds.reduce((map, id) => {
    map[id.toString()] = servers[id.toString()];
    return map;
  }, {});
}

export const getStackEditingServers = createSelector(
  [getStackEditing, getServers],
  mapStackServers
);

export const getCurrentStackServers = createSelector(
  [getCurrentStack, getServers],
  (stack, servers) => stack && mapStackServers(stack, servers)
);


text: package aerospike


text:
#include "logger_private.h"

#include <proton/logger.h>
#include <proton/error.h>

#include "fixed_string.h"
#include "memory.h"
#include "util.h"
#include "value_dump.h"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

static void pni_default_log_sink(intptr_t logger, pn_log_subsystem_t subsystem, pn_log_level_t severity, const char *message)
{
  fprintf(stderr, "[%p]:%5s:%5s:%s\n", (void *) logger, pn_logger_subsystem_name(subsystem), pn_logger_level_name(severity), message);
  fflush(stderr);
}

static pn_logger_t the_default_logger = {
  .sink = pni_default_log_sink,
  .sink_context = (intptr_t) &the_default_logger,
  .sub_mask = PN_SUBSYSTEM_ALL,
  .sev_mask = PN_LEVEL_CRITICAL
};

void pni_logger_init(pn_logger_t *logger)
{
  *logger = the_default_logger;
  logger->sink_context = (intptr_t) logger;
}

void pni_logger_fini(pn_logger_t *logger)
{
}

#define LOGLEVEL(x)   {sizeof(#x)-1, #x, PN_LEVEL_ ## x, PN_LEVEL_ ## x-1}
#define TRACE(x)      {sizeof(#x)-1, #x, PN_LEVEL_ ## x}
#define SPECIAL(x, y) {sizeof(#x)-1, #x, PN_LEVEL_NONE, PN_LEVEL_NONE, y}
typedef struct {
    uint8_t   strlen;
    const char str[11];
    uint16_t   level;
    uint16_t   plus_levels;
    void     (*special)(void);
} log_level;
static const log_level log_levels[] = {
  LOGLEVEL(ERROR),
  LOGLEVEL(WARNING),
  LOGLEVEL(INFO),
  LOGLEVEL(DEBUG),
  LOGLEVEL(TRACE),
  LOGLEVEL(ALL),
  TRACE(FRAME),
  TRACE(RAW),
  SPECIAL(MEMORY, pni_mem_setup_logging),
  {0, ""}
};

void pni_decode_log_env(const char *log_env, int *setmask)
{
  if (!log_env) return;

  for (int i = 0; log_env[i]; i++) {
    for (const log_level *level = &log_levels[0]; level->strlen; level++) {
      if (pn_strncasecmp(&log_env[i], level->str, level->strlen)==0) {
        *setmask |= level->level;
        i += level->strlen;
        if (log_env[i]=='+') {
          i++;
          *setmask |= level->plus_levels;
        }
        i--;
        if (level->special) level->special();
        break;
      }
    }
  }
}

void pni_init_default_logger(void)
{
  int sev_mask = 0;
  int sub_mask = 0;
  /* Back compatible environment settings */
  if (pn_env_bool("PN_TRACE_RAW")) { sev_mask |= PN_LEVEL_RAW; }
  if (pn_env_bool("PN_TRACE_FRM")) { sev_mask |= PN_LEVEL_FRAME; }

  /* These are close enough for obscure undocumented settings */
  if (pn_env_bool("PN_TRACE_DRV")) { sev_mask |= PN_LEVEL_TRACE | PN_LEVEL_DEBUG; }
  if (pn_env_bool("PN_TRACE_EVT")) { sev_mask |= PN_LEVEL_DEBUG; }

  /* Decode PN_LOG into logger settings */
  pni_decode_log_env(getenv("PN_LOG"), &sev_mask);

  the_default_logger.sev_mask = (pn_log_level_t) (the_default_logger.sev_mask | sev_mask);
  the_default_logger.sub_mask = (pn_log_subsystem_t) (the_default_logger.sub_mask | sub_mask);
}

void pni_fini_default_logger(void)
{
  pni_logger_fini(&the_default_logger);
}

const char *pn_logger_level_name(pn_log_level_t severity)
{
  if (severity==PN_LEVEL_ALL)     return "*ALL*";
  if (severity&PN_LEVEL_CRITICAL) return "CRITICAL";
  if (severity&PN_LEVEL_ERROR)    return "ERROR";
  if (severity&PN_LEVEL_WARNING)  return "WARNING";
  if (severity&PN_LEVEL_INFO)     return "INFO";
  if (severity&PN_LEVEL_DEBUG)    return "DEBUG";
  if (severity&PN_LEVEL_TRACE)    return "TRACE";
  if (severity&PN_LEVEL_FRAME)    return "FRAME";
  if (severity&PN_LEVEL_RAW)      return "RAW";
  return "UNKNOWN";
}

const char *pn_logger_subsystem_name(pn_log_subsystem_t subsystem)
{
  if (subsystem==PN_SUBSYSTEM_ALL)    return "*ALL*";
  if (subsystem&PN_SUBSYSTEM_MEMORY)  return "MEMORY";
  if (subsystem&PN_SUBSYSTEM_IO)      return "IO";
  if (subsystem&PN_SUBSYSTEM_EVENT)   return "EVENT";
  if (subsystem&PN_SUBSYSTEM_AMQP)    return "AMQP";
  if (subsystem&PN_SUBSYSTEM_SSL)     return "SSL";
  if (subsystem&PN_SUBSYSTEM_SASL)    return "SASL";
  if (subsystem&PN_SUBSYSTEM_BINDING) return "BINDING";
  return "UNKNOWN";
}

pn_logger_t *pn_default_logger(void)
{
  return &the_default_logger;
}

void pn_logger_set_mask(pn_logger_t *logger, uint16_t subsystem, uint16_t severity)
{
  logger->sev_mask = (pn_log_level_t) (logger->sev_mask | severity);
  logger->sub_mask = (pn_log_subsystem_t) (logger->sub_mask | subsystem);
}

void pn_logger_reset_mask(pn_logger_t *logger, uint16_t subsystem, uint16_t severity)
{
  logger->sev_mask = (pn_log_level_t) (logger->sev_mask & ~severity);
  logger->sub_mask = (pn_log_subsystem_t) (logger->sub_mask & ~subsystem);
}

void pn_logger_set_log_sink(pn_logger_t *logger, pn_log_sink_t sink, intptr_t sink_context)
{
  logger->sink = sink;
  logger->sink_context = sink_context;
}

pn_log_sink_t pn_logger_get_log_sink(pn_logger_t *logger)
{
  return logger->sink;
}

intptr_t pn_logger_get_log_sink_context(pn_logger_t *logger)
{
  return logger->sink_context;
}

void pni_logger_log_data(pn_logger_t *logger, pn_log_subsystem_t subsystem, pn_log_level_t severity, const char *msg, const char *bytes, size_t size)
{
  char buf[256];
  ssize_t n = pn_quote_data(buf, 256, bytes, size);
  if (n >= 0) {
    pn_logger_logf(logger, subsystem, severity, "%s: \"%s\"", msg, buf);
  } else if (n == PN_OVERFLOW) {
    pn_logger_logf(logger, subsystem, severity, "%s: \"%s\"... (truncated)", msg, buf);
  }
}

void pni_logger_log_raw(pn_logger_t *logger, pn_log_subsystem_t subsystem, pn_log_level_t severity, pn_buffer_t *output, size_t size)
{
  char buf[256];

  pn_bytes_t bytes = pn_buffer_bytes(output);
  const char *start = &bytes.start[bytes.size-size];
  for (unsigned i = 0; i < size; i+=16) {
    pn_fixed_string_t out = pn_fixed_string(buf, sizeof(buf));
    pn_fixed_string_addf(&out, "%04x/%04x: ", i, size);
    for (unsigned j = 0; j<16; j++) {
      if (i+j<size) {
        pn_fixed_string_addf(&out, "%02hhx ", start[i+j]);
      } else {
        pn_fixed_string_append(&out, pn_string_const("   ", 3));
      }
    }
    for (unsigned j = 0; j<16; j++) {
      if (i+j>size) break;
      char c = start[i+j];
      if (c>32) { // c is signed so the high bit set is negative
        pn_fixed_string_append(&out, pn_string_const(&c, 1));
      } else {
        pn_fixed_string_append(&out, STR_CONST(.));
      }
    }
    pn_fixed_string_terminate(&out);
    pni_logger_log(logger, subsystem, severity, buf);
  }
}

void pni_logger_log_msg_inspect(pn_logger_t *logger, pn_log_subsystem_t subsystem, pn_log_level_t severity, void* object, const char *fmt, ...) {
  va_list ap;
  char buf[1024];
  pn_fixed_string_t out = pn_fixed_string(buf, sizeof(buf));

  va_start(ap, fmt);
  pn_fixed_string_vaddf(&out, fmt, ap);
  va_end(ap);

  pn_finspect(object, &out);
  pn_fixed_string_terminate(&out);
  pni_logger_log(logger, subsystem, severity, buf);
}

void pni_logger_log_msg_frame(pn_logger_t *logger, pn_log_subsystem_t subsystem, pn_log_level_t severity, pn_bytes_t frame, const char *fmt, ...) {
  va_list ap;
  char buf[1024];
  pn_fixed_string_t output = pn_fixed_string(buf, sizeof(buf));

  va_start(ap, fmt);
  pn_fixed_string_vaddf(&output, fmt, ap);
  va_end(ap);

  size_t psize = pni_value_dump(frame, &output);
  pn_bytes_t payload = {.size=frame.size-psize, .start=frame.start+psize};
  if (payload.size>0) {
    pn_fixed_string_addf(&output, " (%zu) ", payload.size);
    pn_fixed_string_quote(&output, payload.start, payload.size);
  }
  if (output.position==output.size) {
    // Message overflow
    const char truncated[] = " ... (truncated)";
    output.position -= sizeof(truncated);
    pn_fixed_string_append(&output, pn_string_const(truncated, sizeof(truncated)));
  }
  pn_fixed_string_terminate(&output);
  pni_logger_log(logger, subsystem, severity, buf);
}

void pni_logger_log(pn_logger_t *logger, pn_log_subsystem_t subsystem, pn_log_level_t severity, const char *message)
{
  assert(logger);
  logger->sink(logger->sink_context, subsystem, severity, message);
}

void pni_logger_vlogf(pn_logger_t *logger, pn_log_subsystem_t subsystem, pn_log_level_t severity, const char *fmt, va_list ap)
{
  assert(logger);
  char buf[1024];
  pn_fixed_string_t output = pn_fixed_string(buf, sizeof(buf));
  pn_fixed_string_vaddf(&output, fmt, ap);
  if (output.position==output.size) {
    // Message overflow
    const char truncated[] = " ... (truncated)";
    output.position -= sizeof(truncated);
    pn_fixed_string_append(&output, pn_string_const(truncated, sizeof(truncated)));
  }
  pn_fixed_string_terminate(&output);
  pni_logger_log(logger, subsystem, severity, buf);
}

void pn_logger_logf(pn_logger_t *logger, pn_log_subsystem_t subsystem, pn_log_level_t severity, const char *fmt, ...)
{
  va_list ap;

  va_start(ap, fmt);
  pni_logger_vlogf(logger, subsystem, severity, fmt, ap);
  va_end(ap);
}