text:
@interface UITableViewCell (config)

- (void)configCellWithNTAlbum:(NTAlbum *)album;

@end

@implementation AlbumTableDataSource

- (instancetype)init
{
    if (self = [super init]) {
        _dataSource = [[NSMutableArray alloc] init];
    }

    return self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_IDENTIFIER];

    NTAlbum *album = [[AssetParseEngine sharedEngine] getPosterImageFromAssetGroup:_dataSource[indexPath.row]];
    [cell configCellWithNTAlbum:album];

    return cell;

}

@end

@implementation UITableViewCell (config)

- (void)configCellWithNTAlbum:(NTAlbum *)album
{
    self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    [self.imageView setImage:album.poster];
    self.textLabel.text = [NSString stringWithFormat:@"%@(%lu)",album.albumName,(unsigned long)album.count];
}

@end


text:
(function() {
    'use strict';

    angular.module('playlistApp.RootController', [])
        .controller('RootController', ['$scope', 'UiState', function($scope, UiState) {

            init();

            function init(){
                $scope.menuOpen = UiState.isMenuOpen();

                UiState.listenMenuToggle(function(){
                    $scope.menuOpen = UiState.isMenuOpen();
                });
            }
        }]);
})();

redpajama_set_name: RedPajamaGithub


text:
package MiscUtils.Handlers;

import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.IChatComponent;

public class ChatMessageHandler {

    public static void iCommandSenderReply(ICommandSender player, String message) {
        sendChatToPlayer((EntityPlayer)player, message);
    }

    public static IChatComponent createChatComponent(String message) {
        ChatComponentText component = new ChatComponentText(message);
        return component;
    }

    public static void sendChatToPlayer(EntityPlayer player, String message) {
        player.addChatComponentMessage(createChatComponent(message));
    }

    public static void broadcastMessageToPlayers(String message){
        MinecraftServer.getServer().getConfigurationManager().sendChatMsg(createChatComponent(message));
    }
}


text:
<?php

/**
 * Retrieves an instance of CMB2_Option based on the option key
 */
class CMB2_Options {
	/**
	 * Array of all CMB2_Option instances
	 * @var   array
	 * @since 1.0.0
	 */
	protected static $option_sets = array();

	public static function get( $option_key ) {

		if ( empty( self::$option_sets ) || empty( self::$option_sets[ $option_key ] ) ) {
			self::$option_sets[ $option_key ] = new CMB2_Option( $option_key );
		}

		return self::$option_sets[ $option_key ];
	}
}

/**
 * Handles getting/setting of values to an option array
 * for a specific option key
 */
class CMB2_Option {

	/**
	 * Options array
	 * @var array
	 */
	protected $options = array();

	/**
	 * Current option key
	 * @var string
	 */
	protected $key = '';

	/**
	 * Initiate option object
	 * @since 2.0.0
	 */
	public function __construct( $option_key ) {
		$this->key = $option_key;
	}

	/**
	 * Delete the option from the db
	 * @since  2.0.0
	 * @return bool  Delete success or failure
	 */
	public function delete_option() {
		$this->options = delete_option( $this->key );
		return $this->options;
	}

	/**
	 * Removes an option from an option array
	 * @since  1.0.1
	 * @param  string  $field_id Option array field key
	 * @return array             Modified options
	 */
	public function remove( $field_id, $resave = false ) {

		$this->get_options();

		if ( isset( $this->options[ $field_id ] ) ) {
			unset( $this->options[ $field_id ] );
		}

		if ( $resave ) {
			$this->set();
		}

		return $this->options;
	}

	/**
	 * Retrieves an option from an option array
	 * @since  1.0.1
	 * @param  string  $field_id Option array field key
	 * @param  mixed   $default  Fallback value for the option
	 * @return array             Requested field or default
	 */
	function get( $field_id, $default = false ) {
		$opts = $this->get_options();

		if ( 'all' == $field_id ) {
			return $opts;
		} elseif ( array_key_exists( $field_id, $opts ) ) {
			return false !== $opts[ $field_id ] ? $opts[ $field_id ] : $default;
		}

		return $default;
	}

	/**
	 * Updates Option data
	 * @since  1.0.1
	 * @param  string  $field_id   Option array field key
	 * @param  mixed   $value      Value to update data with
	 * @param  bool    $resave     Whether to re-save the data
	 * @param  bool    $single     Whether data should not be an array
	 * @return boolean             Return status of update
	 */
	function update( $field_id, $value = '', $resave = false, $single = true ) {
		$this->get_options();

		if ( true !== $field_id ) {

			if ( ! $single ) {
				// If multiple, add to array
				$this->options[ $field_id ][] = $value;
			} else {
				$this->options[ $field_id ] = $value;
			}

		}

		if ( $resave || true === $field_id ) {
			return $this->set();
		}

		return true;
	}

	/**
	 * Saves the option array
	 * Needs to be run after finished using remove/update_option
	 * @uses apply_filters() Calls 'cmb2_override_option_save_{$this->key}' hook
	 * to allow overwriting the option value to be stored.
	 *
	 * @since  1.0.1
	 * @param  array $options Optional options to override
	 * @return bool           Success/Failure
	 */
	function set( $options = array() ) {
		$this->options = ! empty( $options ) ? $options : $this->options;

		$test_save = apply_filters( "cmb2_override_option_save_{$this->key}", 'cmb2_no_override_option_save', $this->options, $this );

		if ( 'cmb2_no_override_option_save' !== $test_save ) {
			return $test_save;
		}

		// If no override, update the option
		return update_option( $this->key, $this->options );
	}

	/**
	 * Retrieve option value based on name of option.
	 * @uses apply_filters() Calls 'cmb2_override_option_get_{$this->key}' hook to allow
	 * 	overwriting the option value to be retrieved.
	 *
	 * @since  1.0.1
	 * @param  mixed $default Optional. Default value to return if the option does not exist.
	 * @return mixed          Value set for the option.
	 */
	function get_options( $default = null ) {
		if ( empty( $this->options ) ) {

			$test_get = apply_filters( "cmb2_override_option_get_{$this->key}", 'cmb2_no_override_option_get', $default, $this );

			if ( 'cmb2_no_override_option_get' !== $test_get ) {
				$this->options = $test_get;
			} else {
				// If no override, get the option
				$this->options = get_option( $this->key, $default );
			}
		}

		return (array) $this->options;
	}

}


text:
#!/usr/bin/env node
// ////////////////////////////////////////////////////////
// System checks

if (+process.version.replace('v', '').split('.')[0] < 8) {
    // eslint-disable-next-line no-console
    throw console.error('\n\x1B[1;31mYou need to upgrade to NodeJS 8 to run this application!\x1B[0m');
}

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

require('../util/global.js');

const pkg = global.SmartNode.require('package.json');

const Logger = global.SmartNode.require('classes/Log.class');
const masterlogger = new Logger('master');

console.log(''); // eslint-disable-line no-console

const cli = require('cli');
const cluster = require('cluster');

cli.enable('version');
cli.setApp('bin/server.js', pkg.version);

const cliOptions = cli.parse({
    port: ['p', 'Websocket port to use instead of autodiscover', 'int', null],
    web: ['w', 'Port for the website to use', 'int', null],
    nobonjour: [false, 'Disable bonjour to let clients connect by the server address', 'bool', false],
    disableRestart: [false, 'Disable auto-restart of server if it crashes', 'bool', false],
    restartDelay: [false, 'How long the restart should be delayed after exit', 'int', 1000],
    maxRestarts: [false, 'Maximum number of automatic restarts before it should stop - set to -1 to disable', 'int', 5],
});

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

if (cluster.isMaster) {
    let restartCount = 0;
    let forcedRestart = false;
    let forcedExit = false;

    // eslint-disable-next-line global-require
    if (process.title === 'npm' && require('os').type().includes('Windows')) {
        masterlogger.warn(`If you want to see the fontend, you'll need to run
            "npm run watch-scss" as well to compile CSS!`);
        console.log(''); // eslint-disable-line no-console
    }

    // ////////////////////////////////////////////////////////
    masterlogger.info(`Master server process is running with ID ${process.pid}`);

    let child = cluster.fork();

    cluster.on('exit', (worker) => {
        if (forcedExit) return;

        if (forcedRestart) {
            child = restartChild();
            forcedRestart = false;
            restartCount = 0;
        } else {
            masterlogger.warn(`Child with ID ${worker.process.pid} exited`);

            if (!cliOptions.disableRestart &&
                (
                    cliOptions.maxRestarts === -1 ||
                    cliOptions.maxRestarts > restartCount
                )
            ) {
                setTimeout(() => {
                    child = restartChild();
                }, cliOptions.restartDelay);

                restartCount++;
            } else {
                masterlogger.warn('Maximum numbers of automatic restarts reached. Exiting.');
                process.exit(1);
            }
        }
    });

    process.stdin.resume();
    process.stdin.setEncoding('utf8');
    process.stdin.on('data', (data) => {
        if ((`${data}`).trim().toLowerCase() === 'rs') {
            masterlogger.info('Restarting server process NOW!');
            child.send('close');
            forcedRestart = true;
        }
    });

    process.on('SIGINT', () => {
        masterlogger.warn('SIGINT caught!!');
        child.send('close');
        forcedExit = true;
    });
} else {
    const logger = new Logger('child');

    logger.info(`Child process started with ID ${process.pid}`);

    const SmartNodeServer = new (global.SmartNode.require('classes/Server.class.js'))(() => {
        SmartNodeServer
            .init(cliOptions)
            .catch((e) => { logger.error('Server init error', e); });
    });

    // do something when app is closing
    process.on('message', (msg) => {
        if (msg === 'close') {
            exitHandler.call([SmartNodeServer, logger]);
        }
    });
    process.on('exit', exitHandler.bind([SmartNodeServer, logger]));
    process.on('SIGINT', exitHandler.bind([SmartNodeServer, logger]));
    process.on('uncaughtException', exitHandler.bind([SmartNodeServer, logger]));
}

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

function restartChild() {
    return cluster.fork();
}

/**
 * exit handler for cleanup and stuff
 *
 * @author Julian Kern <mail@juliankern.com>
 *
 * @param  {object} err Holding the error messages
 */
function exitHandler(err) {
    const [SmartNodeServer, logger] = this;
    logger.info('SmartNode exiting...');

    if (err) {
        logger.error('System error!', err);
    }

    SmartNodeServer.close(process.exit);
}


text:
%
% Replaces model parameters (from a vector) into a the class
% Used for optimizing a parse to an image
%
% Replaces variables:
%  image blur and pixel noise
%  stroke position, scale, and shape
%
% Requirements:
%  shapes_type should be empty, so we can marginalize over it
%
function vec_to_model_fit_type(theta,M,list_sid)

    if ~exist('list_sid','var')
       list_sid = 1:M.ns;
    end

    % Criteria for use
    for i=list_sid
       assert(isempty(M.S{i}.shapes_type));
    end

    count = 1;

    % pixel noise
    M.epsilon = theta(count);
    count = count + 1;

    % image blur
    M.blur_sigma = theta(count);
    count = count + 1;

    for i=list_sid

        % stroke position
        x = count:count+1;
        M.S{i}.pos_token = vec(theta(x))';
        count = count + 2;

        % sub-stroke shapes
        nn = numel(M.S{i}.shapes_token);
        x = count:count+nn-1;
        M.S{i}.shapes_token = reshape(theta(x),size(M.S{i}.shapes_token));
        count = count + nn;

        % sub-stroke scales (type)
        nn = numel(M.S{i}.invscales_type);
        x = count:count+nn-1;
        M.S{i}.invscales_type = reshape(theta(x),size(M.S{i}.invscales_type));
        count = count + nn;

        % sub-stroke scales (token)
        nn = numel(M.S{i}.invscales_token);
        x = count:count+nn-1;
        M.S{i}.invscales_token = reshape(theta(x),size(M.S{i}.invscales_token));
        count = count + nn;

    end

