text:
'use strict';

var utils = require(__base + 'sharedlib/utils');
var Locale = require(__base + 'sharedlib/formatter');
var outputFormatter = new Locale(__base);
var Joi = require('joi');
var lodash = require('lodash');
var Promise = require('bluebird');
var jwt = require('jsonwebtoken');
var microtime = require('microtime');
var Group = null;
var User = null;
var Team = null;
var Role = null;

//Joi validation Schema for add/remove Users
var addRemoveUsersSchema = Joi.object().keys({
    action: Joi.string().valid('addUsers', 'removeUsers').required(),
    groupId: Joi.number(),
    groupName: Joi.string(),
    userIds: Joi.array().items(Joi.number().required()).required()
}).xor('groupId', 'groupName'); // should have either groupId or groupName, not both

//Joi validation Schema for add/remove Roles
var addRemoveRolesSchema = Joi.object().keys({
    action: Joi.string().valid('addRoles', 'removeRoles').required(),
    groupId: Joi.number(),
    groupName: Joi.string(),
    roleIds: Joi.array().items(Joi.number().required()).required()
}).xor('groupId', 'groupName'); // should have either groupId or groupName, not both

//Joi validation Schema for update group details
var updateGroupSchema = Joi.object().keys({
    action: Joi.string().valid('update').required(),
    groupId: Joi.string().required(),
    name: Joi.string(),
    description: Joi.string().allow(''),
    ownerId: Joi.string(),
});

/**
 * Validate input according to action and corresponding schema
 * @method checkInputParameters
 * @param {Object} input The input body
 * @returns {Promise} Resolved promise if the input is according to the schema, else rejected with appropriate error message
 */
function checkInputParameters(input) {
    if (input && input.action) { // check if input is present and action is present in input
        // depending on the action use the corresponding schema to validate the input. If none of the actions match return error
        switch (input.action) {
            case 'addUsers':
            case 'removeUsers':
                return utils.checkInputParameters(input, addRemoveUsersSchema);
                break;
            case 'addRoles':
            case 'removeRoles':
                return utils.checkInputParameters(input, addRemoveRolesSchema);
                break;
            case 'update':
                return utils.checkInputParameters(input, updateGroupSchema);
                break;
            default:
                return Promise.reject({
                    id: 400,
                    msg: "Invalid input. \"action\" is required and must be one of" +
                        "[\"addUsers\", \"removeUsers\", \"addRoles\", \"removeRoles\", \"update\"]"
                });
        }
    } else { // if action is not present in the input return error.
        return Promise.reject({
            id: 400,
            msg: "Invalid input. \"action\" is required and must be one of " +
                "[\"addUsers\", \"removeUsers\", \"addRoles\", \"removeRoles\", \"update\"]"
        });
    }
}

/**
 * Fetch group instance to update, add users or remove users. For add users/roles, also fetch users/roles belonging to the team to check if input users/roles belong to the team.
 * Similarly, for remove users/roles fetch the users/roles already added to the group to check if the input users/roles belong to the group.
 * @method fetchGroup
 * @param {String} action The action being performed
 * @param {Number} teamId The team Id decoded from the JWT token
 * @param {Object} input The input object
 * @param {Boolean} isMicroservice Whether the caller is a microservice
 * @returns {Promise} Resolved promise containing the fetched group if successful, else rejected promise with the appropriate error message
 */
function fetchGroup(action, teamId, input, isMicroservice) {
    var find = {};

    var groupPromise = null; // for the promise returned by find group
    var teamUsers = null; // for the promise returned by get users belonging to the team
    var teamRoles = null; // for the promise returned by get roles belonging to the team
    var groupRoles = null; // for the promise returned by get roles already added to the group
    var groupUsers = null; // for the promise returned by get users already added to the group

    // create find query for fetching group
    if (input.groupId) { // if groupId is present, use it to create find query
        find.groupId = input.groupId;
    } else if (input.groupName) { // else if groupName is present, use it to create find query
        find.groupName = input.groupName;
    } else { // if neither is present, return error message
        return Promise.reject({ id: 400, msg: "Invalid input. One of \"groupName\" or \"groupId\" must be present." });
    }

    find.teamId = teamId; // add team Id to find query to enforce that the group must belong to this team only

    // fetch group by find query created and assign returned promise to variable
    groupPromise = Group.findOne({ where: find })
        .then(function(group) {
            // if no group is found, return error message
            if (lodash.isEmpty(group)) {
                return Promise.reject(outputFormatter.format(false, 1100, null, 'Group'));
            } else if (!isMicroservice && action === 'update' && (group.name.toLowerCase() === 'users' || group.name.toLowerCase() === 'admins')) {
                // if group being updated is default group and request is not from a microservice, return error message
                return Promise.reject({ id: 400, msg: "Cannot update default groups." })
            } else {
                return group;
            }
        });

    // if action is addUsers, fetch users belonging to the team to check if users to be added to group are present in the team
    if (action === 'addUsers') {
        // teamUsers = getTeamAttributes(teamId, 'user');
        teamUsers = getValidInputs(teamId, input.userIds, 'user');
    } else if (action === 'addRoles') {
        // if action is addRoles, fetch roles belonging to the team to check if the roles to be added to group belong to team
        // teamRoles = getTeamAttributes(teamId, 'role');
        teamRoles = getValidInputs(teamId, input.roleIds, 'role');
    } else if (action === 'removeUsers') {
        // if action is removeUsers, fetch the users already added to the group to check if users to be removed are present in the group
        groupUsers = getGroupAttributes(groupPromise, input.userIds, 'user');
    } else if (action === 'removeRoles') {
        // if action is removeRoles, fetch the roles already added to the group to check if roles to be removed are present in the group
        groupRoles = getGroupAttributes(groupPromise, input.roleIds, 'role');
    }

    // return when all promises have completed
    return Promise.all([teamUsers, teamRoles, groupPromise, groupUsers, groupRoles]);
}

/**
 * Fetch valid inputs by checking if they belong to the team
 * @method getValidInputs
 * @param {Number} teamId The Id of the team
 * @param {Number[]} inputIds The array of input Ids
 * @param {String} attributeName Name of the attribute to be fetched
 * @returns {Promise} Resolved Promise containing the array of valid input Ids, else rejected Promise containing the appropriate error message
 */
function getValidInputs(teamId, inputIds, attributeName) {

    var model;

    // create find query for user/role using input Ids
    var find = {
        where: {}
    };

    // add the input Ids to the where of the find query
    find.where[attributeName + 'Id'] = { $in: inputIds };

    // if attribute is user, add the team model to the include part of the find query with the team Id to match
    if (attributeName === 'user') {
        model = User;
        find.include = {
            model: Team,
            attributes: ['teamId'],
            through: { attributes: [] }
        };
    } else if (attributeName === 'role') { // if attribute is role add the team Id to the where clause of the find query
        model = Role;
        find.where.teamId = teamId;
    } else {
        return Promise.reject({ id: 400, msg: "Incorrect attribute name. Must be one of \"user\" or \"role\"." });
    }

    // find attribute with team Id and return array of valid Ids
    return model.findAll(find)
        .then(function(findResult) {
            // if result is empty, return error message
            if (lodash.isEmpty(findResult)) {
                return [];
            } else {
                // console.log("Find result fetched ---- ", findResult);

                // if find result is not empty, create array of valid Ids to return from the fetched attribute objects
                var validInputs = lodash.map(findResult, lodash.property(attributeName + 'Id'));

                // console.log("Valid inputs ---- ", validInputs);
                return validInputs;
            }
        });
}

/**
 * Fetch the attributes (users or roles) already present in the group, to check if the input attribute values can be removed from the group
 * @method getGroupAttributes
 * @param {Promise} groupPromise The promise for fetch group, to get the group instance
 * @param {Number[]} inputIds The input array of attribute Ids
 * @param {String} attributeName The name of the attribute to be fetched
 * @returns {Promise} Resolved Promise containing the array of attributes fetched, else rejected Promise containing the appropriate error message
 */
function getGroupAttributes(groupPromise, inputIds, attributeName) {

    return groupPromise.then(function(group) { // fetch the attribute after the group instance is returned
            // create find query to check if the input attribute Ids are added to the group
            var find = {
                where: {}
            };
            // add the input attribute Ids to where clause of the find query
            find.where[attributeName + 'Id'] = { $in: inputIds};

            // create function name from the attribute name
            var functionName = 'get' + attributeName[0].toUpperCase() + attributeName.slice(1) + 's';

            // console.log("Find query ----- ", find);

            // execute function to fetch attributes with the find query
            return group[functionName](find);
        })
        .then(function (attribute) {
            // if no attributes are fetched, return empty array
            if (lodash.isEmpty(attribute)) {
                return [];
            } else {
                // console.log("Group attribute fetched ---- ", attribute);

                // if attributes are found, create array of attribute Ids to return from the fetched attributes
                var groupAttr = lodash.map(attribute, lodash.property(attributeName + 'Id'));

                // console.log("Group attributes after map ---- ", groupAttr);
                return groupAttr;
            }
        })
}

/**
 * Checks if the input attribute Ids are valid by comparing it with the possible valid inputs
 * @method checkIfInputIdsCorrect
 * @param {Number[]} inputIds The array of input attribute Ids
 * @param {Number[]} attributeIds The array of valid attribute Ids
 * @param {String} attributeName The attribute name to be passed in case error
 * @param {String} action The action being performed that caused the error
 * @param {String} presentIn The name of the table in which the attribute values are not present in
 * @returns {Promise} The array of valid input attribute Ids or the rejected error message
 */
function checkIfInputIdsCorrect(inputIds, attributeIds, attributeName, action, presentIn) {
    var uniqueAttributes;

    // if inputIds are present, remove duplicates
    if (inputIds) {
        uniqueAttributes = lodash.uniq(inputIds);
    }

    // find valid input attributes by finding common ones between array of input Ids and array of valid Ids
    // var correctInputIds = lodash.intersection(uniqueAttributes, attributeIds);

    // if any input attribute Id is not valid, return error message
    if (attributeIds.length !== uniqueAttributes.length) {
        return Promise.reject(outputFormatter.format(false, 2320, null, attributeName, action, 'group', presentIn));
    } else { // else return the valid input attributes
        return attributeIds;
    }
}

/**
 * Format the output response using the code and attribute
 * @method formatOutput
 * @param {Number} code The code corresponding to the action performed
 * @param {String} attribute The attribute that was to be changed
 * @returns {Object} The formatted output object
 */
function formatOutput(code, attribute) {
    return {
        statusCode: 200,
        content: outputFormatter.format(true, code, null, attribute, 'Group')
    };
}