end


text:
namespace bp = boost::python;

void register_ObjectProperty_class(){

    { //::osgDB::ObjectProperty
        typedef bp::class_< osgDB::ObjectProperty > ObjectProperty_exposer_t;
        ObjectProperty_exposer_t ObjectProperty_exposer = ObjectProperty_exposer_t( "ObjectProperty", bp::init< >() );
        bp::scope ObjectProperty_scope( ObjectProperty_exposer );
        ObjectProperty_exposer.def( bp::init< char const *, bp::optional< int, bool > >(( bp::arg("name"), bp::arg("value")=(int)(0), bp::arg("useMap")=(bool)(false) )) );
        bp::implicitly_convertible< char const *, osgDB::ObjectProperty >();
        ObjectProperty_exposer.def( bp::init< osgDB::ObjectProperty const & >(( bp::arg("copy") )) );
        { //::osgDB::ObjectProperty::get

            typedef int ( ::osgDB::ObjectProperty::*get_function_type)(  ) const;

            ObjectProperty_exposer.def(
                "get"
                , get_function_type( &::osgDB::ObjectProperty::get ) );

        }
        { //::osgDB::ObjectProperty::operator()

            typedef ::osgDB::ObjectProperty & ( ::osgDB::ObjectProperty::*__call___function_type)( char const * ) ;

            ObjectProperty_exposer.def(
                "__call__"
                , __call___function_type( &::osgDB::ObjectProperty::operator() )
                , ( bp::arg("name") )
                , bp::return_self< >() );

        }
        { //::osgDB::ObjectProperty::set

            typedef void ( ::osgDB::ObjectProperty::*set_function_type)( int ) ;

            ObjectProperty_exposer.def(
                "set"
                , set_function_type( &::osgDB::ObjectProperty::set )
                , ( bp::arg("v") ) );

        }
        ObjectProperty_exposer.def_readwrite( "_mapProperty", &osgDB::ObjectProperty::_mapProperty );
        ObjectProperty_exposer.def_readwrite( "_name", &osgDB::ObjectProperty::_name );
        ObjectProperty_exposer.def_readwrite( "_value", &osgDB::ObjectProperty::_value );
    }

}


text:
Docker files and config for my ingress web server at home. Built on top of https://github.com/sdhibit/docker-rpi-raspbian and is for the ARMv7 processor - specifically, a Raspberry Pi3.

## Build like (--no-cache if you want updated apt-get)
`docker build -t amaurer/ingress_web_server:x.x .`

## Run like...
`docker run -d --restart=always -p 80:80 -p 443:443 -v /etc/ssl/certs/web/:/etc/ssl/certs/web/ -v /home/pi/ingress_web_server/logs/:/var/log/nginx/ -v /home/pi/ingress_web_server/fileserve/:/usr/share/nginx/html/fileserve/ --name ingress_web amaurer/ingress_web_server:x.x`

OR

`docker-compose up`


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MD_Dark" parent="Theme.AppCompat.Dialog.Alert">
        <item name="android:windowMinWidthMajor">@dimen/abc_dialog_min_width_major</item>
        <item name="android:windowMinWidthMinor">@dimen/abc_dialog_min_width_minor</item>

        <item name="md_divider">@color/md_divider_white</item>
        <item name="md_list_selector">?android:selectableItemBackground</item>
        <item name="md_btn_stacked_selector">?android:selectableItemBackground</item>
        <item name="md_btn_positive_selector">@drawable/md_btn_selector_ripple_dark</item>
        <item name="md_btn_neutral_selector">@drawable/md_btn_selector_ripple_dark</item>
        <item name="md_btn_negative_selector">@drawable/md_btn_selector_ripple_dark</item>
    </style>
    <style name="MD_Light" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="android:windowMinWidthMajor">@dimen/abc_dialog_min_width_major</item>
        <item name="android:windowMinWidthMinor">@dimen/abc_dialog_min_width_minor</item>

        <item name="md_divider">@color/md_divider_black</item>
        <item name="md_list_selector">?android:selectableItemBackground</item>
        <item name="md_btn_stacked_selector">?android:selectableItemBackground</item>
        <item name="md_btn_positive_selector">@drawable/md_btn_selector_ripple</item>
        <item name="md_btn_neutral_selector">@drawable/md_btn_selector_ripple</item>
        <item name="md_btn_negative_selector">@drawable/md_btn_selector_ripple</item>
    </style>
</resources>


text:
Vous avez écrit une réponse à ce post ?

Faites-moi connaître l'URL :

        <form action="https://webmention.herokuapp.com/api/webmention" method="post">
            <input name="source" type="url" placeholder="http://exemple.com/mon-post-cool">
            <input name="target" value="http://christopheducamp.com/2017/07/25/100-days-of-code/" type="hidden">
            <input class="btn btn-primary" role="button" value="Envoyer l'URL" type="submit">
        </form>


text:
package com.xmomen.module.order.model;

import java.io.Serializable;
import java.math.BigDecimal;

/**
 * Created by Jeng on 2016/4/25.
 */
public class OrderPurchaseModel implements Serializable {

    private String orderNo;
    private Integer itemId;
    private String itemCode;
    private String itemUnit;
    private BigDecimal totalItemQty;
    private BigDecimal totalWeight;

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

    public Integer getItemId() {
        return itemId;
    }

    public void setItemId(Integer itemId) {
        this.itemId = itemId;
    }

    public String getItemCode() {
        return itemCode;
    }

    public void setItemCode(String itemCode) {
        this.itemCode = itemCode;
    }

    public String getItemUnit() {
        return itemUnit;
    }

    public void setItemUnit(String itemUnit) {
        this.itemUnit = itemUnit;
    }

    public BigDecimal getTotalItemQty() {
        return totalItemQty;
    }

    public void setTotalItemQty(BigDecimal totalItemQty) {
        this.totalItemQty = totalItemQty;
    }

    public BigDecimal getTotalWeight() {
        return totalWeight;
    }

    public void setTotalWeight(BigDecimal totalWeight) {
        this.totalWeight = totalWeight;
    }
}


text:
<?php

namespace Intacct\Functions\Common\Query\Comparison\LessThan;

/**
 * @coversDefaultClass \Intacct\Functions\Common\Query\Comparison\LessThan\LessThanFloat
 */
class LessThanFloatTest extends \PHPUnit\Framework\TestCase
{

    public function testToString(): void
    {
        $condition = new LessThanFloat();
        $condition->setField('AMOUNTDUE');
        $condition->setValue(123.45);

        $expected = "AMOUNTDUE < 123.45";

        $this->assertEquals($expected, (string)$condition);
    }

    public function testToStringNot(): void
    {
        $condition = new LessThanFloat();
        $condition->setField('AMOUNTDUE');
        $condition->setValue(123.45);
        $condition->setNegate(true);

        $expected = "NOT AMOUNTDUE < 123.45";

        $this->assertEquals($expected, (string)$condition);
    }
}


text:
#ifndef FIRESTORE_CORE_SRC_MODEL_TYPES_H_
#define FIRESTORE_CORE_SRC_MODEL_TYPES_H_

#include <cstdint>

namespace firebase {
namespace firestore {
namespace model {

/**
 * BatchId is a locally assigned identifier for a batch of mutations that have
 * been applied by the user but have not yet been fully committed at the server.
 */
using BatchId = int32_t;

/**
 * A sequence number that's incremented on each "interesting" action in the
 * local store that establishes the order in which items can be garbage
 * collected.
 */
using ListenSequenceNumber = int64_t;

/**
 * TargetId is a stable numeric identifier assigned for a specific query
 * applied.
 */
using TargetId = int32_t;

/**
 * Describes the online state of the Firestore client. Note that this does not
 * indicate whether or not the remote store is trying to connect or not. This is
 * primarily used by the View / EventManager code to change their behavior while
 * offline (e.g. get() calls shouldn't wait for data from the server and
 * snapshot events should set metadata.from_cache() to true).
 */
enum class OnlineState {
  /**
   * The Firestore client is in an unknown online state. This means the client
   * is either not actively trying to establish a connection or it is currently
   * trying to establish a connection, but it has not succeeded or failed yet.
   * Higher-level components should not operate in offline mode.
   */
  Unknown,

  /**
   * The client is connected and the connections are healthy. This state is
   * reached after a successful connection and there has been at least one
   * successful message received from the backends.
   */
  Online,

  /**
   * The client is either trying to establish a connection but failing, or it
   * has been explicitly marked offline via a call to `DisableNetwork`.
   * Higher-level components should operate in offline mode.
   */
  Offline
};

}  // namespace model
}  // namespace firestore
}  // namespace firebase

#endif  // FIRESTORE_CORE_SRC_MODEL_TYPES_H_


text:
package alluxio.master.metastore;

import alluxio.master.file.meta.EdgeEntry;
import alluxio.master.file.meta.Inode;
import alluxio.master.file.meta.InodeDirectoryView;
import alluxio.master.file.meta.MutableInode;

import com.google.common.annotations.VisibleForTesting;

import java.io.Closeable;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;

/**
 * Read-only access to the inode store.
 */
public interface ReadOnlyInodeStore extends Closeable {
  /**
   * @param id an inode id
   * @param option the options
   * @return the inode with the given id, if it exists
   */
  Optional<Inode> get(long id, ReadOption option);

  /**
   * @param id an inode id
   * @return the result of {@link #get(long, ReadOption)} with default option
   */
  default Optional<Inode> get(long id) {
    return get(id, ReadOption.defaults());
  }

  /**
   * Returns an iterable for the ids of the children of the given directory.
   *
   * @param inodeId an inode id to list child ids for
   * @param option the options
   * @return the child ids iterable
   */
  Iterable<Long> getChildIds(Long inodeId, ReadOption option);

  /**
   * @param inodeId an inode id to list child ids for
   * @return the result of {@link #getChildIds(Long, ReadOption)} with default option
   */
  default Iterable<Long> getChildIds(Long inodeId) {
    return getChildIds(inodeId, ReadOption.defaults());
  }

  /**
   * Returns an iterable for the ids of the children of the given directory.
   *
   * @param inode the inode to list child ids for
   * @param option the options
   * @return the child ids iterable
   */
  default Iterable<Long> getChildIds(InodeDirectoryView inode, ReadOption option) {
    return getChildIds(inode.getId(), option);
  }

  /**
   * @param inode the inode to list child ids for
   * @return the result of {@link #getChildIds(InodeDirectoryView, ReadOption)} with default option
   */
  default Iterable<Long> getChildIds(InodeDirectoryView inode) {
    return getChildIds(inode, ReadOption.defaults());
  }

  /**
   * Returns an iterator over the children of the specified inode.
   *
   * The iterator is weakly consistent. It can operate in the presence of concurrent modification,
   * but it is undefined whether concurrently removed inodes will be excluded or whether
   * concurrently added inodes will be included.
   *
   * @param inodeId an inode id
   * @param option the options
   * @return an iterable over the children of the inode with the given id
   */
  default Iterable<? extends Inode> getChildren(Long inodeId, ReadOption option) {
    return () -> {
      Iterator<Long> it = getChildIds(inodeId, option).iterator();
      return new Iterator<Inode>() {
        private Inode mNext = null;

        @Override
        public boolean hasNext() {
          advance();
          return mNext != null;
        }

        @Override
        public Inode next() {
          if (!hasNext()) {
            throw new NoSuchElementException(
                "No more children in iterator for inode id " + inodeId);
          }
          Inode next = mNext;
          mNext = null;
          return next;
        }

        void advance() {
          while (mNext == null && it.hasNext()) {
            Long nextId = it.next();
            // Make sure the inode metadata still exists
            Optional<Inode> nextInode = get(nextId, option);
            if (nextInode.isPresent()) {
              mNext = nextInode.get();
            }
          }
        }
      };
    };
  }

  /**
   * @param inodeId an inode id
   * @return the result of {@link #getChildren(Long, ReadOption)} with default option
   */
  default Iterable<? extends Inode> getChildren(Long inodeId) {
    return getChildren(inodeId, ReadOption.defaults());
  }

  /**
   * @param inode an inode directory
   * @param option the options
   * @return an iterable over the children of the inode with the given id
   */
  default Iterable<? extends Inode> getChildren(InodeDirectoryView inode, ReadOption option) {
    return getChildren(inode.getId(), option);
  }

  /**
   * @param inode an inode directory
   * @return the result of {@link #getChildren(InodeDirectoryView, ReadOption)} with default option
   */
  default Iterable<? extends Inode> getChildren(InodeDirectoryView inode) {
    return getChildren(inode.getId(), ReadOption.defaults());
  }

  /**
   * @param inodeId an inode id
   * @param name an inode name
   * @param option the options
   * @return the id of the child of the inode with the given name
   */
  Optional<Long> getChildId(Long inodeId, String name, ReadOption option);

  /**
   * @param inodeId an inode id
   * @param name an inode name
   * @return the result of {@link #getChildId(Long, String, ReadOption)} with default option
   */
  default Optional<Long> getChildId(Long inodeId, String name) {
    return getChildId(inodeId, name, ReadOption.defaults());
  }

  /**
   * @param inode an inode directory
   * @param name an inode name
   * @param option the options
   * @return the id of the child of the inode with the given name
   */
  default Optional<Long> getChildId(InodeDirectoryView inode, String name, ReadOption option) {
    return getChildId(inode.getId(), name, option);
  }

  /**
   * @param inode an inode directory
   * @param name an inode name
   * @return the result of {@link #getChildId(InodeDirectoryView, String, ReadOption)} with default
   *    option
   */
  default Optional<Long> getChildId(InodeDirectoryView inode, String name) {
    return getChildId(inode.getId(), name, ReadOption.defaults());
  }

  /**
   * @param inodeId an inode id
   * @param name an inode name
   * @param option the options
   * @return the child of the inode with the given name
   */
  Optional<Inode> getChild(Long inodeId, String name, ReadOption option);

  /**
   * @param inodeId an inode id
   * @param name an inode name
   * @return the result of {@link #getChild(Long, String, ReadOption)} with default option
   */
  default Optional<Inode> getChild(Long inodeId, String name) {
    return getChild(inodeId, name, ReadOption.defaults());
  }

  /**
   * @param inode an inode directory
   * @param name an inode name
   * @param option the options
   * @return the child of the inode with the given name
   */
  default Optional<Inode> getChild(InodeDirectoryView inode, String name, ReadOption option) {
    return getChild(inode.getId(), name, option);
  }

  /**
   * @param inode an inode directory
   * @param name an inode name
   * @return the result of {@link #getChild(InodeDirectoryView, String, ReadOption)} with default
   *    option
   */
  default Optional<Inode> getChild(InodeDirectoryView inode, String name) {
    return getChild(inode.getId(), name, ReadOption.defaults());
  }

  /**
   * @param inode an inode directory
   * @param option the options
   * @return whether the inode has any children
   */
  boolean hasChildren(InodeDirectoryView inode, ReadOption option);

  /**
   * @param inode an inode directory
   * @return the result of {@link #hasChildren(InodeDirectoryView, ReadOption)} with default option
   */
  default boolean hasChildren(InodeDirectoryView inode) {
    return hasChildren(inode, ReadOption.defaults());
  }

  /**
   * @return all edges in the inode store
   */
  @VisibleForTesting
  Set<EdgeEntry> allEdges();

  /**
   * @return all inodes in the inode store
   */
  @VisibleForTesting
  Set<MutableInode<?>> allInodes();
}


text:
package recipient

import (
	"testing"

	stripe "github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/currency"
	"github.com/stripe/stripe-go/token"
	. "github.com/stripe/stripe-go/utils"
)

func init() {
	stripe.Key = GetTestKey()
}

func TestRecipientNew(t *testing.T) {
	recipientParams := &stripe.RecipientParams{
		Name:  "Recipient Name",
		Type:  Individual,
		TaxID: "000000000",
		Email: "a@b.com",
		Desc:  "Recipient Desc",
		Bank: &stripe.BankAccountParams{
			Country: "US",
			Routing: "110000000",
			Account: "000123456789",
		},
		Card: &stripe.CardParams{
			Name:   "Test Debit",
			Number: "4000056655665556",
			Month:  "10",
			Year:   "20",
		},
	}

	target, err := New(recipientParams)

	if err != nil {
		t.Error(err)
	}

	if target.Name != recipientParams.Name {
		t.Errorf("Name %q does not match expected name %q\n", target.Name, recipientParams.Name)
	}

	if target.Type != recipientParams.Type {
		t.Errorf("Type %q does not match expected type %q\n", target.Type, recipientParams.Type)
	}

	if target.Email != recipientParams.Email {
		t.Errorf("Email %q does not match expected email %q\n", target.Email, recipientParams.Email)
	}

	if target.Desc != recipientParams.Desc {
		t.Errorf("Description %q does not match expected description %q\n", target.Desc, recipientParams.Desc)
	}

	if target.Created == 0 {
		t.Errorf("Created date is not set\n")
	}

	if target.Bank == nil {
		t.Errorf("Bank account is not set\n")
	}

	if target.Bank.Country != recipientParams.Bank.Country {
		t.Errorf("Bank country %q does not match expected country %q\n", target.Bank.Country, recipientParams.Bank.Country)
	}

	if target.Bank.Currency != currency.USD {
		t.Errorf("Bank currency %q does not match expected value\n", target.Bank.Currency)
	}

	if target.Bank.LastFour != "6789" {
		t.Errorf("Bank last four %q does not match expected value\n", target.Bank.LastFour)
	}

	if len(target.Bank.Name) == 0 {
		t.Errorf("Bank name is not set\n")
	}

	if target.Cards == nil || target.Cards.Count != 1 {
		t.Errorf("Recipient cards not set\n")
	}

	if len(target.DefaultCard.ID) == 0 {
		t.Errorf("Recipient default card is not set\n")
	}

	Del(target.ID)
}

func TestRecipientNewToken(t *testing.T) {

	tokenParams := &stripe.TokenParams{
		Bank: &stripe.BankAccountParams{
			Country: "US",
			Routing: "110000000",
			Account: "000123456789",
		},
	}

	tok, _ := token.New(tokenParams)

	recipientParams := &stripe.RecipientParams{
		Name:  "Recipient Name",
		Type:  Individual,
		TaxID: "000000000",
		Email: "a@b.com",
		Desc:  "Recipient Desc",
		Bank: &stripe.BankAccountParams{
			Token: tok.ID,
		},
		Card: &stripe.CardParams{
			Name:   "Test Debit",
			Number: "4000056655665556",
			Month:  "10",
			Year:   "20",
		},
	}

	target, err := New(recipientParams)

	if err != nil {
		t.Error(err)
	}

	if target.Name != recipientParams.Name {
		t.Errorf("Name %q does not match expected name %q\n", target.Name, recipientParams.Name)
	}

	if target.Type != recipientParams.Type {
		t.Errorf("Type %q does not match expected type %q\n", target.Type, recipientParams.Type)
	}

	if target.Email != recipientParams.Email {
		t.Errorf("Email %q does not match expected email %q\n", target.Email, recipientParams.Email)
	}

	if target.Desc != recipientParams.Desc {
		t.Errorf("Description %q does not match expected description %q\n", target.Desc, recipientParams.Desc)
	}

	if target.Created == 0 {
		t.Errorf("Created date is not set\n")
	}

	if target.Bank == nil {
		t.Errorf("Bank account is not set\n")
	}

	if target.Bank.Country != tokenParams.Bank.Country {
		t.Errorf("Bank country %q does not match expected country %q\n", target.Bank.Country, tokenParams.Bank.Country)
	}

	if target.Bank.Currency != currency.USD {
		t.Errorf("Bank currency %q does not match expected value\n", target.Bank.Currency)
	}

	if target.Bank.LastFour != "6789" {
		t.Errorf("Bank last four %q does not match expected value\n", target.Bank.LastFour)
	}

	if len(target.Bank.Name) == 0 {
		t.Errorf("Bank name is not set\n")
	}

	if target.Cards == nil || target.Cards.Count != 1 {
		t.Errorf("Recipient cards not set\n")
	}

	if len(target.DefaultCard.ID) == 0 {
		t.Errorf("Recipient default card is not set\n")
	}

	Del(target.ID)
}

func TestRecipientGet(t *testing.T) {
	recipientParams := &stripe.RecipientParams{
		Name: "Recipient Name",
		Type: Individual,
	}

	rec, _ := New(recipientParams)

	target, err := Get(rec.ID, nil)

	if err != nil {
		t.Error(err)
	}

	if len(target.ID) == 0 {
		t.Errorf("Recipient not found\n")
	}

	Del(target.ID)
}

func TestRecipientUpdate(t *testing.T) {
	recipientParams := &stripe.RecipientParams{
		Name:  "Original Name",
		Type:  Individual,
		Email: "original@b.com",
		Desc:  "Original Desc",
	}

	original, _ := New(recipientParams)

	updated := &stripe.RecipientParams{
		Name:  "Updated Name",
		Email: "updated@b.com",
		Desc:  "Updated Desc",
	}

	target, err := Update(original.ID, updated)

	if err != nil {
		t.Error(err)
	}

	if target.Name != updated.Name {
		t.Errorf("Name %q does not match expected name %q\n", target.Name, updated.Name)
	}

	if target.Email != updated.Email {
		t.Errorf("Email %q does not match expected email %q\n", target.Email, updated.Email)
	}

	if target.Desc != updated.Desc {
		t.Errorf("Description %q does not match expected description %q\n", target.Desc, updated.Desc)
	}

	Del(target.ID)
}

func TestRecipientList(t *testing.T) {
	recipientParams := &stripe.RecipientParams{
		Name: "Recipient Name",
		Type: Individual,
	}

	recipients := make([]string, 5)

	for i := 0; i < 5; i++ {
		rec, _ := New(recipientParams)
		recipients[i] = rec.ID
	}

	i := List(nil)
	for i.Next() {
		if i.Recipient() == nil {
			t.Error("No nil values expected")
		}

		if i.Meta() == nil {
			t.Error("No metadata returned")
		}
	}
	if err := i.Err(); err != nil {
		t.Error(err)
	}
}