/**
 * Formats the output response and returns the response
 * @method sendResponse
 * @param {Object} result The updated Group details to return
 * @param {Function} done The done formats and sends the response
 */
function sendResponse(action, result, done) {
    if (result !== null) {
        switch (action) {
            case 'addUsers':
                done(null, formatOutput(2250, 'User/s'));
                break;
            case 'removeUsers':
                done(null, formatOutput(2260, 'User/s'));
                break;
            case 'addRoles':
                done(null, formatOutput(2250, 'Role/s'));
                break;
            case 'removeRoles':
                done(null, formatOutput(2260, 'Role/s'));
                break;
            case 'update':
                done(null, {
                    statusCode: 200,
                    content: outputFormatter.format(true, 2050, result, 'Group')
                });
                break;
            default:
                done(null, {
                    statusCode: 200,
                    content: outputFormatter.format(false, 102)
                });
        }
    } else {
        //else return error
        done(null, {
            statusCode: 200,
            content: outputFormatter.format(false, 102)
        });
    }
}

module.exports = function(options) {
    var seneca = options.seneca;
    var dbConnection = options.dbConnection;
    return function(args, done) {

        Group = Group || dbConnection.models.groups;
        User = User || dbConnection.models.users;
        Team = Team || dbConnection.models.teams;
        Role = Role || dbConnection.models.roles;

        var action = null;

        checkInputParameters(args.body)
            .then(function() {
                action = args.body.action;
                delete args.body.action;
                return utils.checkIfAuthorized(args.credentials, false, true);
            })
            .then(function() {
                var teamId = args.credentials.teamId;
                var isMicroservice = args.credentials.isMicroservice;
                return fetchGroup(action, teamId, args.body.groupId, args.body.groupName, isMicroservice, args.body);
            })
            .spread(function(teamUsers, teamRoles, group, groupUsers, groupRoles) {

                if (action === 'addUsers') {
                    return [group, checkIfInputIdsCorrect(args.body.userIds, teamUsers, 'users', 'added to', 'team')];
                } else if (action === 'removeUsers') {
                    return [group, checkIfInputIdsCorrect(args.body.userIds, groupUsers, 'users', 'removed from', 'group')];
                } else if (action === 'addRoles') {
                    return [group, checkIfInputIdsCorrect(args.body.roleIds, teamRoles, 'roles', 'added to', 'team')];
                } else if (action === 'removeRoles') {
                    return [group, checkIfInputIdsCorrect(args.body.roleIds, groupRoles, 'roles', 'removed from', 'group')];
                }
            })
            .spread(function(group, correctInputIds) {
                // console.log("Correct input ids ---- ", correctInputIds);
                switch (action) {
                    case 'addUsers':
                        return group.addUsers(correctInputIds);
                        break;
                    case 'removeUsers':
                        return group.removeUsers(correctInputIds);
                        break;
                    case 'addRoles':
                        return group.addRoles(correctInputIds);
                        break;
                    case 'removeRoles':
                        return group.removeRoles(correctInputIds);
                        break;
                    case 'update':
                        var updateData = lodash.omitBy(args.body, function(value) {
                            return value === null || value === {};
                        });
                        delete updateData.groupId;
                        return group.update(args.body);
                    default:
                        done(null, {
                            statusCode: 200,
                            content: utils.error(400, "Invalid input. \"action\" is required and must be one of" +
                        "[\"addUsers\", \"removeUsers\", \"addRoles\", \"removeRoles\", \"update\"]", microtime.now())
                        });
                }
            })
            .then(function(response) {
                sendResponse(action, response, done);
            })
            .catch(function(err) {
                console.log("Error in updateRole ----- ", err);
                done(null, {
                    statusCode: 200,
                    content: 'success' in err ? err : utils.error(err.id || 400, err.message || err.msg || 'Unexpected error', microtime.now())
                });
            });
    };
};


text:
package bboss.org.apache.velocity.runtime.resource;

import java.io.StringWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import bboss.org.apache.velocity.exception.ResourceNotFoundException;
import bboss.org.apache.velocity.exception.VelocityException;

/**
 * This class represent a general text resource that may have been
 * retrieved from any number of possible sources.
 *
 * Also of interest is Velocity's {@link bboss.org.apache.velocity.Template}
 * Resource.
 *
 * @author Jason van Zyl
 * @author Geir Magnusson Jr.
 * @version $Id: ContentResource.java 687177 2008-08-19 22:00:32Z nbubna $
 */
public class ContentResource extends Resource
{
    /** Default empty constructor */
    public ContentResource()
    {
        super();

        setType(ResourceManager.RESOURCE_CONTENT);
    }