text:
require 'test_helper'

class RemotePayuInTest < Test::Unit::TestCase
  def setup
    @gateway = PayuInGateway.new(fixtures(:payu_in))

    @amount = 1100
    @credit_card = credit_card('5123456789012346', month: 5, year: 2017, verification_value: 564)

    @options = {
      order_id: generate_unique_id
    }
  end

  def test_successful_purchase
    response = @gateway.purchase(@amount, @credit_card, @options)
    assert_success response
    assert_equal 'No Error', response.message
  end

  def test_successful_purchase_with_full_options
    response = @gateway.purchase(
      @amount,
      @credit_card,
      order_id: generate_unique_id,
      description: 'Awesome!',
      email: 'jim@example.com',
      billing_address: {
        name: 'Jim Smith',
        address1: '123 Road',
        address2: 'Suite 123',
        city: 'Somewhere',
        state: 'ZZ',
        country: 'US',
        zip: '12345',
        phone: '12223334444'
      },
      shipping_address: {
        name: 'Joe Bob',
        address1: '987 Street',
        address2: 'Suite 987',
        city: 'Anyplace',
        state: 'AA',
        country: 'IN',
        zip: '98765',
        phone: '98887776666'
      }
    )

    assert_success response
  end

  def test_failed_purchase
    response = @gateway.purchase(0, @credit_card, @options)
    assert_failure response
    assert_match %r{invalid amount}i, response.message
  end

  def test_successful_refund
    purchase = @gateway.purchase(@amount, @credit_card, @options)
    assert_success purchase

    refund = @gateway.refund(@amount, purchase.authorization)
    assert_success refund
  end

  def test_partial_refund
    purchase = @gateway.purchase(@amount, @credit_card, @options)
    assert_success purchase

    refund = @gateway.refund(@amount - 1, purchase.authorization)
    assert_success refund
  end

  def test_failed_refund
    response = @gateway.refund(100, '')
    assert_failure response
  end

  def test_3ds_enrolled_card_fails
    response = @gateway.purchase(@amount, credit_card('4012001037141112'), @options)
    assert_failure response
    assert_equal '3D-secure enrolled cards are not supported.', response.message

=begin
    # This is handy for testing that 3DS is working with PayU
    response = response.responses.first

    # You'll probably need a new bin from http://requestb.in
    bin = "<requestb.in key>"
    File.open("3ds.html", "w") do |f|
      f.puts %(
        <html>
        <body>
          <form action="#{response.params["post_uri"]}" method="POST">
            <input type="hidden" name="PaReq" value="#{response.params["form_post_vars"]["PaReq"]}" />
            <input type="hidden" name="MD" value="#{response.params["form_post_vars"]["MD"]}" />
            <input type="hidden" name="TermUrl" value="http://requestb.in/#{bin}" />
            <input type="submit" />
          </form>
        </body>
        </html>
      )
    end
    puts "Test 3D-secure via `open 3ds.html`"
    puts "View results at http://requestb.in/#{bin}?inspect"
    puts "Finalize with: `curl -v -d PaRes='' -d MD='' '#{response.params["form_post_vars"]["TermUrl"]}'`"
=end
  end

  def test_transcript_scrubbing
    transcript = capture_transcript(@gateway) do
      @gateway.purchase(@amount, @credit_card, @options)
    end
    transcript = @gateway.scrub(transcript)

    assert_scrubbed(@credit_card.number, transcript)
    refute_match %r{[^\d]#{@credit_card.verification_value}(?:[^\d]|$)}, 'Expected CVV to be scrubbed out of transcript'
  end

  def test_invalid_login
    gateway = PayuInGateway.new(
      key: '',
      salt: ''
    )
    response = gateway.purchase(@amount, @credit_card, @options)
    assert_failure response
  end
end


text:
"use strict";
describe("Rating control tests", function () {
    var testTimeout = 5000;

    sharedSetup();

    it("should initialize a simple Rating control", function () {
        var simpleRatingControl = initControl("

");

        expect(simpleRatingControl.winControl).toBeDefined();
        expect(simpleRatingControl.winControl instanceof WinJS.UI.Rating);
        expect(simpleRatingControl.className).toContain("win-rating");

    });

    it("should use rating attributes", function () {
        var ratingControlWithRatingAttributes = initControl("

");
        var winControl = ratingControlWithRatingAttributes.winControl;

        expect(winControl.maxRating).toEqual(10);
        expect(winControl.userRating).toEqual(9);
        expect(winControl.averageRating).toEqual(3);
    });

    it("should use the disabled attribute", function () {
        var disabledRatingControl = initControl("

");

        expect(disabledRatingControl.winControl.disabled).toBeTruthy();
    });
});


text:
package de.uniaugsburg.isse.solver;

import java.util.Collection;
import java.util.SortedSet;

import de.uniaugsburg.isse.abstraction.types.Interval;
import de.uniaugsburg.isse.powerplants.PowerPlantData;

/**
 * Represents a Constraint Model that is to be solved by an AbstractSolver
 * instance -> includes optimization functions and additional constraints
 *
 * @author Alexander Schiendorfer
 *
 */
public interface AbstractModel {
	void setPlantData(PowerPlantData avpp, Collection<PowerPlantData> children);

	void addEqualityConstraint(String name, String decExpr, double value,
			double tolerance);

	void setObjective(String decExpr, boolean maximize);

	public abstract Collection<PowerPlantData> getChildren();

	public abstract PowerPlantData getAvpp();

	public abstract void setTimeHorizon(int timeHorizon);

	public abstract int getTimeHorizon();

	void setFeasibleRegions(SortedSet<Interval<Double>> generalFeasibleRegions);

	public abstract void setGeneralHoles(
			Collection<Interval<Double>> generalHoles);

	public abstract Collection<Interval<Double>> getGeneralHoles();

	public abstract void addDecisionExpressions(Collection<String> dexprs);

	void requireEqualBound();

	void setInputExpression(String inputExpr);

	void addInputLowerBoundConstraint(double lowerBound);

	void addOutputLowerBound(String decExpr, double prevResult);

	void setCosts(boolean b);

	void setCostsInCents(boolean b);

	public abstract void setUseSoftConstraints(boolean useSoftConstraints);

	public abstract boolean isUseSoftConstraints();

}


text:
package srec

import (
	"bytes"
	"encoding/hex"
	"errors"
	"fmt"
	"io/ioutil"
	"strconv"
	"strings"
)

type srecType int

// HexRec is the generalized form of a hex record
type HexRec struct {
	Address    uint32
	RecordType srecType
	Data       []byte
}

// Enumerated S-Record types
const (
	S0Header srecType = iota // 0
	S1Data                   // 1...
	S2Data                   //
	S3Data                   //
	_                        // S4 not defined in Motorola SREC standard
	S5Count
	S6Count
	S7Start
	S8Start
	S9Start
)

var srecTypeMap map[string]srecType
var srecStrMap map[srecType]string

func init() {
	srecTypeMap = make(map[string]srecType)
	srecStrMap = make(map[srecType]string)

	var srecEnums = []srecType{
		S0Header, S1Data, S2Data,
		S3Data, S5Count, S6Count,
		S7Start, S8Start, S9Start}

	for _, v := range srecEnums {
		s := fmt.Sprintf("S%d", v)
		srecTypeMap[s] = v
		srecStrMap[v] = s
	}
}

// String is the idiomatic Go string-ize method
func (r HexRec) String() string {
	var s string

	header := srecStrMap[r.RecordType]
	if header == "" {
		header = "S?"
	}

	switch r.RecordType {
	case S0Header, S1Data, S5Count, S9Start: // 16-bit address cases
		s = fmt.Sprintf("Address: 0x%04X, Type: %s, Lenght: %d, content: %v",
			r.Address, header, len(r.Data), r.Data)

	case S2Data, S6Count, S8Start: // 24-bit address cases
		s = fmt.Sprintf("Address: 0x%06X, Type: %s, Lenght: %d, content: %v",
			r.Address, header, len(r.Data), r.Data)

	case S3Data, S7Start: // 32-bit address cases
		s = fmt.Sprintf("Address: 0x%08X, Type: %s, Lenght: %d, content: %v",
			r.Address, header, len(r.Data), r.Data)
	}

	return s
}

// Break the ASCII-Hex record up into fields; translate
// and validate all fields according to record type.
func decodeRecord(r string) (rec *HexRec, err error) {
	defer func() {
		if x := recover(); x != nil {
			err = fmt.Errorf("run time panic: %v", x)
		}
	}()

	var (
		address   string
		data      string
		checksum  string
		header    = r[:2]
		byteCount = r[2:4]
		recTyp    = srecTypeMap[header]
		ovhd      int
		csData    = r[2 : len(r)-2] // this is what will be checksum'd
	)

	switch recTyp {
	case S0Header, S1Data, S5Count, S9Start: // 16-bit address cases
		address = r[4:8]
		data = r[8:]
		ovhd = 2 + 1

	case S2Data, S6Count, S8Start: // 24-bit address cases
		address = r[4:10]
		data = r[10:]
		ovhd = 3 + 1

	case S3Data, S7Start: // 32-bit address cases
		address = r[4:12]
		data = r[12:]
		ovhd = 4 + 1

	default:
		return nil, errors.New("Unknown SREC type")
	}

	checksum, data = data[len(data)-2:], data[:len(data)-2]
	cs, err := strconv.ParseUint(checksum, 16, 8)
	if err != nil {
		return nil, err
	}

	csCalc, err := calcChecksumHexASCII(csData)
	if err != nil {
		return nil, err
	}
	if byte(cs) != csCalc {
		return nil, errors.New("Checksum error")
	}

	binData, err := hex.DecodeString(data)
	if err != nil {
		return nil, fmt.Errorf("Data chars bad: %s", err)
	}

	addrBin, err := strconv.ParseUint(address, 16, 32)
	if err != nil {
		return nil, fmt.Errorf("Address field error: %s", err)
	}

	bc, err := strconv.ParseUint(byteCount, 16, 8)
	if err != nil {
		return nil, fmt.Errorf("Byte-count field error: %s", err)
	}

	if int(bc) != (len(binData) + ovhd) {
		return nil, errors.New("byte-count error")
	}

	rec = new(HexRec)
	rec.Address = uint32(addrBin)
	rec.RecordType = recTyp
	rec.Data = binData

	return rec, nil
}

// Process all hex records
func processRecords(records []string) ([]*HexRec, error) {
	var hrecs []*HexRec

	for _, rec := range records {
		if len(rec) > 0 {
			hr, err := decodeRecord(rec)
			if err != nil {
				return nil, err
			}
			hrecs = append(hrecs, hr)
		}
	}

	return hrecs, nil
}

// Load contents of hex file into memory; break up into
// a slice of strings.
func loadFile(fn string) ([]string, error) {
	content, err := ioutil.ReadFile(fn)
	if err != nil {
		return nil, err
	}

	records := strings.Split(string(content), "\n")

	return records, nil
}

// ReadFile loads the contents of a hex file into memory and
// converts the contents into a slice of hex records.
func ReadFile(fn string) ([]*HexRec, error) {
	records, err := loadFile(fn)
	if err != nil {
		return nil, err
	}

	return processRecords(records)
}

// CoalesceDataRecs merges a contiguous runs of data records. All other
// record types are unaffected.  Contiguous data records are coalesced into
// a so-called "jumbo" data record.  A jumbo record is really a hex record
// that represents a large run of contiguous bytes
func CoalesceDataRecs(list []*HexRec) []*HexRec {
	type handler func(*HexRec, srecType)
	var (
		dataRecGroup   bool
		addressCounter uint32
		outList        []*HexRec
		data           bytes.Buffer
		dataBaseAddr   uint32
		processDataRec handler
	)

	emitJumboDataRec := func(pt srecType) {
		var r HexRec
		r.Address = dataBaseAddr // Set Base Address
		r.RecordType = pt
		r.Data = data.Bytes()         // Set Data slice within record
		data.Reset()                  // Clear accumulation buffer
		outList = append(outList, &r) // Append record to output slice
	}

	processDataRec = func(r *HexRec, pt srecType) {
		if !dataRecGroup { // have we hit a new run of data recs?
			dataRecGroup = true
			dataBaseAddr = r.Address
			addressCounter = r.Address + uint32(len(r.Data))
			data.Reset()
			data.Write(r.Data)
		} else {
			if r.Address == addressCounter { // Contiguous with previous?
				data.Write(r.Data)
				addressCounter += uint32(len(r.Data))
			} else { // else, data records are not contiguous
				// Emit a Jumbo Data Record; reset temp buffer
				emitJumboDataRec(pt)
				dataRecGroup = false
				processDataRec(r, pt)
			}
		}
	}

	// Survey data record types
	var s1Count, s2Count, s3Count int
	for _, r := range list {
		switch r.RecordType {
		case S1Data:
			s1Count++
		case S2Data:
			s2Count++
		case S3Data:
			s3Count++
		}
	}

	// In case mixed data records were used in the original file,
	// determine which should be used for emitted jumbo records
	var preferredDataRecType srecType
	if s3Count > 0 {
		preferredDataRecType = S3Data
	} else if s2Count > 0 {
		preferredDataRecType = S2Data
	} else {
		preferredDataRecType = S1Data
	}

	// Cycle through all records looking specifically for data
	// records.
	for _, r := range list {
		switch r.RecordType {
		case S1Data, S2Data, S3Data:
			processDataRec(r, preferredDataRecType)

		default: // Other type found; terminate preceeding data group
			if data.Len() > 0 {
				emitJumboDataRec(preferredDataRecType)
			}
			dataRecGroup = false
			outList = append(outList, r)
		}
	}

	// Do we need to emit one last jumbo data record?
	if data.Len() > 0 {
		emitJumboDataRec(preferredDataRecType)
	}

	return outList
}


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

namespace GlobalcachingApplication.Plugins.FormulaSolver.FormulaInterpreter.Functions
{
    interface ICharacterMapper
    {
        int GetCharacterCode(char character);
    }
}


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

var minLengthValidator = require('../../src/validators').minLength;

describe('minLength', function () {

  it('throws an error if length is not numeric', function (done) {
    var fn = function () {
      minLengthValidator();
    };
    expect(fn).to.throw(TypeError, /length/);
    done();
  });

  it('returns a default error message if rule fails', function (done) {
    var expectedMessage = 'value has a minimum length of 10';
    var adapter = {
      value: function () {
        return 'too short';
      }
    };
    var rule = minLengthValidator(10);
    var error = rule(adapter);
    expect(error).to.be.instanceOf(Error);
    expect(error.message).to.equal(expectedMessage);
    done();
  });

  it('returns a custom error message if rule fails', function (done) {
    var expectedMessage = 'expected message';
    var adapter = {
      value: function () {
        return 'too short';
      }
    };
    var rule = minLengthValidator(10, expectedMessage);
    var error = rule(adapter);
    expect(error).to.be.instanceOf(Error);
    expect(error.message).to.equal(expectedMessage);
    done();
  });

  it('returns undefined if rule succeeds', function (done) {
    var adapter = {
      value: function () {
        return '12345678901';
      }
    };
    var rule = minLengthValidator(10);
    var error = rule(adapter);
    expect(error).to.be.undefined;
    done();
  });
});


text:
module OffsitePayments #:nodoc:
  module Integrations #:nodoc:
    # Documentation:
    # https://www.payfast.co.za/s/std/integration-guide
    module PayFast
      # Overwrite this if you want to change the PayFast sandbox url
      mattr_accessor :process_test_url
      self.process_test_url = 'https://sandbox.payfast.co.za/eng/process'

      # Overwrite this if you want to change the PayFast production url
      mattr_accessor :process_production_url
      self.process_production_url = 'https://www.payfast.co.za/eng/process'

      # Overwrite this if you want to change the PayFast sandbox url
      mattr_accessor :validate_test_url
      self.validate_test_url = 'https://sandbox.payfast.co.za/eng/query/validate'

      # Overwrite this if you want to change the PayFast production url
      mattr_accessor :validate_production_url
      self.validate_production_url = 'https://www.payfast.co.za/eng/query/validate'

      mattr_accessor :signature_parameter_name
      self.signature_parameter_name = 'signature'

      def self.service_url
        mode = OffsitePayments.mode
        case mode
        when :production
          self.process_production_url
        when :test
          self.process_test_url
        else
          raise StandardError, "Integration mode set to an invalid value: #{mode}"
        end
      end

      def self.validate_service_url
        mode = OffsitePayments.mode
        case mode
        when :production
          self.validate_production_url
        when :test
          self.validate_test_url
        else
          raise StandardError, "Integration mode set to an invalid value: #{mode}"
        end
      end

      def self.helper(order, account, options = {})
        Helper.new(order, account, options)
      end

      def self.notification(query_string, options = {})
        Notification.new(query_string, options)
      end

      def self.return(post, options = {})
        Return.new(post, options)
      end

      module Common
        def generate_signature(type)
          string = case type
          when :request
            request_signature_string
          when :notify
            notify_signature_string
          end

          Digest::MD5.hexdigest(string)
        end

        def request_attributes
          [:merchant_id, :merchant_key, :return_url, :cancel_url,
           :notify_url, :name_first, :name_last, :email_address,
           :payment_id, :amount, :item_name, :item_description,
           :custom_str1, :custom_str2, :custom_str3, :custom_str4,
           :custom_str5, :custom_int1, :custom_int2, :custom_int3,
           :custom_int4, :custom_int5, :email_confirmation,
           :confirmation_address]
        end

        def request_signature_string
          request_attributes.map do |attr|
            "#{mappings[attr]}=#{CGI.escape(@fields[mappings[attr]])}" if @fields[mappings[attr]].present?
          end.compact.join('&')
        end

        def notify_signature_string
          params.map do |key, value|
            "#{key}=#{CGI.escape(value)}" unless key == PayFast.signature_parameter_name
          end.compact.join('&')
        end
      end

      class Helper < OffsitePayments::Helper
        include Common

        def initialize(order, account, options = {})
          super
          add_field('merchant_id', account)
          add_field('merchant_key', options.delete(:credential2))
          add_field('m_payment_id', order)
        end

        def form_fields
          @fields
        end

        def params
          @fields
        end

        mapping :merchant_id, 'merchant_id'
        mapping :merchant_key, 'merchant_key'
        mapping :return_url, 'return_url'
        mapping :cancel_return_url, 'cancel_url'
        mapping :notify_url, 'notify_url'
        mapping :name_first, 'name_first'
        mapping :name_last, 'name_last'
        mapping :email_address, 'email_address'
        mapping :payment_id, 'm_payment_id'
        mapping :amount, 'amount'
        mapping :item_name, 'item_name'
        mapping :description, 'item_name'

        mapping :customer, :first_name => 'name_first',
                           :last_name  => 'name_last',
                           :email      => 'email_address',
                           :phone      => 'phone'

        5.times { |i| mapping :"custom_str#{i}", "custom_str#{i}" }
        5.times { |i| mapping :"custom_int#{i}", "custom_int#{i}" }

        mapping :email_confirmation, 'email_confirmation'
        mapping :confirmation_address, 'confirmation_address'
      end

      # Parser and handler for incoming ITN from PayFast.
      # The Example shows a typical handler in a rails application.
      #
      # Example
      #
      #   class BackendController < ApplicationController
      #     include OffsitePayments::Integrations
      #
      #     def pay_fast_itn
      #       notify = PayFast::Notification.new(request.raw_post)
      #
      #       order = Order.find(notify.item_id)
      #
      #       if notify.acknowledge
      #         begin
      #
      #           if notify.complete? and order.total == notify.amount
      #             order.status = 'success'
      #
      #             shop.ship(order)
      #           else
      #             logger.error("Failed to verify Paypal's notification, please investigate")
      #           end
      #
      #         rescue => e
      #           order.status = 'failed'
      #           raise
      #         ensure
      #           order.save
      #         end
      #       end
      #
      #       render :nothing
      #     end
      #   end
      class Notification < OffsitePayments::Notification
        include ActiveUtils::PostsData
        include Common

        # Was the transaction complete?
        def complete?
          status == "Completed"
        end

        # Status of transaction. List of possible values:
        # <tt>COMPLETE</tt>::
        def status
          if params['payment_status'] == "COMPLETE"
            "Completed"
          else
            "Failed"
          end
        end

        # Id of this transaction (uniq PayFast transaction id)
        def transaction_id
          params['pf_payment_id']
        end

        # Id of this transaction (uniq Shopify transaction id)
        def item_id
          params['m_payment_id']
        end

        # The total amount which the payer paid.
        def gross
          params['amount_gross']
        end

        # The total in fees which was deducted from the amount.
        def fee
          params['amount_fee']
        end

        # The net amount credited to the receiver's account.
        def amount
          params['amount_net']
        end

        # The name of the item being charged for.
        def item_name
          params['item_name']
        end

        # The Merchant ID as given by the PayFast system. Used to uniquely identify the receiver's account.
        def merchant_id
          params['merchant_id']
        end

        def currency
          nil
        end

        # Generated hash depends on params order so use OrderedHash instead of Hash
        def empty!
          super
          @params  = ActiveSupport::OrderedHash.new
        end

        # Acknowledge the transaction to PayFast. This method has to be called after a new
        # ITN arrives. PayFast will verify that all the information we received are correct and will return a
        # VERIFIED or INVALID status.
        #
        # Example:
        #
        #   def pay_fast_itn
        #     notify = PayFastNotification.new(request.raw_post)
        #
        #     if notify.acknowledge
        #       ... process order ... if notify.complete?
        #     else
        #       ... log possible hacking attempt ...
        #     end
        def acknowledge(authcode = nil)
          if params[PayFast.signature_parameter_name] == generate_signature(:notify)
            response = ssl_post(PayFast.validate_service_url, notify_signature_string,
              'Content-Type' => "application/x-www-form-urlencoded",
              'Content-Length' => "#{notify_signature_string.size}"
            )
            raise StandardError.new("Faulty PayFast result: #{response}") unless ['VALID', 'INVALID'].include?(response)

            response == "VALID"
          end
        end
      end

      class Return < OffsitePayments::Return
      end
    end
  end
end


text:
(function() {

    var Window = require('ui/ApplicationWindow');
    Ti.App.rootWindow = new Window();
    Ti.App.rootWindow.open();

    Ti.App.Properties.setBool("music", Ti.App.Properties.getBool("music", true));
	Ti.App.Properties.setString("version_settings", Ti.App.version);

})();


text:
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/http';
import '@angular/router';

import 'rxjs';
import '@angularclass/hmr';

// Other vendors for example jQuery, Lodash or Bootstrap
// You can import js, ts, css, sass, ...
import '@angular/material/core/theming/prebuilt/indigo-pink';


text:
/**
 *  @file MolalityVPSSTP.h
 *   Header for intermediate ThermoPhase object for phases which
 *   employ molality based activity coefficient formulations
 *  (see \ref thermoprops
 * and class \link Cantera::MolalityVPSSTP MolalityVPSSTP\endlink).
 *
 * Header file for a derived class of ThermoPhase that handles
 * variable pressure standard state methods for calculating
 * thermodynamic properties that are further based upon activities
 * based on the molality scale.  These include most of the methods for
 * calculating liquid electrolyte thermodynamics.
 */
/*
 * Copyright (2006) Sandia Corporation. Under the terms of
 * Contract DE-AC04-94AL85000 with Sandia Corporation, the
 * U.S. Government retains certain rights in this software.
 */
#ifndef CT_MOLALITYVPSSTP_H
#define CT_MOLALITYVPSSTP_H

#include "VPStandardStateTP.h"

namespace Cantera
{

/**
 * @ingroup thermoprops
 */

/*!
 * MolalityVPSSTP is a derived class of ThermoPhase that handles
 * variable pressure standard state methods for calculating
 * thermodynamic properties that are further based on
 * molality-scaled activities.
 * This category incorporates most of the methods
 * for calculating liquid electrolyte thermodynamics that have been
 * developed since the 1970's.
 *
 * This class adds additional functions onto the ThermoPhase interface
 * that handle molality based standard states. The ThermoPhase
 * class includes a member function, ThermoPhase::activityConvention()
 * that indicates which convention the activities are based on. The
 * default is to assume activities are based on the molar convention.
 * However, classes which derive from the MolalityVPSSTP class return
 * cAC_CONVENTION_MOLALITY from this member function.
 *
 * The molality of a solute, \f$ m_i \f$, is defined as
 *
 * \f[
 *     m_i = \frac{n_i}{\tilde{M}_o n_o}
 * \f]
 * where
 * \f[
 *     \tilde{M}_o = \frac{M_o}{1000}
 * \f]
 *
 * where \f$ M_o \f$ is the molecular weight of the solvent. The molality
 * has units of gmol kg-1. For the solute, the molality may be
 * considered as the amount of gmol's of solute per kg of solvent, a natural
 * experimental quantity.
 *
 * The formulas for calculating mole fractions if given the molalities of
 * the solutes is stated below. First calculate \f$ L^{sum} \f$, an intermediate
 * quantity.
 *
 *   \f[
 *       L^{sum} = \frac{1}{\tilde{M}_o X_o} = \frac{1}{\tilde{M}_o} + \sum_{i\ne o} m_i
 *  \f]
 *  Then,
 *  \f[
 *       X_o =   \frac{1}{\tilde{M}_o L^{sum}}
 *  \f]
 *  \f[
 *       X_i =   \frac{m_i}{L^{sum}}
 *  \f]
 * where \f$ X_o \f$ is the mole fraction of solvent, and \f$ X_o \f$ is the
 * mole fraction of solute i. Thus, the molality scale and the mole fraction
 * scale offer a one-to-one mapping between each other, except in the limit
 * of a zero solvent mole fraction.
 *
 * The standard states for thermodynamic objects that derive from MolalityVPSSTP
 * are on the unit molality basis. Chemical potentials
 * of the solutes,  \f$ \mu_k \f$, and the solvent, \f$ \mu_o \f$, which are based
 * on the molality form, have the following general format:
 *
 * \f[
 *    \mu_k = \mu^{\triangle}_k(T,P) + R T ln(\gamma_k^{\triangle} \frac{m_k}{m^\triangle})
 * \f]
 * \f[
 *    \mu_o = \mu^o_o(T,P) + RT ln(a_o)
 * \f]
 *
 * where \f$ \gamma_k^{\triangle} \f$ is the molality based activity coefficient for species
 * \f$k\f$.
 *
 * The chemical potential of the solvent is thus expressed in a different format
 * than the chemical potential of the solutes. Additionally, the activity of the
 * solvent, \f$ a_o \f$, is further reexpressed in terms of an osmotic coefficient,
 * \f$ \phi \f$.
 *   \f[
 *       \phi = \frac{- ln(a_o)}{\tilde{M}_o \sum_{i \ne o} m_i}
 *   \f]
 *
 *  MolalityVPSSTP::osmoticCoefficient() returns the value of \f$ \phi \f$.
 *  Note there  are a few of definitions of the osmotic coefficient floating
 *  around. We use the one defined in
 *  (Activity Coefficients in Electrolyte Solutions, K. S. Pitzer
 *   CRC Press, Boca Raton, 1991, p. 85, Eqn. 28). This definition is most clearly
 *  related to theoretical calculation.
 *
 * The molar-based activity coefficients \f$ \gamma_k \f$ may be calculated
 * from the molality-based
 * activity coefficients, \f$ \gamma_k^\triangle \f$ by the following
 * formula.
 * \f[
 *     \gamma_k = \frac{\gamma_k^\triangle}{X_o}
 * \f]
 * For purposes of establishing a convention, the molar activity coefficient of the
 * solvent is set equal to the molality-based activity coefficient of the
 * solvent:
 * \f[
 *     \gamma_o = \gamma_o^\triangle
 * \f]
 *
 *  The molality-based and molarity-based standard states may be related to one
 *  another by the following formula.
 *
 * \f[
 *   \mu_k^\triangle(T,P) = \mu_k^o(T,P) + R T \ln(\tilde{M}_o m^\triangle)
 * \f]
 *
 *  An important convention is followed in all routines that derive from MolalityVPSSTP.
 *  Standard state thermodynamic functions and reference state thermodynamic functions
 *  return the molality-based quantities. Also all functions which return
 *  activities return the molality-based activities. The reason for this convention
 *  has been discussed in supporting memos. However, it's important because the
 *  term in the equation above is non-trivial. For example it's equal
 *  to 2.38 kcal gmol-1 for water at 298 K.
 *
 *
 * In order to prevent a singularity, this class includes the concept of a minimum
 * value for the solvent mole fraction. All calculations involving the formulation
 * of activity coefficients and other non-ideal solution behavior adhere to
 * this concept of a minimal value for the solvent mole fraction. This makes sense
 * because these solution behavior were all designed and measured far away from
 * the zero solvent singularity condition and are not applicable in that limit.
 *
 *
 * This objects add a layer that supports molality. It inherits from VPStandardStateTP.
 *
 *  All objects that derive from this are assumed to have molality based standard states.
 *
 *  Molality based activity coefficients are scaled according to the current
 *  pH scale. See the Eq3/6 manual for details.
 *
 *  Activity coefficients for species k may be altered between scales s1 to s2
 *  using the following formula
 *
 *   \f[
 *       ln(\gamma_k^{s2}) = ln(\gamma_k^{s1})
 *          + \frac{z_k}{z_j} \left(  ln(\gamma_j^{s2}) - ln(\gamma_j^{s1}) \right)
 *   \f]
 *
 *  where j is any one species. For the NBS scale, j is equal to the Cl- species
 *  and
 *
 *  \f[
 *       ln(\gamma_{Cl-}^{s2}) = \frac{-A_{\phi} \sqrt{I}}{1.0 + 1.5 \sqrt{I}}
 *  \f]
 *
 *  The Pitzer scale doesn't actually change anything. The pitzer scale is defined
 *  as the raw unscaled activity coefficients produced by the underlying objects.
 *
 *
 SetState Strategy

 *
 *   The MolalityVPSSTP object does not have a setState strategy concerning the
 *   molalities. It does not keep track of whether the molalities have changed.
 *   It's strictly an interfacial layer that writes the current mole fractions to the
 *   State object. When molalities are needed it recalculates the molalities from
 *   the State object's mole fraction vector.
 *
 *
 * @todo Make two solvent minimum fractions. One would be for calculation of the non-ideal
 *       factors. The other one would be for purposes of stoichiometry evaluation. the
 *       stoichiometry evaluation one would be a 1E-13 limit. Anything less would create
 *       problems with roundoff error.
 */
class MolalityVPSSTP : public VPStandardStateTP
{
public:
    /// Default Constructor
    /*!
     * This doesn't do much more than initialize constants with
     * default values for water at 25C. Water molecular weight
     * comes from the default elements.xml file. It actually
     * differs slightly from the IAPWS95 value of 18.015268. However,
     * density conservation and therefore element conservation
     * is the more important principle to follow.
     */
    MolalityVPSSTP();

    //! Copy constructor
    /*!
     * @param b class to be copied
     */
    MolalityVPSSTP(const MolalityVPSSTP& b);

    /// Assignment operator
    /*!
     * @param b class to be copied.
     */
    MolalityVPSSTP& operator=(const MolalityVPSSTP& b);

    //! Duplication routine for objects which inherit from ThermoPhase.
    /*!
     *  This virtual routine can be used to duplicate objects
     *  inherited from ThermoPhase even if the application only has
     *  a pointer to ThermoPhase to work with.
     */
    virtual ThermoPhase* duplMyselfAsThermoPhase() const;

    //! @name  Utilities
    //! @{

    //! Set the pH scale, which determines the scale for single-ion activity
    //! coefficients.
    /*!
     *  Single ion activity coefficients are not unique in terms of the
     *  representing actual measurable quantities.
     *
     * @param pHscaleType  Integer representing the pHscale
     */
    void setpHScale(const int pHscaleType);

    //! Reports the pH scale, which determines the scale for single-ion activity
    //! coefficients.
    /*!
     *  Single ion activity coefficients are not unique in terms of the
     *  representing actual measurable quantities.
     *
     * @return Return the pHscale type
     */
    int pHScale() const;

    //! @}
    //! @name Utilities for Solvent ID and Molality
    //! @{

    /**
     * This routine sets the index number of the solvent for the phase.
     *
     *  Note, having a solvent is a precursor to many things having to do
     *  with molality.
     *
     * @param k the solvent index number
     */
    void setSolvent(size_t k);

    //! Returns the solvent index.
    size_t solventIndex() const;

    /**
     * Sets the minimum mole fraction in the molality formulation.
     * Note the molality formulation is singular in the limit that
     * the solvent mole fraction goes to zero. Numerically, how
     * this limit is treated and resolved is an ongoing issue within
     * Cantera. The minimum mole fraction must be in the range 0 to 0.9.
     *
     * @param xmolSolventMIN  Input double containing the minimum mole fraction
     */
    void setMoleFSolventMin(doublereal xmolSolventMIN);

    //! Returns the minimum mole fraction in the molality formulation.
    doublereal moleFSolventMin() const;

    //! Calculates the molality of all species and stores the result internally.
    /*!
     *   We calculate the vector of molalities of the species
     *   in the phase and store the result internally:
     *   \f[
     *     m_i = \frac{X_i}{1000 * M_o * X_{o,p}}
     *   \f]
     *    where
     *    - \f$ M_o \f$ is the molecular weight of the solvent
     *    - \f$ X_o \f$ is the mole fraction of the solvent
     *    - \f$ X_i \f$ is the mole fraction of the solute.
     *    - \f$ X_{o,p} = \max (X_{o}^{min}, X_o) \f$
     *    - \f$ X_{o}^{min} \f$ = minimum mole fraction of solvent allowed
     *              in the denominator.
     */
    void calcMolalities() const;

    //!  This function will return the molalities of the species.
    /*!
     *   We calculate the vector of molalities of the species
     *   in the phase
     * \f[
     *     m_i = \frac{X_i}{1000 * M_o * X_{o,p}}
     * \f]
     *    where
     *    - \f$ M_o \f$ is the molecular weight of the solvent
     *    - \f$ X_o \f$ is the mole fraction of the solvent
     *    - \f$ X_i \f$ is the mole fraction of the solute.
     *    - \f$ X_{o,p} = \max (X_{o}^{min}, X_o) \f$
     *    - \f$ X_{o}^{min} \f$ = minimum mole fraction of solvent allowed
     *              in the denominator.
     *
     * @param molal       Output vector of molalities. Length: m_kk.
     */
    void getMolalities(doublereal* const molal) const;

    //! Set the molalities of the solutes in a phase
    /*!
     * Note, the entry for the solvent is not used.
     *   We are supplied with the molalities of all of the
     *   solute species. We then calculate the mole fractions of all
     *   species and update the ThermoPhase object.
     *  \f[
     *     m_i = \frac{X_i}{M_o/1000 * X_{o,p}}
     *  \f]
     *    where
     *    -  \f$M_o\f$ is the molecular weight of the solvent
     *    -  \f$X_o\f$ is the mole fraction of the solvent
     *    -  \f$X_i\f$ is the mole fraction of the solute.
     *    -  \f$X_{o,p} = \max(X_o^{min}, X_o)\f$
     *    -  \f$X_o^{min}\f$ = minimum mole fraction of solvent allowed
     *                     in the denominator.
     *
     * The formulas for calculating mole fractions are
     *  \f[
     *       L^{sum} = \frac{1}{\tilde{M}_o X_o} = \frac{1}{\tilde{M}_o} + \sum_{i\ne o} m_i
     *  \f]
     *  Then,
     *  \f[
     *       X_o =   \frac{1}{\tilde{M}_o L^{sum}}
     *  \f]
     *  \f[
     *       X_i =   \frac{m_i}{L^{sum}}
     *  \f]
     *  It is currently an error if the solvent mole fraction is attempted to be set
     *  to a value lower than  \f$X_o^{min}\f$.
     *
     * @param molal   Input vector of molalities. Length: m_kk.
     */
    void setMolalities(const doublereal* const molal);

    //! Set the molalities of a phase
    /*!
     * Set the molalities of the solutes in a phase. Note, the entry for the
     * solvent is not used.
     *
     * @param xMap  Composition Map containing the molalities.
     */
    void setMolalitiesByName(const compositionMap& xMap);

    //! Set the molalities of a phase
    /*!
     * Set the molalities of the solutes in a phase. Note, the entry for the
     * solvent is not used.
     *
     * @param name  String containing the information for a composition map.
     */
    void setMolalitiesByName(const std::string& name);

    /**
     * @}
     * @name Activities, Standard States, and Activity Concentrations
     *
     * The activity \f$a_k\f$ of a species in solution is
     * related to the chemical potential by \f[ \mu_k = \mu_k^0(T)
     * + \hat R T \log a_k. \f] The quantity \f$\mu_k^0(T,P)\f$ is
     * the chemical potential at unit activity, which depends only
     * on temperature and pressure.
     * @{
     */

    /**
     * This method returns the activity convention.
     * Currently, there are two activity conventions:
     * - Molar-based activities: %Unit activity of species at either a
     *   hypothetical pure solution of the species or at a hypothetical
     *   pure ideal solution at infinite dilution.
     *   `cAC_CONVENTION_MOLAR 0` (default)
     * - Molality based activities: unit activity of solutes at a hypothetical
     *   1 molal solution referenced to infinite dilution at all pressures and
     *   temperatures. The solvent is still on molar basis.
     *   `cAC_CONVENTION_MOLALITY 1`
     *
     *  We set the convention to molality here.
     */
    int activityConvention() const;

    /**
     * This method returns an array of generalized concentrations
     * \f$ C_k\f$ that are defined such that
     * \f$ a_k = C_k / C^0_k, \f$ where \f$ C^0_k \f$
     * is a standard concentration
     * defined below.  These generalized concentrations are used
     * by kinetics manager classes to compute the forward and
     * reverse rates of elementary reactions.
     *
     * @param c Array of generalized concentrations. The
     *           units depend upon the implementation of the
     *           reaction rate expressions within the phase.
     */
    virtual void getActivityConcentrations(doublereal* c) const;

    /**
     * The standard concentration \f$ C^0_k \f$ used to normalize
     * the generalized concentration. In many cases, this quantity
     * will be the same for all species in a phase - for example,
     * for an ideal gas \f$ C^0_k = P/\hat R T \f$. For this
     * reason, this method returns a single value, instead of an
     * array.  However, for phases in which the standard
     * concentration is species-specific (e.g. surface species of
     * different sizes), this method may be called with an
     * optional parameter indicating the species.
     *
     * @param k species index. Defaults to zero.
     */
    virtual doublereal standardConcentration(size_t k=0) const;

    /**
     * Returns the units of the standard and generalized
     * concentrations Note they have the same units, as their
     * ratio is defined to be equal to the activity of the kth
     * species in the solution, which is unitless.
     *
     * This routine is used in print out applications where the
     * units are needed. Usually, MKS units are assumed throughout
     * the program and in the XML input files.
     *
     * @param uA Output vector containing the units
     *  uA[0] = kmol units - default  = 1
     *  uA[1] = m    units - default  = -nDim(), the number of spatial
     *                                dimensions in the Phase class.
     *  uA[2] = kg   units - default  = 0;
     *  uA[3] = Pa(pressure) units - default = 0;
     *  uA[4] = Temperature units - default = 0;
     *  uA[5] = time units - default = 0
     * @param k species index. Defaults to 0.
     * @param sizeUA output int containing the size of the vector.
     *        Currently, this is equal to 6.
     */
    virtual void getUnitsStandardConc(double* uA, int k = 0,
                                      int sizeUA = 6) const;

    //! Get the array of non-dimensional activities (molality
    //! based for this class and classes that derive from it) at
    //! the current solution temperature, pressure, and solution concentration.
    /*!
     * All standard state properties for molality-based phases are
     * evaluated consistent with the molality scale. Therefore, this function
     * must return molality-based activities.
     *
     * \f[
     *  a_i^\triangle = \gamma_k^{\triangle} \frac{m_k}{m^\triangle}
     * \f]
     *
     * This function must be implemented in derived classes.
     *
     * @param ac     Output vector of molality-based activities. Length: m_kk.
     */
    virtual void getActivities(doublereal* ac) const;

    //! Get the array of non-dimensional activity coefficients at
    //! the current solution temperature, pressure, and solution concentration.
    /*!
     * These are mole-fraction based activity coefficients. In this
     * object, their calculation is based on translating the values
     * of the molality-based activity coefficients.
     *  See Denbigh p. 278 for a thorough discussion.
     *
     * The molar-based activity coefficients \f$ \gamma_k \f$ may be calculated from the
     * molality-based
     * activity coefficients, \f$ \gamma_k^\triangle \f$ by the following
     * formula.
     * \f[
     *     \gamma_k = \frac{\gamma_k^\triangle}{X_o}
     * \f]
     *
     * For purposes of establishing a convention, the molar activity coefficient of the
     * solvent is set equal to the molality-based activity coefficient of the
     * solvent:
     *
     * \f[
     *     \gamma_o = \gamma_o^\triangle
     * \f]
     *
     * Derived classes don't need to overload this function. This function is
     * handled at this level.
     *
     * @param ac  Output vector containing the mole-fraction based activity coefficients.
     *            length: m_kk.
     */
    void getActivityCoefficients(doublereal* ac) const;

    //!  Get the array of non-dimensional molality based
    //!  activity coefficients at the current solution temperature,
    //!  pressure, and  solution concentration.
    /*!
     *  See Denbigh p. 278 for a thorough discussion. This class must be overwritten in
     *  classes which derive from MolalityVPSSTP. This function takes over from the
     *  molar-based activity coefficient calculation, getActivityCoefficients(), in
     *  derived classes.
     *
     *  These molality based activity coefficients are scaled according to the current
     *  pH scale. See the Eq3/6 manual for details.
     *
     *  Activity coefficients for species k may be altered between scales s1 to s2
     *  using the following formula
     *
     *   \f[
     *       ln(\gamma_k^{s2}) = ln(\gamma_k^{s1})
     *          + \frac{z_k}{z_j} \left(  ln(\gamma_j^{s2}) - ln(\gamma_j^{s1}) \right)
     *   \f]
     *
     *  where j is any one species. For the NBS scale, j is equal to the Cl- species
     *  and
     *
     *  \f[
     *       ln(\gamma_{Cl-}^{s2}) = \frac{-A_{\phi} \sqrt{I}}{1.0 + 1.5 \sqrt{I}}
     *  \f]
     *
     * @param acMolality Output vector containing the molality based activity coefficients.
     *                   length: m_kk.
     */
    virtual void getMolalityActivityCoefficients(doublereal* acMolality) const;

    //! Calculate the osmotic coefficient
    /*!
     *   \f[
     *       \phi = \frac{- ln(a_o)}{\tilde{M}_o \sum_{i \ne o} m_i}
     *   \f]
     *
     *  Note there  are a few of definitions of the osmotic coefficient floating
     *  around. We use the one defined in
     *  (Activity Coefficients in Electrolyte Solutions, K. S. Pitzer
     *   CRC Press, Boca Raton, 1991, p. 85, Eqn. 28). This definition is most clearly
     *  related to theoretical calculation.
     *
     *  units = dimensionless
     */
    virtual double osmoticCoefficient() const;

    //@}
    /// @name  Partial Molar Properties of the Solution
    //@{

    /**
     * Get the species electrochemical potentials.
     * These are partial molar quantities. This method adds a term
     * \f$ Fz_k \phi_k \f$ to each chemical potential.
     *
     * Units: J/kmol
     *
     * @param mu     output vector containing the species electrochemical potentials.
     *               Length: m_kk.
     */
    void getElectrochemPotentials(doublereal* mu) const;

    //@}
    /**
     * @name Chemical Equilibrium
     * Routines that implement the Chemical equilibrium capability
     * for a single phase, based on the element-potential method.
     * @{
     */

    /**
     * This method is used by the ChemEquil element-potential
     * based equilibrium solver.
     * It sets the state such that the chemical potentials of the
     * species within the current phase satisfy
     * \f[ \frac{\mu_k}{\hat R T} = \sum_m A_{k,m}
     * \left(\frac{\lambda_m} {\hat R T}\right) \f] where
     * \f$ \lambda_m \f$ is the element potential of element m. The
     * temperature is unchanged.  Any phase (ideal or not) that
     * implements this method can be equilibrated by ChemEquil.
     *
     * @param lambda_RT Input vector containing the dimensionless
     *                  element potentials.
     */
    virtual void setToEquilState(const doublereal* lambda_RT);

    //@}

    //! Set equation of state parameter values from XML entries.
    /*!
     * This method is called by function importPhase() when processing a phase
     * definition in an input file. It should be overloaded in subclasses to set
     * any parameters that are specific to that particular phase model.
     *
     * The MolalityVPSSTP object defines a new method for setting
     * the concentrations of a phase. The new method is defined by a
     * block called "soluteMolalities". If this block
     * is found, the concentrations within that phase are
     * set to the "name":"molalities pairs found within that
     * XML block. The solvent concentration is then set
     * to everything else.
     *
     * The function first calls the overloaded function,
     * VPStandardStateTP::setStateFromXML(), to pick up the parent class
     * behavior.
     *
     * usage: Overloaded functions should call this function
     *        before carrying out their own behavior.
     *
     * @param state An XML_Node object corresponding to
     *              the "state" entry for this phase in the input file.
     */
    virtual void setStateFromXML(const XML_Node& state);

    //@}
    //! @name Initialization
    /// The following methods are used in the process of constructing
    /// the phase and setting its parameters from a specification in an
    /// input file. They are not normally used in application programs.
    /// To see how they are used, see importPhase().
    //@{

    virtual void initThermo();

    /**
     *   Import and initialize a ThermoPhase object
     *
     * @param phaseNode This object must be the phase node of a
     *             complete XML tree
     *             description of the phase, including all of the
     *             species data. In other words while "phase" must
     *             point to an XML phase object, it must have
     *             sibling nodes "speciesData" that describe
     *             the species in the phase.
     * @param id   ID of the phase. If nonnull, a check is done
     *             to see if phaseNode is pointing to the phase
     *             with the correct id.
     */
    void initThermoXML(XML_Node& phaseNode, const std::string& id);

    //@}

    //! Set the temperature (K), pressure (Pa), and molalities
    //!(gmol kg-1) of the solutes
    /*!
     * @param t           Temperature (K)
     * @param p           Pressure (Pa)
     * @param molalities  Input vector of molalities of the solutes.
     *                    Length: m_kk.
     */
    void setState_TPM(doublereal t, doublereal p,
                      const doublereal* const molalities);

    //! Set the temperature (K), pressure (Pa), and molalities.
    /*!
     * @param t           Temperature (K)
     * @param p           Pressure (Pa)
     * @param m           compositionMap containing the molalities
     */
    void setState_TPM(doublereal t, doublereal p, const compositionMap& m);

    //! Set the temperature (K), pressure (Pa), and molalities.
    /*!
     * @param t           Temperature (K)
     * @param p           Pressure (Pa)
     * @param m           String which gets translated into a composition
     *                    map for the molalities of the solutes.
     */
    void setState_TPM(doublereal t, doublereal p, const std::string& m);

    //! Get the array of derivatives of the log activity coefficients with respect to the log of the species mole numbers
    /*!
     * Implementations should take the derivative of the logarithm of the activity coefficient with respect to a
     * species log mole number (with all other species mole numbers held constant). The default treatment in the
     * ThermoPhase object is to set this vector to zero.
     *
     *  units = 1 / kmol
     *
     *  dlnActCoeffdlnN[ ld * k  + m]  will contain the derivative of log act_coeff for the mth
     *                               species with respect to the number of moles of the kth species.
     *
     * \f[
     *        \frac{d \ln(\gamma_m) }{d \ln( n_k ) }\Bigg|_{n_i}
     * \f]
     *
     * @param ld               Number of rows in the matrix
     * @param dlnActCoeffdlnN    Output vector of derivatives of the
     *                           log Activity Coefficients. length = m_kk * m_kk
     */
    virtual void getdlnActCoeffdlnN(const size_t ld, doublereal* const dlnActCoeffdlnN) {
        getdlnActCoeffdlnN_numderiv(ld, dlnActCoeffdlnN);
    }

    //! returns a summary of the state of the phase as a string
    /*!
     * @param show_thermo If true, extra information is printed out
     *                    about the thermodynamic state of the system.
     * @param threshold   Show information about species with mole fractions
     *                    greater than *threshold*.
     */
    virtual std::string report(bool show_thermo=true,
                               doublereal threshold=1e-14) const;

protected:

    virtual void getCsvReportData(std::vector<std::string>& names,
                                  std::vector<vector_fp>& data) const;

    //! Get the array of unscaled non-dimensional molality based
    //!  activity coefficients at the current solution temperature,
    //!  pressure, and  solution concentration.
    /*!
     *  See Denbigh p. 278 for a thorough discussion. This class must be overwritten in
     *  classes which derive from MolalityVPSSTP. This function takes over from the
     *  molar-based activity coefficient calculation, getActivityCoefficients(), in
     *  derived classes.
     *
     * @param acMolality Output vector containing the molality based activity coefficients.
     *                   length: m_kk.
     */
    virtual void getUnscaledMolalityActivityCoefficients(doublereal* acMolality) const;

    //! Apply the current phScale to a set of activity Coefficients or activities
    /*!
     *  See the Eq3/6 Manual for a thorough discussion.
     *
     * @param acMolality input/Output vector containing the molality based
     *                   activity coefficients. length: m_kk.
     */
    virtual void applyphScale(doublereal* acMolality) const;

private:
    //! Returns the index of the Cl- species.
    /*!
     *  The Cl- species is special in the sense that its single ion
     *  molality-based activity coefficient is used in the specification
     *  of the pH scale for single ions. Therefore, we need to know
     *  what species index is Cl-. If the species isn't in the species
     *  list then this routine returns -1, and we can't use the NBS
     *  pH scale.
     *
     *  Right now we use a restrictive interpretation. The species
     *  must be named "Cl-". It must consist of exactly one Cl and one E
     *  atom.
     */
    virtual size_t findCLMIndex() const;

    //! Initialize lengths of local variables after all species have
    //! been identified.
    void initLengths();

protected:

    //! Index of the solvent
    /*!
     * Currently the index of the solvent is hard-coded to the value 0
     */
    size_t m_indexSolvent;

    //! Scaling to be used for output of single-ion species activity
    //! coefficients.
    /*!
     *   Index of the species to be used in the single-ion scaling
     *   law. This is the identity of the Cl- species for the PHSCALE_NBS
     *   scaling.
     *   Either PHSCALE_PITZER or PHSCALE_NBS
     */
    int        m_pHScalingType;

    //! Index of the phScale species
    /*!
     *   Index of the species to be used in the single-ion scaling
     *   law. This is the identity of the Cl- species for the PHSCALE_NBS
     *   scaling
     */
    size_t m_indexCLM;

    //! Molecular weight of the Solvent
    doublereal m_weightSolvent;

    /*!
     * In any molality implementation, it makes sense to have
     * a minimum solvent mole fraction requirement, since the
     * implementation becomes singular in the xmolSolvent=0
     * limit. The default is to set it to 0.01.
     * We then modify the molality definition to ensure that
     * molal_solvent = 0 when xmol_solvent = 0.
     */
    doublereal m_xmolSolventMIN;

    //! This is the multiplication factor that goes inside
    //! log expressions involving the molalities of species.
    /*!
     * It's equal to Wt_0 / 1000,
     *     where Wt_0 = weight of solvent (kg/kmol)
     */
    doublereal m_Mnaught;

    //! Current value of the molalities of the species in the phase.
    /*!
     * Note this vector is a mutable quantity.
     * units are (kg/kmol)
     */
    mutable vector_fp  m_molalities;
};

//! Scale to be used for the output of single-ion activity coefficients
//! is that used by Pitzer.
/*!
 *  This is the internal scale used within the code. One property is that
 *  the activity coefficients for the cation and anion of a single salt
 *  will be equal. This scale is the one presumed by the formulation of the
 *  single-ion activity coefficients described in this report.
 *
 *  Activity coefficients for species k may be altered between scales s1 to s2
 *  using the following formula
 *
 *   \f[
 *       ln(\gamma_k^{s2}) = ln(\gamma_k^{s1})
 *          + \frac{z_k}{z_j} \left(  ln(\gamma_j^{s2}) - ln(\gamma_j^{s1}) \right)
 *   \f]
 *
 *  where j is any one species.
 */
const int PHSCALE_PITZER = 0;

//! Scale to be used for evaluation of single-ion activity coefficients
//! is that used by the NBS standard for evaluation of the pH variable.
/*!
 *  This is not the internal scale used within the code.
 *
 *  Activity coefficients for species k may be altered between scales s1 to s2
 *  using the following formula
 *
 *   \f[
 *       ln(\gamma_k^{s2}) = ln(\gamma_k^{s1})
 *          + \frac{z_k}{z_j} \left(  ln(\gamma_j^{s2}) - ln(\gamma_j^{s1}) \right)
 *   \f]
 *
 *  where j is any one species. For the NBS scale, j is equal to the Cl- species
 *  and
 *
 *  \f[
 *       ln(\gamma_{Cl-}^{s2}) = \frac{-A_{\phi} \sqrt{I}}{1.0 + 1.5 \sqrt{I}}
 *  \f]
 *
 *  This is the NBS pH scale, which is used in all conventional pH
 *  measurements. and is based on the Bates-Guggenheim equations.
 */
const int PHSCALE_NBS    = 1;

}

#endif


text:
package com.seovic.core.updater;

import com.seovic.core.Updater;
import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;
import com.tangosol.io.pof.PortableObject;
import java.io.IOException;
import java.util.Map;

/**
 * Simple imlementation of {@link Updater} that updates single map entry.
 *
 * @author Aleksandar Seovic  2009.06.17
 */
public class MapUpdater
        implements Updater, PortableObject {
    // ---- data members ----------------------------------------------------

    private String key;

    // ---- constructors ----------------------------------------------------

    /**
     * Deserialization constructor (for internal use only).
     */
    public MapUpdater() {
    }

    /**
     * Construct a <tt>MapUpdater</tt> instance.
     *
     * @param key the key of the entry to update
     */
    public MapUpdater(String key) {
        this.key = key;
    }

    // ---- Updater implementation ------------------------------------------

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings({"unchecked"})
    public void update(Object target, Object value) {
        if (target == null) {
            throw new IllegalArgumentException("Updater target cannot be null");
        }
        if (!(target instanceof Map)) {
            throw new IllegalArgumentException("Updater target is not a Map");
        }

        ((Map) target).put(key, value);
    }

    //---- PortableObject implementation -----------------------------------

    /**
     * Deserialize this object from a POF stream.
     *
     * @param reader POF reader to use
     *
     * @throws IOException if an error occurs during deserialization
     */
    public void readExternal(PofReader reader)
            throws IOException {
        key = reader.readString(0);
    }

    /**
     * Serialize this object into a POF stream.
     *
     * @param writer POF writer to use
     *
     * @throws IOException if an error occurs during serialization
     */
    public void writeExternal(PofWriter writer)
            throws IOException {
        writer.writeString(0, key);
    }

    // ---- Object methods --------------------------------------------------

    /**
     * Test objects for equality.
     *
     * @param o object to compare this object with
     *
     * @return <tt>true</tt> if the specified object is equal to this object
     *         <tt>false</tt> otherwise
     */
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        MapUpdater that = (MapUpdater) o;
        return key.equals(that.key);
    }

    /**
     * Return hash code for this object.
     *
     * @return this object's hash code
     */
    @Override
    public int hashCode() {
        return key.hashCode();
    }

    /**
     * Return string representation of this object.
     *
     * @return string representation of this object
     */
    @Override
    public String toString() {
        return "MapUpdater{" +
               "key='" + key + '\'' +
               '}';
    }
}