    /**
     * Pull in static content and store it.
     * @return True if everything went ok.
     *
     * @exception ResourceNotFoundException Resource could not be
     * found.
     */
    public boolean process()
        throws ResourceNotFoundException
    {
        BufferedReader reader = null;

        try
        {
            StringWriter sw = new StringWriter();

            reader = new BufferedReader(
                new InputStreamReader(resourceLoader.getResourceStream(name),
                                      encoding));

            char buf[] = new char[1024];
            int len = 0;

            while ( ( len = reader.read( buf, 0, 1024 )) != -1)
                sw.write( buf, 0, len );

            setData(sw.toString());

            return true;
        }
        catch ( ResourceNotFoundException e )
        {
            // Tell the ContentManager to continue to look through any
            // remaining configured ResourceLoaders.
            throw e;
        }
        catch ( Exception e )
        {
            String msg = "Cannot process content resource";
            rsvc.getLog().error(msg, e);
            throw new VelocityException(msg, e);
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (Exception ignored)
                {
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Rocket extends Model {

	protected $table = 'rockets';

	protected $fillable = array('user_id', 'cannon_id', 'shield_id', 'engine_id');

	protected $hidden = array('created_at', 'updated_at');

	public function user()
	{
		return $this->belongsTo('App\User');
	}

	public function rocketComponents()
	{
		return $this->hasMany('App\RocketComponent');
	}
}


text:
import styles from './nav_bar_create_and_search_sets.mss';

/*****************************************************************************/
/* NavBarCreateAndSearchSets: Event Handlers */
/*****************************************************************************/
Template.NavBarCreateAndSearchSets.events({
  'keyup [name="search"]': function (event, template) {
    let value = event.target.value.trim();
    this.textChangeHandler(value);
  }
});

/*****************************************************************************/
/* NavBarCreateAndSearchSets: Helpers */
/*****************************************************************************/
Template.NavBarCreateAndSearchSets.helpers({
  styles: styles
});

/*****************************************************************************/
/* NavBarCreateAndSearchSets: Lifecycle Hooks */
/*****************************************************************************/
Template.NavBarCreateAndSearchSets.onCreated(function () {
});

Template.NavBarCreateAndSearchSets.onRendered(function () {
});

Template.NavBarCreateAndSearchSets.onDestroyed(function () {
});


text:
import logging
import lldb

log = logging.getLogger('disassembly')

MAX_INSTR_BYTES = 8 # Max number of instruction bytes to show.
NO_SYMBOL_INSTRUCTIONS = 32 # How many instructions to show when there isn't a symbol associated
                            # with the PC location.

# bisect_left with get_key
def lower_bound(a, x, get_key = lambda x: x):
    lo = 0
    hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if get_key(a[mid]) < x: lo = mid+1
        else: hi = mid
    return lo

# bisect_right with get_key
def upper_bound(a, x, get_key = lambda x: x):
    lo = 0
    hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < get_key(a[mid]): hi = mid
        else: lo = mid+1
    return lo

# Find a Dissassembly whose range the address belongs to (assuming a is sorted on start_address)
def find(a, address):
    i  = upper_bound(a, address, lambda dasm: dasm.start_address) - 1
    if i >= 0 and a[i].start_address <= address < a[i].end_address:
        return a[i]
    else:
        return None

# Insert Dissassembly in sorted order
def insert(a, dasm):
    i = lower_bound(a, dasm.start_address, lambda dasm: dasm.start_address)
    assert i == len(a) or dasm.start_address != a[i].start_address
    a.insert(i, dasm)

class Disassembly:
    start_sbaddr = None # SBAddress
    start_address = None # physical address
    end_address = None # physical address
    target = None
    source_ref = None

    def __init__(self, pc_sbaddr, target):
        self.target = target
        self.symbol = symbol = pc_sbaddr.GetSymbol()
        pc_address = pc_sbaddr.GetLoadAddress(self.target)
        if symbol.IsValid():
            self.start_sbaddr = symbol.GetStartAddress()
            self.start_address = self.start_sbaddr.GetLoadAddress(self.target)
            self.source_name = '%s @%x' % (symbol.GetName(), self.start_address)
            self.instructions = symbol.GetInstructions(self.target)
            last_instr = self.instructions[len(self.instructions)-1]
            self.end_address = last_instr.GetAddress().GetLoadAddress(self.target) + last_instr.GetByteSize()

        if not symbol.IsValid() or not (self.start_address <= pc_address < self.end_address):
            # Just read some instructions around the PC location.
            self.start_sbaddr = pc_sbaddr
            self.start_address = pc_sbaddr.GetLoadAddress(self.target)
            self.source_name = "@%x" % self.start_address
            self.instructions = self.target.ReadInstructions(pc_sbaddr, NO_SYMBOL_INSTRUCTIONS)
            last_instr = self.instructions[len(self.instructions)-1]
            self.end_address = last_instr.GetAddress().GetLoadAddress(self.target) + last_instr.GetByteSize()

        assert self.start_address <= pc_address < self.end_address
        self.addresses = [-1, -1] # addresses corresponding to source lines (-1 = comment)
        for instr in self.instructions:
            self.addresses.append(instr.GetAddress().GetLoadAddress(self.target))

    def line_num_by_address(self, load_addr):
        return lower_bound(self.addresses, load_addr) + 1 # lines numbers are 1-based

    def address_by_line_num(self, line_num):
        return self.addresses[line_num - 1]

    def get_source_ref(self):
        return { 'name': self.source_name, 'sourceReference': self.source_ref }

    def get_source_text(self):
        line_entry = self.start_sbaddr.GetLineEntry()
        if line_entry.IsValid():
            source_location = '%s:%d' % (line_entry.GetFileSpec(), line_entry.GetLine())
        else:
            source_location = 'unknown'
        if self.symbol.IsValid():
            desc = lldb.SBStream()
            self.symbol.GetDescription(desc)
            description = desc.GetData()
        else:
            description = 'No symbol info'

        lines = [
            '; %s' % description,
            '; Source location: %s' % source_location ]
        for instr in self.instructions:
            addr = instr.GetAddress().GetLoadAddress(self.target)
            dump = ''
            for i,b in enumerate(instr.GetData(self.target).uint8):
                if i >= MAX_INSTR_BYTES:
                    dump += '>'
                    break
                dump += '%02X ' % b
            dump = dump.ljust(MAX_INSTR_BYTES * 3 + 2)
            line = '%08X: %s %-6s %s' % (addr, dump,
                instr.GetMnemonic(self.target), instr.GetOperands(self.target))
            comment = instr.GetComment(self.target)
            if len(comment) > 0:
                line += '  ; ' + comment
            #line = str(instr)
            lines.append(line)
        return '\n'.join(lines)


text:
using ConnectFour.GameOverConditions;
using NUnit.Framework;

namespace ConnectFour.Tests.GameOverConditions
{
    [TestFixture]
    public class DrawConditionTests : GameOverConditionTestBase
    {
        /// <summary>
        /// Does a Draw occur when we fill the entire board with pieces?
        /// </summary>
        [Test]
        public void DrawConditionWorksFullWithFullBoard()
        {
            // Y R Y R Y
            // R Y R Y R
            // R Y R Y Y
            // R R Y R R
            // Y R Y R Y
            // 0 1 2 3 4
            int[] columnMoves = { 0, 1, 0, 1, 2, 3, 2, 3, 4, 4, 1, 0, 1, 0, 3, 2, 3, 2, 4, 4, 0, 1, 2, 3, 4 };

            RunGameOverConditionTest(rows: 5, columns: 5,
                expectedValidMoveCount: 25, expectedInvalidMoveCount: 0, expectedGameOverCount: 1,
                columnMoves: columnMoves, expectedWinnerType: null, expectedGameOverType: typeof(DrawGameOverCondition));
        }
    }
}


text:
<!DOCTYPE HTML>

	<meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>BHG's Newest Recipes:Eggnog Cheesecake with Candied Kumquats Recipe</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<meta property="og:title" content="Eggnog Cheesecake with Candied Kumquats"/>
        <meta property="og:description" content=""/>
        <meta property="og:type" content="food"/>
        <meta property="og:url" content="http://www.bhg.com/recipe/cheesecake/eggnog-cheesecake-with-candied-kumquats/"/>

                <meta property="og:image" content="http://images.meredith.com/bhg/images/recipe/l_R142956.jpg"/>
                                    <meta property="og:site_name" content="Better Homes & Gardens"/>
    <meta property="fb:admins" content="1561750258" />
<meta property="fb:app_id" content="85037231102" />
    <meta property="fb:page_id" content="72571226018" />
    <meta property="taboola:track" content="false">
<meta name="apple-itunes-app" content="app-id=411903182">
            <link rel="shortcut icon" href="/web/bhg/bhg.ico" />
    <link rel="apple-touch-icon" href='http://images.meredith.com/bhg/images/template/shell/bhg_72x72.png' />
        <link href="http://s1.mdpcdn.com/web/css-min/common/css/html5Reset_9556ab43ae63ce0ea2bfe752cc06a20c.css" rel="stylesheet" /><link href="http://s1.mdpcdn.com/web/css-min/bhg/css/core_bf2ca42c99cdabc922e631c4c43f161d.css" rel="stylesheet" /><link href="http://s1.mdpcdn.com/web/css-min/bhg/css/image_0f30fa78e08f28f5e818146c8db99ed1.css" rel="stylesheet" /><link href="http://s1.mdpcdn.com/web/css-min/common/css/socialmedia_0e0c04c9c1ed3c46b9eee309ddbc4b57.css" rel="stylesheet" /><link href="http://s1.mdpcdn.com/web/css-min/bhg/css/socialmedia_73e896a3d0c035f4223264debb8c6f7e.css" rel="stylesheet" /><link href="http://s1.mdpcdn.com/web/css-min/bhg/css/recipe_749de31edacf32a58a0730da2d0f9613.css" rel="stylesheet" /><link href="http://s1.mdpcdn.com/web/css-min/bhg/css/rating_b9f0f24c348902205f5a1a2559c894cd.css" rel="stylesheet" /><link rel="stylesheet" type="text/css" href="http://www.bhg.com/bhg/files/partner/googleAds/css/bhgGoogle.css"/>

                help

                Q&A

                newsletters

                bhg products

                free offers

                sweepstakes

                subscribe

Join now!

More

Close

            <form id="topsearch" action="/bhg/results.jsp" name="searchbhg" method="get">
                <input type="text" name="q" id="search" class="searchBox" value="Search BHG.com" />
                <input type="hidden" name="searchMode" value='recipes'/>
                <input type="submit" value="Search" class="searchSubmit largeBtn" />
            </form>

    We Like

Delicious Dinner Recipes

Easy Dinner Recipes

                                                                                Recipes & Cooking

Desserts

Healthy Recipes

Chicken

Slow Cooker

Quick & Easy

Party Recipes

                New Recipes

                Food Blog

See All

                                                                                Decorating & Home Ideas

                                                                                Gardening

                                                                                Entertaining

                                                                                Holidays

                                                                                Health

                                                                                Magazine

                                                                                Pets

        Videos

                                                                                Shop

BHG.com  /  Recipes & Cooking

Eggnog Cheesecake with Candied Kumquats

Share

            Save

            Already Saved

                                                    Print

                    Rate

                    Makes: 12
                    servings

                Prep
                 30 mins

                Bake
                375°F 10 mins

                                to  12 mins

                Bake
                350°F 45 mins

                Stand
                1 hr

                         in oven

                Cool
                1 hr 45 mins

                Chill
                6 hrs

                                            Average rating 4.5 from 9 reviews

1

2

3

4

5

make this recipe

                    user reviews ()

Eggnog Cheesecake with Candied Kumquats

1

2

3

4

5

Loved It?

                            Ingredients

                                5

                            tablespoons butter, melted

                                1 1/4

                            cups whole-grain nugget cereal (such as Grape Nuts)

                                1/3

                            cup granulated sugar

                                1/4

                            teaspoon ground cinnamon

                            Dashkosher or sea salt

                                3

                            3 ounce packagescream cheese, softened

                                1

                            cup granulated sugar

                                4

                            eggs, lightly beaten

                                1

                            cup eggnog

                                1

                            tablespoon pure vanilla extract

                                1

                            tablespoon bourbon

                                1

                            tablespoon dark rum

                                1

                            tablespoon brandy

Candied Kumquats

                            12-oz.fresh kumquats (about 45) stems removed

                                2 1/2

                            cups sugar

                                3/4

                            cup water

                            Directions

                    1.
                    Heat oven to 375 degrees F. Butter a 9- or 10-inch springform pan with 1 tablespoon of the butter; set aside.

                    2.
                    In food processor bowl; process cereal about 2 minutes, until a fine crumb forms. Add the 1/3 cup sugar, cinnamon, and salt; process to combine. With processor running, add remaining butter through feed tube just until combined. Press crumb mixture on bottom and 1 inch up sides of prepared pan. Bake 10 to 12 minutes or until crisp and lightly browned. Cool on wire rack. Reduce oven temperature to 350 degrees F.

                    3.
                    In clean food processor bowl,* process cream cheese until smooth. Add 1 cup sugar until combined. Add eggs; process until creamy, scraping down sides once or twice. Add eggnog, vanilla, bourbon, rum, and brandy; process until combined.

                    4.
                    Gently pour filling into baked crust. Bake 45 minutes or until sides are slightly puffed (the center will be soft). Turn off oven and leave the door ajar. Let cheesecake stand in oven 1 hour.

                    5.
                    Transfer to wire rack; cool 15 minutes. Using a small think knife, loosen crust from sides of springform pan. Cool 30 minutes. Remove sides from pan; cool 1 hour. Cover and refrigerate 6 hours or overnight. To serve, top with Candied Kumquats, if desired. Makes 12 servings.

        Candied Kumquats::

                    6.
                    With paring knife, pierce only skin, cutting four evenly spaced slits in each kumquat. Place in medium saucepan; add cold water to cover. Bring to a simmer over medium heat; cook 5 minutes. Drain in colander.

                    7.
                    In medium saucepan stir to dissolve 1-1/2 cups of the sugar in the 3/4 cup water; add kumquats. Bring to a simmer over medium heat. Reduce to low to barely simmer. Cook, uncovered, 30 minutes, until glazed. Remove fruit from syrup with slotted spoon. Place on wire rack over 15x10x1-inch pan. Cool 10 minutes.

                    8.
                    Place the remaining 1 cup sugar in small bowl. Roll whole kumquats in sugar. Space on rack and let stand overnight. Store in airtight container in cool, dry place up to 3 months. Kumquats may be sliced before topping cheesecake.

                            From the Test Kitchen

*Cheesecake filling may be prepared with electric mixer, beating on medium speed.

                Nutrition Facts

                            (Eggnog Cheesecake with Candied Kumquats)

Servings Per Recipe 12,

cal. (kcal) 435,

Fat, total (g) 28,

chol. (mg) 156,

sat. fat (g) 16,

carb. (g) 37,

Monosaturated fat (g) 8,

Polyunsaturated fat (g) 1,

Trans fatty acid (g) 0,

fiber (g) 1,

sugar (g) 27,

pro. (g) 8,

vit. A (IU) 972,

vit. C (mg) 1,

Thiamin (mg) 0,

Riboflavin (mg) 0,

Niacin (mg) 1,

Pyridoxine (Vit. B6) (mg) 0,

Folate (µg) 48,

Cobalamin (Vit. B12) (µg) 1,

sodium (mg) 321,

Potassium (mg) 154,

calcium (mg) 40,

iron (mg) 4,

Percent Daily Values are based on a 2,000 calorie diet

                    Add your review

1

2

3

4

5

Loved It?

    Top Brands

                                            log in

                                                Join now!

My Viewed

My Saved

Recommended

                                            See Where You've Been!

Quickly and easily find items you've viewed. Recipes, decorating ideas, gardening tips and more will all appear right here! We'll list where you've been so you can easily find them again.

        Start Now

                                            Save Your Favorites!

Quick and easy way to save and access decorating ideas, recipes, gardening tips - all in one spot!

        Save Now

    your picks

Quick &amp; Easy Casseroles

Healthy Dinner Recipes Under $3

Warm and Cozy Fall Desserts

Quick Skillet Recipes

Fabulous Fall Cake Recipes

Our Best Slow Cooker Chicken Recipes

Mexican Casserole Recipes

23 Fuss-Free Ground Beef Recipes

Make-and-Take Recipes for Fall

Fabulous 5-Ingredient Slow Cooker Recipes

        more smart savings

    Connect with Us

<map name="connectMap">
	<area alt="Like us on Facebook" coords="0,0,125,50" href="http://www.facebook.com/pages/Better-Homes-and-Gardens/72571226018">
	<area alt="Follow us on Pinterest" coords="152,0,277,50" href="http://pinterest.com/bhg/">
</map>

Your Account

Log in

Join now!

Account

Renew

                Help

                Profile

                Newsletters

                Mobile Site

                Member Benefits

                Subscribe

                Give a Gift

                Privacy Policy

Customer Service

                                            AdChoices

                                            Digital Subscriptions

Better Homes & Gardens

                About Us

                Advertise on BHG.com

                Media Kit

                Tools

                Sweepstakes & Offers

                Facebook

                Twitter

                Videos

                Topics

                From Our Sponsors

                Home & Garden Sitemap

                Recipe Sitemap

                Shop Sitemap

    Better Homes & Gardens Network

Better Homes and Gardens

Midwest Living

Traditional Home

All People Quilt

DIY Advice

Home and Family

            © Copyright 2013, Meredith Corporation. All Rights Reserved |

            By using this site, you agree to our Terms of
            Service.


text:
package com.jeesuite.mongo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

import com.mongodb.ClientSessionOptions;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoDatabase;

/**
 *
 * <br>
 * Class Name   : MultiTenantMongoDbFactory
 *
 * @author jiangwei
 * @version 1.0.0
 * @date 2020年5月25日
 */
public class MultiTenantMongoDbFactory implements MongoDatabaseFactory,InitializingBean ,DisposableBean{

	private final static Logger logger = LoggerFactory.getLogger("com.zyframework.core.mongodb");

	//
	private Map<String, SimpleMongoClientDatabaseFactory> realTenantFactoryMappings = new HashMap<>();

	@Override
	public void afterPropertiesSet() throws Exception {
		new SimpleMongoClientDatabaseFactory(mongoClient, databaseName)
		//MultiTenantMongoTemplate.addMongoDbFactory(tenantId, mongoDbFactory);

	}

	@Override
	public MongoDatabase getMongoDatabase() throws DataAccessException {
		return getCurrentClientDatabaseFactory().getMongoDatabase();
	}

	@Override
	public MongoDatabase getMongoDatabase(String dbName) throws DataAccessException {
		return getCurrentClientDatabaseFactory().getMongoDatabase(dbName);
	}

	@Override
	public PersistenceExceptionTranslator getExceptionTranslator() {
		return getCurrentClientDatabaseFactory().getExceptionTranslator();
	}

	@Override
	public ClientSession getSession(ClientSessionOptions options) {
		return getCurrentClientDatabaseFactory().getSession(options);
	}

	@Override
	public MongoDatabaseFactory withSession(ClientSession session) {
		return getCurrentClientDatabaseFactory().withSession(session);
	}

	@Override
	public void destroy() throws Exception {
		realTenantFactoryMappings.values().forEach(c -> {
			try {
				c.destroy();
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
	}

private MongoClient buildMongoClient(DataSourceConfig config){

		Builder builder = new MongoClientOptions.Builder();
		// 连接池设置为300个连接,默认为100
		builder.connectionsPerHost(200);
		// 连接超时毫秒
		builder.connectTimeout(5000);
		//最大等待时间
		builder.maxWaitTime(60000);
		// 套接字超时时间,0无限制
		builder.socketTimeout(10000);
		// 线程队列数
		builder.threadsAllowedToBlockForConnectionMultiplier(10);
		if(StringUtils.isNotBlank(config.getReplicaSetName())){
			builder.requiredReplicaSetName(config.getReplicaSetName());
			builder.readPreference(ReadPreference.secondaryPreferred());//读取偏好, 首先从从节点读取.
			//写关注为1 ,写入主节点即返回.
			builder.writeConcern(WriteConcern.ACKNOWLEDGED);
		}
		MongoClientOptions myOptions = builder.build();

		MongoCredential credential = null;
		if(StringUtils.isNoneBlank(config.getUser(),config.getPassword())){
			credential = MongoCredential.createCredential(config.getUser(), config.getAuthDatabaseName(), config.getPassword().toCharArray());
		}

		List<ServerAddress> seeds = new ArrayList<ServerAddress>();
		String[] hostPortArray = config.getServers().split(";");
		for (String hostPorts : hostPortArray) {
			String[] arr = hostPorts.split(":");
			seeds.add(new ServerAddress(arr[0].toString(), Integer.parseInt(arr[1])));
		}

		 MongoClient mongoClient;
		 if(credential == null){
			 mongoClient = new MongoClient(seeds, myOptions);
		 }else{
			 mongoClient = new MongoClient(seeds, credential, myOptions);
		 }

		 return mongoClient;
	}

	private SimpleMongoClientDatabaseFactory getCurrentClientDatabaseFactory() {
		return realTenantFactoryMappings.get(TenantHolder.getTenantId());
	}

}


text:
package com.facebook.buck.event.listener;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.test.event.TestStatusMessageEvent;
import com.facebook.buck.core.test.event.TestSummaryEvent;
import com.facebook.buck.event.LeafEvent;
import com.facebook.buck.event.TestEventConfigurator;
import com.facebook.buck.step.StepEvent;
import com.facebook.buck.test.TestRuleEvent;
import com.facebook.buck.test.TestStatusMessage;
import com.facebook.buck.util.Ansi;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.logging.Level;
import org.junit.Test;

public class TestThreadStateRendererTest {

  private static final Ansi ANSI = Ansi.withoutTty();
  private static final Function<Long, String> FORMAT_TIME_FUNCTION =
      timeMs -> String.format(Locale.US, "%.1fs", timeMs / 1000.0);
  private static final BuildTarget TARGET1 = BuildTargetFactory.newInstance("//:target1");
  private static final BuildTarget TARGET2 = BuildTargetFactory.newInstance("//:target2");
  private static final BuildTarget TARGET3 = BuildTargetFactory.newInstance("//:target3");
  private static final BuildTarget TARGET4 = BuildTargetFactory.newInstance("//:target4");

  @Test
  public void emptyInput() {
    TestThreadStateRenderer renderer =
        createRenderer(
            2100, ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of());
    assertThat(renderLines(renderer, true), is(equalTo(ImmutableList.<String>of())));
    assertThat(renderLines(renderer, false), is(equalTo(ImmutableList.<String>of())));
    assertThat(renderShortStatus(renderer, true), is(equalTo(ImmutableList.<String>of())));
    assertThat(renderShortStatus(renderer, false), is(equalTo(ImmutableList.<String>of())));
  }

  @Test
  public void commonCase() {
    TestThreadStateRenderer renderer =
        createRenderer(
            4200,
            ImmutableMap.of(
                1L, createTestStartedEventOptional(1, 1000, TARGET2),
                3L, createTestStartedEventOptional(3, 2300, TARGET3),
                4L, createTestStartedEventOptional(4, 1100, TARGET1),
                5L, Optional.empty(),
                8L, createTestStartedEventOptional(6, 3000, TARGET4)),
            ImmutableMap.of(
                1L, Optional.empty(),
                3L, createTestSummaryEventOptional(1, 1600, "Test Case A", "Test A"),
                4L, Optional.empty(),
                5L, Optional.empty(),
                8L, createTestSummaryEventOptional(1, 3800, "Test Case B", "Test B")),
            ImmutableMap.of(),
            ImmutableMap.of(
                1L, createStepStartedEventOptional(1, 1500, "step A"),
                3L, Optional.empty(),
                4L, Optional.empty(),
                5L, Optional.empty(),
                8L, createStepStartedEventOptional(1, 3700, "step B")));
    assertThat(
        renderLines(renderer, true),
        is(
            equalTo(
                ImmutableList.of(
                    " - //:target2... 3.2s (running step A[2.7s])",
                    " - //:target1... 3.1s",
                    " - //:target3... 1.9s (running Test A[2.6s])",
                    " - //:target4... 1.2s (running Test B[0.4s])",
                    " - IDLE"))));
    assertThat(
        renderLines(renderer, false),
        is(
            equalTo(
                ImmutableList.of(
                    " - //:target2... 3.2s (running step A[2.7s])",
                    " - //:target3... 1.9s (running Test A[2.6s])",
                    " - //:target1... 3.1s",
                    " - IDLE",
                    " - //:target4... 1.2s (running Test B[0.4s])"))));
    assertThat(
        renderShortStatus(renderer, true),
        is(equalTo(ImmutableList.of("[:]", "[:]", "[:]", "[:]", "[ ]"))));
    assertThat(
        renderShortStatus(renderer, false),
        is(equalTo(ImmutableList.of("[:]", "[:]", "[:]", "[ ]", "[:]"))));
  }

  @Test
  public void withTestStatusMessageEvents() {
    TestThreadStateRenderer renderer =
        createRenderer(
            4200,
            ImmutableMap.of(
                1L, createTestStartedEventOptional(1, 1000, TARGET2),
                3L, createTestStartedEventOptional(3, 2300, TARGET3),
                4L, createTestStartedEventOptional(4, 1100, TARGET1),
                5L, Optional.empty(),
                8L, createTestStartedEventOptional(6, 3000, TARGET4)),
            ImmutableMap.of(
                1L, Optional.empty(),
                3L, createTestSummaryEventOptional(1, 1600, "Test Case A", "Test A"),
                4L, Optional.empty(),
                5L, Optional.empty(),
                8L, Optional.empty()),
            ImmutableMap.of(
                1L, Optional.empty(),
                3L, Optional.empty(),
                4L, Optional.empty(),
                5L, Optional.empty(),
                8L, createTestStatusMessageEventOptional(1, 3800, "Installing Sim", Level.INFO)),
            ImmutableMap.of(
                1L, createStepStartedEventOptional(1, 1500, "step A"),
                3L, Optional.empty(),
                4L, Optional.empty(),
                5L, Optional.empty(),
                8L, createStepStartedEventOptional(1, 3700, "step B")));
    assertThat(
        renderLines(renderer, true),
        is(
            equalTo(
                ImmutableList.of(
                    " - //:target2... 3.2s (running step A[2.7s])",
                    " - //:target1... 3.1s",
                    " - //:target3... 1.9s (running Test A[2.6s])",
                    " - //:target4... 1.2s (running Installing Sim[0.4s])",
                    " - IDLE"))));
    assertThat(
        renderShortStatus(renderer, true),
        is(equalTo(ImmutableList.of("[:]", "[:]", "[:]", "[:]", "[ ]"))));
  }

  @Test
  public void withMissingInformation() {
    // SuperConsoleEventBusListener stores the data it passes to the renderer in a map that might
    // be concurrently modified from other threads. It is important that the renderer can handle
    // data containing inconsistencies.
    TestThreadStateRenderer renderer =
        createRenderer(
            4200,
            ImmutableMap.of(
                3L, createTestStartedEventOptional(3, 2300, TARGET3),
                4L, createTestStartedEventOptional(4, 1100, TARGET1),
                5L, Optional.empty(),
                8L, createTestStartedEventOptional(6, 3000, TARGET4)),
            ImmutableMap.of(
                1L, Optional.empty(),
                4L, Optional.empty(),
                5L, Optional.empty()),
            ImmutableMap.of(),
            ImmutableMap.of(
                1L, createStepStartedEventOptional(1, 1500, "step A"),
                3L, Optional.empty(),
                5L, Optional.empty()));
    assertThat(
        renderLines(renderer, true),
        is(
            equalTo(
                ImmutableList.of(
                    // missing test rule - no output
                    " - //:target1... 3.1s", // missing test summary
                    " - //:target3... 1.9s", // missing step information
                    " - //:target4... 1.2s",
                    " - IDLE")))); // missing accumulated time - show as IDLE
    assertThat(
        renderShortStatus(renderer, true),
        is(equalTo(ImmutableList.of("[:]", "[:]", "[:]", "[ ]"))));
  }

  private static Optional<? extends TestRuleEvent> createTestStartedEventOptional(
      long threadId, long timeMs, BuildTarget buildTarget) {
    return Optional.of(
        TestEventConfigurator.configureTestEventAtTime(
            TestRuleEvent.started(buildTarget), timeMs, TimeUnit.MILLISECONDS, threadId));
  }

  private static Optional<? extends TestSummaryEvent> createTestSummaryEventOptional(
      long threadId, long timeMs, String testCaseName, String testName) {
    return Optional.of(
        TestEventConfigurator.configureTestEventAtTime(
            TestSummaryEvent.started(UUID.randomUUID(), testCaseName, testName),
            timeMs,
            TimeUnit.MILLISECONDS,
            threadId));
  }

  private static Optional<? extends TestStatusMessageEvent> createTestStatusMessageEventOptional(
      long threadId, long timeMs, String message, Level level) {
    return Optional.of(
        TestEventConfigurator.configureTestEventAtTime(
            TestStatusMessageEvent.started(TestStatusMessage.of(message, level, timeMs)),
            timeMs,
            TimeUnit.MILLISECONDS,
            threadId));
  }

  private static Optional<? extends LeafEvent> createStepStartedEventOptional(
      long threadId, long timeMs, String name) {
    return Optional.of(
        TestEventConfigurator.configureTestEventAtTime(
            StepEvent.started(name, name + " description", UUID.randomUUID()),
            timeMs,
            TimeUnit.MILLISECONDS,
            threadId));
  }

  private TestThreadStateRenderer createRenderer(
      long timeMs,
      Map<Long, Optional<? extends TestRuleEvent>> testEvents,
      Map<Long, Optional<? extends TestSummaryEvent>> testSummaries,
      Map<Long, Optional<? extends TestStatusMessageEvent>> testStatusMessages,
      Map<Long, Optional<? extends LeafEvent>> runningSteps) {
    return new TestThreadStateRenderer(
        ANSI,
        FORMAT_TIME_FUNCTION,
        timeMs,
        80, /* outputMaxColumns */
        testSummaries,
        testStatusMessages,
        runningSteps,
        new BuildRuleThreadTracker(ImmutableMap.of(), testEvents));
  }

  private ImmutableList<String> renderLines(TestThreadStateRenderer renderer, boolean sortByTime) {
    ImmutableList.Builder<String> lines = ImmutableList.builder();
    StringBuilder lineBuilder = new StringBuilder();
    for (long threadId : renderer.getSortedIds(sortByTime)) {
      lineBuilder.delete(0, lineBuilder.length());
      lines.add(renderer.renderStatusLine(threadId));
    }
    return lines.build();
  }

  private ImmutableList<String> renderShortStatus(
      TestThreadStateRenderer renderer, boolean sortByTime) {
    ImmutableList.Builder<String> status = ImmutableList.builder();
    for (long threadId : renderer.getSortedIds(sortByTime)) {
      status.add(renderer.renderShortStatus(threadId));
    }
    return status.build();
  }
}


text:
#pragma once

#include <string>
#include <vector>
class TensorsInfinite;
class StateInfinite;
class ModelInfinite;
class EdgesInfinite;
class AlgorithmStatus;
enum class StorageLevel;
enum class SimulationTask;
namespace h5pp {
    class File;
}

namespace tools::infinite::h5 {
    /* clang-format off */
    namespace save{
        extern int decide_layout(std::string_view prefix_path);
        extern void state            (h5pp::File & h5file, std::string_view  state_prefix, const StorageLevel & storage_level, const StateInfinite & state, const AlgorithmStatus &status);
        extern void edges            (h5pp::File & h5file, std::string_view  edges_prefix, const StorageLevel & storage_level, const EdgesInfinite & edges);
        extern void model            (h5pp::File & h5file, std::string_view  model_prefix, const StorageLevel & storage_level, const ModelInfinite & model);
        extern void mpo              (h5pp::File & h5file, std::string_view  model_prefix, const StorageLevel & storage_level, const ModelInfinite & model);
        extern void measurements     (h5pp::File & h5file, std::string_view  table_prefix, const StorageLevel & storage_level, const TensorsInfinite & tensors, const AlgorithmStatus & status);
    }

    namespace load{
        extern void tensors (const h5pp::File & h5file, std::string_view  state_prefix, TensorsInfinite & state, AlgorithmStatus & status);
        extern void state (const h5pp::File & h5file, std::string_view  state_prefix, StateInfinite & state, const AlgorithmStatus & status);
        extern void model (const h5pp::File & h5file, std::string_view  state_prefix, ModelInfinite & state, const AlgorithmStatus & status);
        extern void validate (const h5pp::File & h5file, std::string_view  state_prefix, const TensorsInfinite & state, const AlgorithmStatus & status);
        extern std::vector<SimulationTask>
            getTaskList(const h5pp::File &h5file, std::string_view state_prefix, const StateInfinite & state, const AlgorithmStatus & status);

    }
    /* clang-format on */
}


text:
package exectest

import (
	"reflect"
	"strings"
	"sync"

	"github.com/pkg/errors"
	"github.com/tsuru/tsuru/exec"
	"github.com/tsuru/tsuru/safe"
)

type command struct {
	name string
	dir  string
	args []string
	envs []string
}

func (c *command) GetName() string {
	return c.name
}

func (c *command) GetArgs() []string {
	return c.args
}

// GetEnvs returns the command environment variables.
func (c *command) GetEnvs() []string {
	return c.envs
}

func (c *command) GetDir() string {
	return c.dir
}

type FakeExecutor struct {
	cmds    []command
	mut     sync.RWMutex
	callMut sync.Mutex
	calls   map[string]int
	Output  map[string][][]byte
}

func (e *FakeExecutor) hasOutputForArgs(args []string) (bool, []byte) {
	e.callMut.Lock()
	defer e.callMut.Unlock()
	if e.calls == nil {
		e.calls = make(map[string]int)
	}
	var generic []byte
	sArgs := strings.Join(args, " ")
	for k, v := range e.Output {
		switch k {
		case sArgs:
			counter := e.calls[sArgs]
			out := v[counter%len(v)]
			e.calls[sArgs] = counter + 1
			return true, out
		case "*":
			generic = v[e.calls["*"]%len(v)]
		}
	}
	if generic != nil {
		e.calls["*"]++
		return true, generic
	}
	return false, nil
}

func (e *FakeExecutor) Execute(opts exec.ExecuteOptions) error {
	c := command{name: opts.Cmd, args: opts.Args, envs: opts.Envs, dir: opts.Dir}
	e.mut.Lock()
	e.cmds = append(e.cmds, c)
	e.mut.Unlock()
	has, out := e.hasOutputForArgs(opts.Args)
	if has {
		opts.Stdout.Write(out)
	}
	return nil
}

func (e *FakeExecutor) ExecutedCmd(cmd string, args []string) bool {
	e.mut.RLock()
	defer e.mut.RUnlock()
	for _, c := range e.cmds {
		if c.name == cmd && reflect.DeepEqual(c.args, args) {
			return true
		}
	}
	return false
}

func (e *FakeExecutor) GetCommands(cmdName string) []command {
	e.mut.RLock()
	defer e.mut.RUnlock()
	var cmds []command
	for _, cmd := range e.cmds {
		if cmd.name == cmdName {
			cmds = append(cmds, cmd)
		}
	}
	return cmds
}

type ErrorExecutor struct {
	FakeExecutor
	Err error
}

func (e *ErrorExecutor) Execute(opts exec.ExecuteOptions) error {
	e.FakeExecutor.Execute(opts)
	if e.Err != nil {
		return e.Err
	}
	return errors.New("")
}

// RetryExecutor succeeds after N failures.
type RetryExecutor struct {
	FakeExecutor

	// How many times will it fail before succeeding?
	Failures int64
	calls    safe.Counter
}

func (e *RetryExecutor) Execute(opts exec.ExecuteOptions) error {
	defer e.calls.Increment()
	var err error
	succeed := e.Failures <= e.calls.Val()
	if !succeed {
		opts.Stdout = opts.Stderr
		err = errors.New("")
	}
	e.FakeExecutor.Execute(opts)
	return err
}

// FailLaterExecutor is the opposite of RetryExecutor. It fails after N
// Succeeds.
type FailLaterExecutor struct {
	FakeExecutor

	Succeeds int64
	calls    safe.Counter
}

func (e *FailLaterExecutor) Execute(opts exec.ExecuteOptions) error {
	defer e.calls.Increment()
	var err error
	fail := e.Succeeds <= e.calls.Val()
	if fail {
		opts.Stdout = opts.Stderr
		err = errors.New("")
	}
	e.FakeExecutor.Execute(opts)
	return err
}


text:
package console.test;

import org.junit.Test;

import console.dao.UserDao;
import console.dao.UserFactory;
import console.dao.WuliuFactory;
import console.dao.vo.Wuliu;

public class DaoTest {

	private UserDao  ud = null;
	{
		ud = UserFactory.getInstance();
	}

	@Test
	public void delDate(){
		Wuliu wl = new Wuliu();

		wl = WuliuFactory.getInstance().getWuliuById(4);
		System.out.println(wl);
		WuliuFactory.getInstance().delWuliu(wl);

	}

	@Test
	public void test() {
//		User user =  new User(3, "adkdskdksk", "admin", "192.168.1.0");

//		ud.addUser(user);
//		ud.addUser(new User(2, "dskkk", "root", "192.168.1.1"));
//
//		System.out.println(ud.addUser(new User(3, "dskkk", "root", "192.168.1.1")));

//		System.out.println(ud.getUserById(4));

//		User user =ud.getUserById(1);
//		user.setCreateTime(new Date());
//		System.out.println(ud.updateUser(user));
		System.out.println(ud.getUserById(1));

	}

	@Test
	public void testWuliu(){
/*		Wuliu wl = new Wuliu();
		wl.setCreateTime(new Date());
		wl.setId(0);
		wl.setCroassName("addd");
		wl.setToName("admin");
		WuliuFactory.getInstance().addWuliu(wl);*/

		System.out.println(WuliuFactory.getInstance().getWuliuById(0));
	}

}


text:
<?php

/* core/modules/rdf/templates/rdf-metadata.html.twig */
class __TwigTemplate_321012967055b791b33c185f23fa70cfe3e531bacde8e4606068f7cb223d3bb9 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $tags = array("for" => 20);
        $filters = array();
        $functions = array();

        try {
            $this->env->getExtension('sandbox')->checkSecurity(
                array('for'),
                array(),
                array()
            );
        } catch (Twig_Sandbox_SecurityError $e) {
            $e->setTemplateFile($this->getTemplateName());

            if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
                $e->setTemplateLine($tags[$e->getTagName()]);
            } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
                $e->setTemplateLine($filters[$e->getFilterName()]);
            } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
                $e->setTemplateLine($functions[$e->getFunctionName()]);
            }

            throw $e;
        }

        // line 20
        $context['_parent'] = $context;
        $context['_seq'] = twig_ensure_traversable((isset($context["metadata"]) ? $context["metadata"] : null));
        foreach ($context['_seq'] as $context["_key"] => $context["attributes"]) {
            // line 21
            echo "  env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["attributes"], "addClass", array(0 => "hidden"), "method"), "html", null, true));
            echo ">
";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['attributes'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
    }

    public function getTemplateName()
    {
        return "core/modules/rdf/templates/rdf-metadata.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  47 => 21,  43 => 20,);
    }
}
/* {#*/
/* /***/
/*  * @file*/
/*  * Default theme implementation for empty spans with RDF attributes.*/
/*  **/
/*  * The XHTML+RDFa doctype allows either  or  syntax to*/
/*  * be used, but for maximum browser compatibility, W3C recommends the*/
/*  * former when serving pages using the text/html media type, see*/
/*  * http://www.w3.org/TR/xhtml1/#C_3.*/
/*  **/
/*  * Available variables:*/
/*  * - metadata: Each item within corresponds to its own set of attributes,*/
/*  *   and therefore, needs its own 'attributes' element.*/
/*  **/
/*  * @see template_preprocess_rdf_metadata()*/
/*  **/
/*  * @ingroup themeable*/
/*  *//* */
/* #}*/
/* {% for attributes in metadata %}*/
/*   */
/* {% endfor %}*/
/* */


text:
@interface SPDMainModel : NSObject

@property (nonatomic, weak) id<SPDListenerAngleProtocol> delegate;
@property CGFloat listenerAngle;

+ (SPDMainModel *) sharedInstance;

- (NSDictionary *) calculateInstrument: (NSString *) instrumentName
                          relocationTo: (CGPoint) instrumentLocation
                    relativetoListener: (CGPoint) listenerLocation;

- (void) calculateListenerRelocationTo: (CGPoint) listenerLocation
                     forAllInstruments: (NSArray *) instruments;   // Dictionaries with name/coordinates pairs

- (void) switchInstrument: (NSString *) instrumentName
                     toOn: (BOOL) isOn;

@end


text:
package ru.job4j.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * class PrimeIterator - итератор для перебора простых чисел в массиве.
 */
public class PrimeIterator implements Iterator {
    /**
     * Входной массив.
     */
    private final int[] values;
    /**
     * Индекс в массиве.
     */
    private int index = 0;

    /**
     * Конструктор.
     * @param values входной массив.
     */
    public PrimeIterator(int[] values) {
        this.values = values;
    }

    /**
     * Переопределенный hasNext.
     * @return true, если в массиве еще остались простые числа.
     */
    @Override
    public boolean hasNext() {
        return getIndexOfNextPrime() != -1;
    }

    /**
     * Переопределенный next.
     * @return простое число из массива.
     */
    @Override
    public Object next() {
        if (getIndexOfNextPrime() != -1) {
            int result = values[getIndexOfNextPrime()];
            index = getIndexOfNextPrime() + 1;
            return result;
        } else {
            throw new NoSuchElementException("No more prime numbers in this collection!");
        }

    }

    /**
     * Метод получения индекса следующего простого числа в массиве.
     * @return индекс следующего просто числа из массива или -1, если такого нет.
     */
    private int getIndexOfNextPrime() {
        int result = -1;
        for (int i = index; i != values.length; i++) {
            if (values[i] != 1) {
                if (values[i] == 2) {
                    return i;
                }
                for (int j = 2; j != values[i]; j++) {
                    if (values[i] % j == 0) {
                        break;
                    }
                    result = i;
                }
                if (result != -1) {
                    break;
                }
            }
        }
        return result;
    }
}


text:
"""
Django settings for someapiproject project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gunicorn',
    'rest_framework',
    'apitestapp',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'someapiproject.urls'

WSGI_APPLICATION = 'someapiproject.wsgi.application'

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

##################
# LOCAL SETTINGS #
##################

# Allow any settings to be defined in local_settings.py which should be
# ignored in your version control system allowing for settings to be
# defined per machine.
try:
    from local_settings import *
except ImportError as e:
    if "local_settings" not in str(e):
        raise e


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter;

import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.DYNAMIC_MAX_ASSIGN;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.MAX_CAPACITY_PERCENTAGE;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.MAX_CHILD_CAPACITY;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.MAX_CHILD_QUEUE_LIMIT;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.QUEUE_AUTO_CREATE;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.RESERVATION_SYSTEM;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.SPECIFIED_NOT_FIRST;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.USER_MAX_APPS_DEFAULT;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.USER_MAX_RUNNING_APPS;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.FAIR_AS_DRF;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.Properties;

import org.junit.Before;
import org.junit.Test;

/**
 * Unit tests for FSConfigToCSConfigRuleHandler.
 *
 */
public class TestFSConfigToCSConfigRuleHandler {
  private static final String ABORT = "abort";
  private static final String WARNING = "warning";

  private FSConfigToCSConfigRuleHandler ruleHandler;
  private DryRunResultHolder dryRunResultHolder;

  @Before
  public void setup() {
    dryRunResultHolder = new DryRunResultHolder();
  }

  private ConversionOptions createDryRunConversionOptions() {
    return new ConversionOptions(dryRunResultHolder, true);
  }

  private ConversionOptions createDefaultConversionOptions() {
    return new ConversionOptions(dryRunResultHolder, false);
  }

  @Test
  public void testInitPropertyActionsToWarning() throws IOException {
    ruleHandler = new FSConfigToCSConfigRuleHandler(new Properties(),
        createDefaultConversionOptions());

    ruleHandler.handleChildQueueCount("test", 1);
    ruleHandler.handleDynamicMaxAssign();
    ruleHandler.handleMaxCapacityPercentage("test");
    ruleHandler.handleMaxChildCapacity();
    ruleHandler.handleQueueAutoCreate("test");
    ruleHandler.handleReservationSystem();
    ruleHandler.handleSpecifiedNotFirstRule();
    ruleHandler.handleUserMaxApps();
    ruleHandler.handleUserMaxAppsDefault();
  }

  @Test
  public void testAllRulesWarning() throws IOException {
    Properties rules = new Properties();
    rules.put(DYNAMIC_MAX_ASSIGN, WARNING);
    rules.put(MAX_CAPACITY_PERCENTAGE, WARNING);
    rules.put(MAX_CHILD_CAPACITY, WARNING);
    rules.put(QUEUE_AUTO_CREATE, WARNING);
    rules.put(RESERVATION_SYSTEM, WARNING);
    rules.put(SPECIFIED_NOT_FIRST, WARNING);
    rules.put(USER_MAX_APPS_DEFAULT, WARNING);
    rules.put(USER_MAX_RUNNING_APPS, WARNING);
    rules.put(FAIR_AS_DRF, WARNING);

    ruleHandler = new FSConfigToCSConfigRuleHandler(rules,
        createDefaultConversionOptions());

    ruleHandler.handleDynamicMaxAssign();
    ruleHandler.handleMaxCapacityPercentage("test");
    ruleHandler.handleMaxChildCapacity();
    ruleHandler.handleQueueAutoCreate("test");
    ruleHandler.handleReservationSystem();
    ruleHandler.handleSpecifiedNotFirstRule();
    ruleHandler.handleUserMaxApps();
    ruleHandler.handleUserMaxAppsDefault();
  }

  @Test
  public void testAllRulesAbort() throws IOException {
    Properties rules = new Properties();
    rules.put(DYNAMIC_MAX_ASSIGN, ABORT);
    rules.put(MAX_CAPACITY_PERCENTAGE, ABORT);
    rules.put(MAX_CHILD_CAPACITY, ABORT);
    rules.put(QUEUE_AUTO_CREATE, ABORT);
    rules.put(RESERVATION_SYSTEM, ABORT);
    rules.put(SPECIFIED_NOT_FIRST, ABORT);
    rules.put(USER_MAX_APPS_DEFAULT, ABORT);
    rules.put(USER_MAX_RUNNING_APPS, ABORT);
    rules.put(USER_MAX_RUNNING_APPS, ABORT);
    rules.put(FAIR_AS_DRF, ABORT);
    rules.put(MAX_CHILD_QUEUE_LIMIT, "1");

    ruleHandler = new FSConfigToCSConfigRuleHandler(rules,
        createDefaultConversionOptions());

    expectAbort(() -> ruleHandler.handleChildQueueCount("test", 2),
        ConversionException.class);
    expectAbort(() -> ruleHandler.handleDynamicMaxAssign());
    expectAbort(() -> ruleHandler.handleMaxCapacityPercentage("test"));
    expectAbort(() -> ruleHandler.handleMaxChildCapacity());
    expectAbort(() -> ruleHandler.handleQueueAutoCreate("test"));
    expectAbort(() -> ruleHandler.handleReservationSystem());
    expectAbort(() -> ruleHandler.handleSpecifiedNotFirstRule());
    expectAbort(() -> ruleHandler.handleUserMaxApps());
    expectAbort(() -> ruleHandler.handleUserMaxAppsDefault());
    expectAbort(() -> ruleHandler.handleFairAsDrf("test"));
  }

  @Test(expected = ConversionException.class)
  public void testMaxChildQueueCountNotInteger() throws IOException {
    Properties rules = new Properties();
    rules.put(MAX_CHILD_QUEUE_LIMIT, "abc");

    ruleHandler = new FSConfigToCSConfigRuleHandler(rules,
        createDefaultConversionOptions());

    ruleHandler.handleChildQueueCount("test", 1);
  }

  @Test
  public void testDryRunWarning() {
    Properties rules = new Properties();

    ruleHandler = new FSConfigToCSConfigRuleHandler(rules,
        createDryRunConversionOptions());

    ruleHandler.handleDynamicMaxAssign();
    ruleHandler.handleMaxChildCapacity();

    assertEquals("Number of warnings", 2,
        dryRunResultHolder.getWarnings().size());
    assertEquals("Number of errors", 0,
        dryRunResultHolder.getErrors().size());
  }

  @Test
  public void testDryRunError() {
    Properties rules = new Properties();
    rules.put(DYNAMIC_MAX_ASSIGN, ABORT);
    rules.put(MAX_CHILD_CAPACITY, ABORT);

    ruleHandler = new FSConfigToCSConfigRuleHandler(rules,
        createDryRunConversionOptions());

    ruleHandler.handleDynamicMaxAssign();
    ruleHandler.handleMaxChildCapacity();

    assertEquals("Number of warnings", 0,
        dryRunResultHolder.getWarnings().size());
    assertEquals("Number of errors", 2,
        dryRunResultHolder.getErrors().size());
  }

  private void expectAbort(VoidCall call) {
    expectAbort(call, UnsupportedPropertyException.class);
  }

  private void expectAbort(VoidCall call, Class<?> exceptionClass) {
    boolean exceptionThrown = false;
    Throwable thrown = null;

    try {
      call.apply();
    } catch (Throwable t) {
      thrown = t;
      exceptionThrown = true;
    }

    assertTrue("Exception was not thrown", exceptionThrown);
    assertEquals("Unexpected exception", exceptionClass, thrown.getClass());
  }

  @FunctionalInterface
  private interface VoidCall {
    void apply();
  }
}


text:
var h = document.getElementById('height');
var d = document.getElementById('distance');

init();

Math.radians = function(degrees) {
  return degrees * Math.PI / 180;
};

function init() {
  if (window.DeviceOrientationEvent) {
    window.addEventListener('deviceorientation', function(eventData) {
      print(eventData.beta);
    }, false);
  } else {
    alert('your browser doesn\'t support the DeviceOrientationEvent.\nTry this on a phone.');
  }
}

function print(angle) {
  document.getElementById("angle").innerHTML = Math.round(angle);
  h.innerHTML = Math.round(Math.tan(Math.radians(Math.round(angle))) * d.value * 10) / 10;
}

function save() {
  document.getElementById('saved').innerHTML = h.innerHTML;
}

document.getElementById('save').addEventListener('click',function(){
  save();
});


text:
require 'optparse'

class MyOptionParser

	attr_reader :options

	def initialize(args)
		@args = args
	end

	def parse()
		@options = {}

		opts = OptionParser.new do|opts|
			#Banner string displayed at top of help
			opts.banner = "Usage: ./main.rb\t--ssh HOST[:PORT] [--user USERNAME] --key KEYFILE --benchmark BENCHMARK"
			opts.separator "\t\t\t--ami AMI-ID --credentials CREDENTIALS --benchmark BENCHMARK"

			@options[:verbose] = false
			opts.on('-v', '--[no-]verbose', 'Output more information') do|v|
				@options[:verbose] = v
			end

			opts.on('-A', '--ami AMI-ID', String, 'Select this AMI for audit') do|ami|
				@options[:ami] = ami
			end

			opts.on('-S', '--ssh HOST', String, 'Select this host for audit') do|host|
				@options[:ssh] = host
			end

			opts.on('-B', '--benchmark BENCHMARK', String, 'Use this benchmark file') do|bm|
				@options[:benchmark] = bm
			end

			opts.on('-K', '--key KEY', String, 'Use this private key file for authentication') do|key|
				@options[:key] = key
			end

			opts.on('-P', '--password PASSWORD', String, 'Use this password for authentication') do|pwd|
				@options[:password] = pwd
			end

			opts.on('-C', '--credentials CREDENTIALS', String, 'Use these Amazon Account credentials to start the AMI') do|cd|
				@options[:credentials] = cd
			end

			opts.on_tail("-h", "--help", "Show this message") do
				puts opts
				exit
			end
		end

		opts.parse(@args)

		if @options[:ssh].nil? and @options[:ami].nil? then
			print "You must specify one of the --ssh or --ami options. Exiting.\n"
			exit 1
		end

		if not @options[:ssh].nil? and not @options[:ami].nil? then
			print "Options --ssh and --ami are mutually exclusive, but both chosen. Please specify only one of them. Exiting.\n"
			exit 1
		end

		if @options[:benchmark].nil? then
			print "Option --benchmark is required. Please specify a benchmark file for this audit. Exiting.\n"
			exit 1
		end

		if not @options[:ssh].nil? and @options[:key].nil? and @options[:password].nil? then
			print "At least one authentication method for SSH is required. Please specify either --key or --password. Exiting.\n"
			exit 1
		end

		return self
	end

	def connection_type
		return :ami unless @options[:ami].nil?
		return :ssh unless @options[:ssh].nil?
		return :none
	end

	def ssh_credentials
		raise "SSH credentials requested although SSH connection method is not chosen" if @options[:ssh].nil?
		raise "No SSH authentication method chosen" if @options[:password].nil? and @options[:key].nil?

		cred = {:host => @options[:ssh]}
		if @options[:user].nil? then
			cred[:user] = 'root'
		else
			cred[:user] = @options[:user]
		end
		cred[:key_data] = @options[:key] unless @options[:key].nil?
		cred[:password] = @options[:password] unless @options[:password].nil?

		return cred
	end

	def benchmark
		raise "No benchmark file specified" if @options[:benchmark].nil?
		return @options[:benchmark]
	end
end


text:
@implementation BOTextTableViewCell

- (void)setup {
	self.textField = [UITextField new];
	self.textField.delegate = self;
	self.textField.textAlignment = NSTextAlignmentRight;
	self.textField.returnKeyType = UIReturnKeyDone;
	self.textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
	[self.contentView addSubview:self.textField];

	NSLayoutConstraint *centerYConstraint = [NSLayoutConstraint constraintWithItem:self.textField attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.textField.superview attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
	NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self.textField attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.textLabel attribute:NSLayoutAttributeRight multiplier:1 constant:15];
	NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:self.textField attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.textField.superview attribute:NSLayoutAttributeRightMargin multiplier:1 constant:0];

	self.textField.translatesAutoresizingMaskIntoConstraints = NO;
	[self.textField.superview addConstraints:@[centerYConstraint, leftConstraint, rightConstraint]];
}

- (void)updateAppearance {
	self.textField.textColor = self.secondaryColor;
	self.textField.tintColor = self.secondaryColor;

	if (self.secondaryFont) {
		self.textField.font = self.secondaryFont;
		self.textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.textField.placeholder attributes:@{NSFontAttributeName : self.secondaryFont}];
	}
}

- (void)settingValueDidChange {
	self.textField.text = self.setting.value;
}

#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField endEditing:YES];

	return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
	NSString *filteredText = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];

	if (filteredText.length < self.minimumTextLength) {
		if (self.inputErrorBlock) self.inputErrorBlock(self, BOTextFieldInputTooShortError);
		textField.text = self.setting.value;
	} else {
		self.setting.value = textField.text;
	}
}

@end


text:
package fox.spiteful.forbidden;

public class Proxy {

    public void stupidJsonBullshit(){

    }
}


text:
/*-
 * This file is part of CXX Experiments.
 *
 * CXX Experiments is free software. See AUTHORS and LICENSE for more
 * information on the copying conditions.
 */
#ifndef TRANSPORT_HPP
#define TRANSPORT_HPP

///
/// \file include/transport.hpp
/// \brief Model of libight's transport
///

#include "constraints.hpp"
#include "pointer.hpp"
#include "slot.hpp"

#include <iostream>
#include <string>

namespace cxx_experiments {

template <template <typename T> class F>
class Transport : public NonCopyable, public NonMovable {

  private:
    int filedesc = -1;

  protected:
    F<void()> connect_handler;
    F<void(std::string)> data_handler;
    F<void()> flush_handler;
    F<void(int)> error_handler;

  public:
    Transport(int fd = -1) : filedesc(fd) {}

    void on_connect(std::function<void()> fn) { connect_handler = fn; }
    void on_data(std::function<void(std::string)> fn) { data_handler = fn; }
    void on_flush(std::function<void()> fn) { flush_handler = fn; }
    void on_error(std::function<void(int)> fn) { error_handler = fn; }

    virtual void emit_connect() { connect_handler(); }
    virtual void emit_data(std::string d) { data_handler(d); }
    virtual void emit_flush() { flush_handler(); }
    virtual void emit_error(int e) { error_handler(e); }

    int get_filedesc() { return filedesc; }

    void close() {
        connect_handler = nullptr;
        data_handler = nullptr;
        flush_handler = nullptr;
        error_handler = nullptr;
        filedesc = -1;
    }

    virtual ~Transport(){};
};

struct TransportWithSlots : public Transport<Slot> {
    using Transport::Transport;
};

struct TransportWrong : public Transport<std::function> {
    using Transport::Transport;
};

struct TransportManual : public Transport<std::function> {
    using Transport::Transport;

    virtual void emit_connect() override {
        auto fn = connect_handler;
        fn();
    }

    virtual void emit_data(std::string d) override {
        auto fn = data_handler;
        fn(d);
    }

    virtual void emit_flush() override {
        auto fn = flush_handler;
        fn();
    }

    virtual void emit_error(int e) override {
        auto fn = error_handler;
        fn(e);
    }
};

template <class T> struct VerboseTransport : public T {
    VerboseTransport(int fd = -1) : T(fd) {
        std::cout << "Construct " << this << "\n";
    }

    virtual ~VerboseTransport() { std::cout << "Destruct " << this << "\n"; }

    virtual void emit_connect() override {
        std::cout << "Connect " << this << "\n";
        T::emit_connect();
    }
};

template <class T> void closure_example() {
    auto pointer = []() {
        auto transport = make<VerboseTransport<T>>(12345);
        transport->on_connect([transport]() { transport->close(); });
        //
        // Here we only return the raw pointer and the reference count of
        // transport is decremented because we leave the scope.
        //
        // However, transport is still alive because it is saved in the
        // closure of the on_connect() callback.
        //
        // We use the raw pointer as dirty trick to use the transport from
        // the main function without changing its refcnt.
        //
        return transport.get();
    }();

    //
    // Now we emit connect() which triggers the above callback which
    // closes the transport which in turn means that all the callbacks
    // are reset. That is, the closure of the callbacks is erased,
    // hence the last reference to transport is gone.
    //
    pointer->emit_connect();
}

}
#endif


text:
RxJava

RxJS

Rx.NET

RxScala

RxClojure

RxSwift

Others


text:
actions :install, :remove

attribute :package_name, name_attribute: true, kind_of: String
attribute :base_url, kind_of: String, default: 'ftp://ftp.software.ibm.com/aix/freeSoftware/aixtoolbox/RPMS/ppc'

default_action :install


text:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Brian Mont</title>
    <atom:link href="http://0.0.0.0:8080/feed.xml" rel="self" type="application/rss+xml"/>
    <link>http://0.0.0.0:8080/</link>
    <description>A personal portfolio and blog website</description>
    <pubDate>Thu, 25 May 2017 21:59:58 +0000</pubDate>

      <item>
        <title>Other projects</title>
        <link>http://0.0.0.0:8080/2017/05/25/more-work.html</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/2017/05/25/more-work.html</guid>
        <description>

Brick Destroyer

A Timer &amp; Countdown Application using React

Sports Chat Application using Ruby on Rails

Location Finder - Links to Google Maps

</description>
        <pubDate>Thu, 25 May 2017 00:00:00 +0000</pubDate>
      </item>

      <item>
        <title>First Experiences With React</title>
        <link>http://0.0.0.0:8080/2017/02/06/react-redux.html</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/2017/02/06/react-redux.html</guid>
        <description>
Advantages of React

I recently decided to built some basic applications with React. If you know basic JS it is relatively straight forward.
A few bullet points:

React Pros

It's easy to see how a component is rendered - it is right in the render function!

Since each part of an app should be built into its own component, it is incredibly easy to follow functionality. This makes debugging and maintainance pretty simple

It works with most frameworks. I rebuilt portions of an AngularJS application to render using React with very little issue.

The Virtual DOM - React knows when to render the view because it is aware of data changes.

There are many react-addons which offer high versatility - For example, state management: redux, or graphing abilities: recharts.

React Negatives

React only serves as the view, although there are compatible tools to simplify state management

Integrating ReactJS into some MVC frameworks requires additional configuration.

Writing components isn't as straight forward as plain HTML/CSS, there is a learning curve for the new syntax

</description>
        <pubDate>Mon, 06 Feb 2017 00:00:00 +0000</pubDate>
      </item>

      <item>
        <title>Experience At Bloc</title>
        <link>http://0.0.0.0:8080/2017/01/03/experience-at-bloc.html</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/2017/01/03/experience-at-bloc.html</guid>
        <description>
Choosing a bootcamp

After learning some basics on my own through books and web sources, I needed a more in depth education on coding. After a lot of research and weighing pros vs cons I chose Bloc.

Foundational courses

Before getting into any application programming, Bloc's curriculum allowed me to reinforce my skills in HTML5, CSS, JS, &amp; Ruby, enough for a basic application. Accounts with Code School and Code Warsoffered me more experience working through JS &amp; Ruby problems.

Mentors

The mentors at Bloc might be the greatest part of this program. Some people may have experience before signing up for a bootcamp. My personal coding experience was limited. Early on, it was very difficult for me to sort through error messages. It was also very difficult to configure the environments needed for working applications. Having a mentor who could dedicate time to me when help was needed was HUGE.

 Sometimes issues are unique to the point that there aren't solutions through stack overflow or other online documentation. To a new coder, having a mentor to challenge you and help you work through issues has been an invaluable resource.

Projects

Bloc has pointed me towards various projects forcing me to explore different frameworks and libraries of code. As of now, I've built applications with VanillaJS, Ruby on Rails and Angular1 frameworks. The projects have required the use of Angular elements, JQuery, SCSS, JSON parsing and API calls, and much more. I'm currently learning React JS and plan on developing dynamic projects with its versatile library of code. The curriculum offered by Bloc has forced me to learn things that I wouldn't have known to look for or how to start.

Yet to come

I am about to enter my final project phase with Bloc. I will post additional information in the future for these projects and experiences with them. Based on my experiences so far, I am confident that the final phase of this course with Bloc will be very beneficial.

</description>
        <pubDate>Tue, 03 Jan 2017 00:00:00 +0000</pubDate>
      </item>

      <item>
        <title>Learning to Develop</title>
        <link>http://0.0.0.0:8080/2016/12/13/learning-to-develop.html</link>
        <guid isPermaLink="true">http://0.0.0.0:8080/2016/12/13/learning-to-develop.html</guid>
        <description>
Deciding to code

I have been working in sales for 6 years now. Every client has unique needs, patterns, and goals. At the same time, to provide for most clients, the overall company processes are very similar.
Documenting everything requires a lot of organization, time, and record keeping. I had been through at least 20 personal systems and was discussing possible solutions when developing an internal program came up.
This conversation led me to research the benefits of building a web application where existing and prospective clients could provide everything to me, and the system would do all of the organizing.

Finding my resources

Before I could decide if I wanted to dive deep into learning how to code, I tested available resources:

HTML &amp; CSS Self-Learning Books

JavaScript Self-Learning Books

Codecademy

W3Schools

Hitting a plateau

All of these resources were great…I learned the basics. I learned syntax and how to structure very simple functions. I could design a static website and have very basic click and hover actions. Online tutorials do a lot of directing but sometimes are light on explanations. These foundations were fantastic as far as learning an application's structure, but to do anything more dynamic, it takes an investment and a lot more time.

Although I reached a plateau after using the above resources, I had a taste for how things worked and I wanted more. I could visualize how to develop more advanced behaviors to offer users more than just information. After doing much more research, I decided on choosing Bloc to be my online web dev bootcamp.

Projects

Learning any language's rules and syntax is definitely beneficial, but without an end goal, it is easy to forget what you are writing. When being assigned a project, it enables you to visualize the UI. Once you decide on the UI, you can begin connecting the user requests to the actions they should be executing. For example:

Some of my projects

BlocJams - Spotify Replica - A user must have the ability to see the albums, songs, and then be able to select actions.

Bloccit - A reddit inspired site - A user can see &amp; read topics, and then create their own and comment on existing ones.

Blocipedia - A wiki site where users can share their knowledge on any topic.

I have found that building the user-interface is the best place for me to start. When you see what the user will be looking at, you can then connect function to the users' requests. When the UI features are in place, you can then target and change elements depending on the application.

Right now, I have a foundation in JS, Ruby, Rails, HTML5, CSS, JQuery, JSON, Angular1, and ReactJS. Every language, library, and framework has its benefit in specific situations. Some are defintely better than others. I look forward to continuing my education to solidify these and learn more through practice and new projects.

</description>
        <pubDate>Tue, 13 Dec 2016 00:00:00 +0000</pubDate>
      </item>

  </channel>
</rss>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>XmlDataAdapterImpl (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.sf.jasperreports.data.xml

Class XmlDataAdapterImpl

java.lang.Object

net.sf.jasperreports.data.AbstractDataAdapter

net.sf.jasperreports.data.xml.XmlDataAdapterImpl

All Implemented Interfaces:

DataAdapter, XmlDataAdapter

Direct Known Subclasses:

RemoteXmlDataAdapterImpl

public class XmlDataAdapterImpl
extends AbstractDataAdapter
implements XmlDataAdapter

Version:

$Id: XmlDataAdapterImpl.java 6026 2013-03-26 11:49:34Z narcism $

Author:

Teodor Danciu (teodord@users.sourceforge.net)

Constructor Summary

Constructors

Constructor and Description

XmlDataAdapterImpl()

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
getDatePattern()

java.lang.String
getFileName()

java.util.Locale
getLocale()

java.lang.String
getNumberPattern()

java.lang.String
getSelectExpression()

java.util.TimeZone
getTimeZone()

boolean
isNamespaceAware()

boolean
isUseConnection()

void
setDatePattern(java.lang.String datePattern)

void
setFileName(java.lang.String fileName)

void
setLocale(java.util.Locale locale)

void
setNamespaceAware(boolean namespaceAware)

void
setNumberPattern(java.lang.String numberPattern)

void
setSelectExpression(java.lang.String selectExpression)

void
setTimeZone(java.util.TimeZone timeZone)

void
setUseConnection(boolean useConnection)

Methods inherited from class net.sf.jasperreports.data.AbstractDataAdapter

getName, setName

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface net.sf.jasperreports.data.DataAdapter

getName, setName

Constructor Detail

XmlDataAdapterImpl

public XmlDataAdapterImpl()

Method Detail

getFileName

public java.lang.String getFileName()

Specified by:

getFileName in interface XmlDataAdapter

setFileName

public void setFileName(java.lang.String fileName)

Specified by:

setFileName in interface XmlDataAdapter

getSelectExpression

public java.lang.String getSelectExpression()

Specified by:

getSelectExpression in interface XmlDataAdapter

setSelectExpression

public void setSelectExpression(java.lang.String selectExpression)

Specified by:

setSelectExpression in interface XmlDataAdapter

getLocale

public java.util.Locale getLocale()

Specified by:

getLocale in interface XmlDataAdapter

setLocale

public void setLocale(java.util.Locale locale)

Specified by:

setLocale in interface XmlDataAdapter

getDatePattern

public java.lang.String getDatePattern()

Specified by:

getDatePattern in interface XmlDataAdapter

setDatePattern

public void setDatePattern(java.lang.String datePattern)

Specified by:

setDatePattern in interface XmlDataAdapter

getNumberPattern

public java.lang.String getNumberPattern()

Specified by:

getNumberPattern in interface XmlDataAdapter

setNumberPattern

public void setNumberPattern(java.lang.String numberPattern)

Specified by:

setNumberPattern in interface XmlDataAdapter

getTimeZone

public java.util.TimeZone getTimeZone()

Specified by:

getTimeZone in interface XmlDataAdapter

setTimeZone

public void setTimeZone(java.util.TimeZone timeZone)

Specified by:

setTimeZone in interface XmlDataAdapter

isUseConnection

public boolean isUseConnection()

Specified by:

isUseConnection in interface XmlDataAdapter

setUseConnection

public void setUseConnection(boolean useConnection)

Specified by:

setUseConnection in interface XmlDataAdapter

isNamespaceAware

public boolean isNamespaceAware()

Specified by:

isNamespaceAware in interface XmlDataAdapter

setNamespaceAware

public void setNamespaceAware(boolean namespaceAware)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com