text:
/**
 * @output wp-admin/js/edit-comments.js
 */

/* global adminCommentsL10n, thousandsSeparator, list_args, QTags, ajaxurl, wpAjax */
/* global commentReply, theExtraList, theList, setCommentsList */

(function($) {
var getCount, updateCount, updateCountText, updatePending, updateApproved,
	updateHtmlTitle, updateDashboardText, updateInModerationText, adminTitle = document.title,
	isDashboard = $('#dashboard_right_now').length,
	titleDiv, titleRegEx;

	getCount = function(el) {
		var n = parseInt( el.html().replace(/[^0-9]+/g, ''), 10 );
		if ( isNaN(n) ) {
			return 0;
		}
		return n;
	};

	updateCount = function(el, n) {
		var n1 = '';
		if ( isNaN(n) ) {
			return;
		}
		n = n < 1 ? '0' : n.toString();
		if ( n.length > 3 ) {
			while ( n.length > 3 ) {
				n1 = thousandsSeparator + n.substr(n.length - 3) + n1;
				n = n.substr(0, n.length - 3);
			}
			n = n + n1;
		}
		el.html(n);
	};

	updateApproved = function( diff, commentPostId ) {
		var postSelector = '.post-com-count-' + commentPostId,
			noClass = 'comment-count-no-comments',
			approvedClass = 'comment-count-approved',
			approved,
			noComments;

		updateCountText( 'span.approved-count', diff );

		if ( ! commentPostId ) {
			return;
		}

		// cache selectors to not get dupes
		approved = $( 'span.' + approvedClass, postSelector );
		noComments = $( 'span.' + noClass, postSelector );

		approved.each(function() {
			var a = $(this), n = getCount(a) + diff;
			if ( n < 1 )
				n = 0;

			if ( 0 === n ) {
				a.removeClass( approvedClass ).addClass( noClass );
			} else {
				a.addClass( approvedClass ).removeClass( noClass );
			}
			updateCount( a, n );
		});

		noComments.each(function() {
			var a = $(this);
			if ( diff > 0 ) {
				a.removeClass( noClass ).addClass( approvedClass );
			} else {
				a.addClass( noClass ).removeClass( approvedClass );
			}
			updateCount( a, diff );
		});
	};

	updateCountText = function( selector, diff ) {
		$( selector ).each(function() {
			var a = $(this), n = getCount(a) + diff;
			if ( n < 1 ) {
				n = 0;
			}
			updateCount( a, n );
		});
	};

	updateDashboardText = function( response ) {
		if ( ! isDashboard || ! response || ! response.i18n_comments_text ) {
			return;
		}

		$( '.comment-count a', '#dashboard_right_now' ).text( response.i18n_comments_text );
	};

	/**
	 * Updates the "comments in moderation" text across the UI.
	 *
	 * @since 5.2.0
	 *
	 * @param {object} response Ajax response from the server.
	 *
	 * @return {void}
	 */
	updateInModerationText = function( response ) {
		if ( ! response || ! response.i18n_moderation_text ) {
			return;
		}

		// Update the "comment in moderation" text across the UI.
		$( '.comments-in-moderation-text' ).text( response.i18n_moderation_text );
		// Hide the "comment in moderation" text in the Dashboard "At a Glance" widget.
		if ( isDashboard && response.in_moderation ) {
			$( '.comment-mod-count', '#dashboard_right_now' )
				[ response.in_moderation > 0 ? 'removeClass' : 'addClass' ]( 'hidden' );
		}
	};

	updateHtmlTitle = function( diff ) {
		var newTitle, regExMatch, titleCount, commentFrag;

		titleRegEx = titleRegEx || new RegExp( adminCommentsL10n.docTitleCommentsCount.replace( '%s', '\\([0-9' + thousandsSeparator + ']+\\)' ) + '?' );
		// count funcs operate on a $'d element
		titleDiv = titleDiv || $( '
' );
		newTitle = adminTitle;

		commentFrag = titleRegEx.exec( document.title );
		if ( commentFrag ) {
			commentFrag = commentFrag[0];
			titleDiv.html( commentFrag );
			titleCount = getCount( titleDiv ) + diff;
		} else {
			titleDiv.html( 0 );
			titleCount = diff;
		}

		if ( titleCount >= 1 ) {
			updateCount( titleDiv, titleCount );
			regExMatch = titleRegEx.exec( document.title );
			if ( regExMatch ) {
				newTitle = document.title.replace( regExMatch[0], adminCommentsL10n.docTitleCommentsCount.replace( '%s', titleDiv.text() ) + ' ' );
			}
		} else {
			regExMatch = titleRegEx.exec( newTitle );
			if ( regExMatch ) {
				newTitle = newTitle.replace( regExMatch[0], adminCommentsL10n.docTitleComments );
			}
		}
		document.title = newTitle;
	};

	updatePending = function( diff, commentPostId ) {
		var postSelector = '.post-com-count-' + commentPostId,
			noClass = 'comment-count-no-pending',
			noParentClass = 'post-com-count-no-pending',
			pendingClass = 'comment-count-pending',
			pending,
			noPending;

		if ( ! isDashboard ) {
			updateHtmlTitle( diff );
		}

		$( 'span.pending-count' ).each(function() {
			var a = $(this), n = getCount(a) + diff;
			if ( n < 1 )
				n = 0;
			a.closest('.awaiting-mod')[ 0 === n ? 'addClass' : 'removeClass' ]('count-0');
			updateCount( a, n );
		});

		if ( ! commentPostId ) {
			return;
		}

		// cache selectors to not get dupes
		pending = $( 'span.' + pendingClass, postSelector );
		noPending = $( 'span.' + noClass, postSelector );

		pending.each(function() {
			var a = $(this), n = getCount(a) + diff;
			if ( n < 1 )
				n = 0;

			if ( 0 === n ) {
				a.parent().addClass( noParentClass );
				a.removeClass( pendingClass ).addClass( noClass );
			} else {
				a.parent().removeClass( noParentClass );
				a.addClass( pendingClass ).removeClass( noClass );
			}
			updateCount( a, n );
		});

		noPending.each(function() {
			var a = $(this);
			if ( diff > 0 ) {
				a.parent().removeClass( noParentClass );
				a.removeClass( noClass ).addClass( pendingClass );
			} else {
				a.parent().addClass( noParentClass );
				a.addClass( noClass ).removeClass( pendingClass );
			}
			updateCount( a, diff );
		});
	};

window.setCommentsList = function() {
	var totalInput, perPageInput, pageInput, dimAfter, delBefore, updateTotalCount, delAfter, refillTheExtraList, diff,
		lastConfidentTime = 0;

	totalInput = $('input[name="_total"]', '#comments-form');
	perPageInput = $('input[name="_per_page"]', '#comments-form');
	pageInput = $('input[name="_page"]', '#comments-form');

	// Updates the current total (stored in the _total input)
	updateTotalCount = function( total, time, setConfidentTime ) {
		if ( time < lastConfidentTime )
			return;

		if ( setConfidentTime )
			lastConfidentTime = time;

		totalInput.val( total.toString() );
	};

	// this fires when viewing "All"
	dimAfter = function( r, settings ) {
		var editRow, replyID, replyButton, response,
			c = $( '#' + settings.element );

		if ( true !== settings.parsed ) {
			response = settings.parsed.responses[0];
		}

		editRow = $('#replyrow');
		replyID = $('#comment_ID', editRow).val();
		replyButton = $('#replybtn', editRow);

		if ( c.is('.unapproved') ) {
			if ( settings.data.id == replyID )
				replyButton.text(adminCommentsL10n.replyApprove);

			c.find( '.row-actions span.view' ).addClass( 'hidden' ).end()
				.find( 'div.comment_status' ).html( '0' );

		} else {
			if ( settings.data.id == replyID )
				replyButton.text(adminCommentsL10n.reply);

			c.find( '.row-actions span.view' ).removeClass( 'hidden' ).end()
				.find( 'div.comment_status' ).html( '1' );
		}

		diff = $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1;
		if ( response ) {
			updateDashboardText( response.supplemental );
			updateInModerationText( response.supplemental );
			updatePending( diff, response.supplemental.postId );
			updateApproved( -1 * diff, response.supplemental.postId );
		} else {
			updatePending( diff );
			updateApproved( -1 * diff  );
		}
	};

	// Send current total, page, per_page and url
	delBefore = function( settings, list ) {
		var note, id, el, n, h, a, author,
			action = false,
			wpListsData = $( settings.target ).attr( 'data-wp-lists' );

		settings.data._total = totalInput.val() || 0;
		settings.data._per_page = perPageInput.val() || 0;
		settings.data._page = pageInput.val() || 0;
		settings.data._url = document.location.href;
		settings.data.comment_status = $('input[name="comment_status"]', '#comments-form').val();

		if ( wpListsData.indexOf(':trash=1') != -1 )
			action = 'trash';
		else if ( wpListsData.indexOf(':spam=1') != -1 )
			action = 'spam';

		if ( action ) {
			id = wpListsData.replace(/.*?comment-([0-9]+).*/, '$1');
			el = $('#comment-' + id);
			note = $('#' + action + '-undo-holder').html();

			el.find('.check-column :checkbox').prop('checked', false); // Uncheck the row so as not to be affected by Bulk Edits.

			if ( el.siblings('#replyrow').length && commentReply.cid == id )
				commentReply.close();

			if ( el.is('tr') ) {
				n = el.children(':visible').length;
				author = $('.author strong', el).text();
				h = $('
' + note + '
');
			} else {
				author = $('.comment-author', el).text();
				h = $('
' + note + '
');
			}

			el.before(h);

			$('strong', '#undo-' + id).text(author);
			a = $('.undo a', '#undo-' + id);
			a.attr('href', 'comment.php?action=un' + action + 'comment&c=' + id + '&_wpnonce=' + settings.data._ajax_nonce);
			a.attr('data-wp-lists', 'delete:the-comment-list:comment-' + id + '::un' + action + '=1');
			a.attr('class', 'vim-z vim-destructive aria-button-if-js');
			$('.avatar', el).first().clone().prependTo('#undo-' + id + ' .' + action + '-undo-inside');

			a.click(function( e ){
				e.preventDefault();
				e.stopPropagation(); // ticket #35904
				list.wpList.del(this);
				$('#undo-' + id).css( {backgroundColor:'#ceb'} ).fadeOut(350, function(){
					$(this).remove();
					$('#comment-' + id).css('backgroundColor', '').fadeIn(300, function(){ $(this).show(); });
				});
			});
		}

		return settings;
	};

	// In admin-ajax.php, we send back the unix time stamp instead of 1 on success
	delAfter = function( r, settings ) {
		var total_items_i18n, total, animated, animatedCallback,
			response = true === settings.parsed ? {} : settings.parsed.responses[0],
			commentStatus = true === settings.parsed ? '' : response.supplemental.status,
			commentPostId = true === settings.parsed ? '' : response.supplemental.postId,
			newTotal = true === settings.parsed ? '' : response.supplemental,

			targetParent = $( settings.target ).parent(),
			commentRow = $('#' + settings.element),

			spamDiff, trashDiff, pendingDiff, approvedDiff,

			/*
			 * As `wpList` toggles only the `unapproved` class, the approved comment
			 * rows can have both the `approved` and `unapproved` classes.
			 */
			approved = commentRow.hasClass( 'approved' ) && ! commentRow.hasClass( 'unapproved' ),
			unapproved = commentRow.hasClass( 'unapproved' ),
			spammed = commentRow.hasClass( 'spam' ),
			trashed = commentRow.hasClass( 'trash' ),
			undoing = false; // ticket #35904

		updateDashboardText( newTotal );
		updateInModerationText( newTotal );

		// the order of these checks is important
		// .unspam can also have .approve or .unapprove
		// .untrash can also have .approve or .unapprove

		if ( targetParent.is( 'span.undo' ) ) {
			// the comment was spammed
			if ( targetParent.hasClass( 'unspam' ) ) {
				spamDiff = -1;

				if ( 'trash' === commentStatus ) {
					trashDiff = 1;
				} else if ( '1' === commentStatus ) {
					approvedDiff = 1;
				} else if ( '0' === commentStatus ) {
					pendingDiff = 1;
				}

			// the comment was trashed
			} else if ( targetParent.hasClass( 'untrash' ) ) {
				trashDiff = -1;

				if ( 'spam' === commentStatus ) {
					spamDiff = 1;
				} else if ( '1' === commentStatus ) {
					approvedDiff = 1;
				} else if ( '0' === commentStatus ) {
					pendingDiff = 1;
				}
			}

			undoing = true;

		// user clicked "Spam"
		} else if ( targetParent.is( 'span.spam' ) ) {
			// the comment is currently approved
			if ( approved ) {
				approvedDiff = -1;
			// the comment is currently pending
			} else if ( unapproved ) {
				pendingDiff = -1;
			// the comment was in the trash
			} else if ( trashed ) {
				trashDiff = -1;
			}
			// you can't spam an item on the spam screen
			spamDiff = 1;

		// user clicked "Unspam"
		} else if ( targetParent.is( 'span.unspam' ) ) {
			if ( approved ) {
				pendingDiff = 1;
			} else if ( unapproved ) {
				approvedDiff = 1;
			} else if ( trashed ) {
				// the comment was previously approved
				if ( targetParent.hasClass( 'approve' ) ) {
					approvedDiff = 1;
				// the comment was previously pending
				} else if ( targetParent.hasClass( 'unapprove' ) ) {
					pendingDiff = 1;
				}
			} else if ( spammed ) {
				if ( targetParent.hasClass( 'approve' ) ) {
					approvedDiff = 1;

				} else if ( targetParent.hasClass( 'unapprove' ) ) {
					pendingDiff = 1;
				}
			}
			// you can Unspam an item on the spam screen
			spamDiff = -1;

		// user clicked "Trash"
		} else if ( targetParent.is( 'span.trash' ) ) {
			if ( approved ) {
				approvedDiff = -1;
			} else if ( unapproved ) {
				pendingDiff = -1;
			// the comment was in the spam queue
			} else if ( spammed ) {
				spamDiff = -1;
			}
			// you can't trash an item on the trash screen
			trashDiff = 1;

		// user clicked "Restore"
		} else if ( targetParent.is( 'span.untrash' ) ) {
			if ( approved ) {
				pendingDiff = 1;
			} else if ( unapproved ) {
				approvedDiff = 1;
			} else if ( trashed ) {
				if ( targetParent.hasClass( 'approve' ) ) {
					approvedDiff = 1;
				} else if ( targetParent.hasClass( 'unapprove' ) ) {
					pendingDiff = 1;
				}
			}
			// you can't go from trash to spam
			// you can untrash on the trash screen
			trashDiff = -1;

		// User clicked "Approve"
		} else if ( targetParent.is( 'span.approve:not(.unspam):not(.untrash)' ) ) {
			approvedDiff = 1;
			pendingDiff = -1;

		// User clicked "Unapprove"
		} else if ( targetParent.is( 'span.unapprove:not(.unspam):not(.untrash)' ) ) {
			approvedDiff = -1;
			pendingDiff = 1;

		// User clicked "Delete Permanently"
		} else if ( targetParent.is( 'span.delete' ) ) {
			if ( spammed ) {
				spamDiff = -1;
			} else if ( trashed ) {
				trashDiff = -1;
			}
		}

		if ( pendingDiff ) {
			updatePending( pendingDiff, commentPostId );
			updateCountText( 'span.all-count', pendingDiff );
		}

		if ( approvedDiff ) {
			updateApproved( approvedDiff, commentPostId );
			updateCountText( 'span.all-count', approvedDiff );
		}

		if ( spamDiff ) {
			updateCountText( 'span.spam-count', spamDiff );
		}

		if ( trashDiff ) {
			updateCountText( 'span.trash-count', trashDiff );
		}

		if (
			( ( 'trash' === settings.data.comment_status ) && !getCount( $( 'span.trash-count' ) ) ) ||
			( ( 'spam' === settings.data.comment_status ) && !getCount( $( 'span.spam-count' ) ) )
		) {
			$( '#delete_all' ).hide();
		}

		if ( ! isDashboard ) {
			total = totalInput.val() ? parseInt( totalInput.val(), 10 ) : 0;
			if ( $(settings.target).parent().is('span.undo') )
				total++;
			else
				total--;

			if ( total < 0 )
				total = 0;

			if ( 'object' === typeof r ) {
				if ( response.supplemental.total_items_i18n && lastConfidentTime < response.supplemental.time ) {
					total_items_i18n = response.supplemental.total_items_i18n || '';
					if ( total_items_i18n ) {
						$('.displaying-num').text( total_items_i18n );
						$('.total-pages').text( response.supplemental.total_pages_i18n );
						$('.tablenav-pages').find('.next-page, .last-page').toggleClass('disabled', response.supplemental.total_pages == $('.current-page').val());
					}
					updateTotalCount( total, response.supplemental.time, true );
				} else if ( response.supplemental.time ) {
					updateTotalCount( total, response.supplemental.time, false );
				}
			} else {
				updateTotalCount( total, r, false );
			}
		}

		if ( ! theExtraList || theExtraList.length === 0 || theExtraList.children().length === 0 || undoing ) {
			return;
		}

		theList.get(0).wpList.add( theExtraList.children( ':eq(0):not(.no-items)' ).remove().clone() );

		refillTheExtraList();

		animated = $( ':animated', '#the-comment-list' );
		animatedCallback = function() {
			if ( ! $( '#the-comment-list tr:visible' ).length ) {
				theList.get(0).wpList.add( theExtraList.find( '.no-items' ).clone() );
			}
		};

		if ( animated.length ) {
			animated.promise().done( animatedCallback );
		} else {
			animatedCallback();
		}
	};

	refillTheExtraList = function(ev) {
		var args = $.query.get(), total_pages = $('.total-pages').text(), per_page = $('input[name="_per_page"]', '#comments-form').val();

		if (! args.paged)
			args.paged = 1;

		if (args.paged > total_pages) {
			return;
		}

		if (ev) {
			theExtraList.empty();
			args.number = Math.min(8, per_page); // see WP_Comments_List_Table::prepare_items() @ class-wp-comments-list-table.php
		} else {
			args.number = 1;
			args.offset = Math.min(8, per_page) - 1; // fetch only the next item on the extra list
		}

		args.no_placeholder = true;

		args.paged ++;

		// $.query.get() needs some correction to be sent into an ajax request
		if ( true === args.comment_type )
			args.comment_type = '';

		args = $.extend(args, {
			'action': 'fetch-list',
			'list_args': list_args,
			'_ajax_fetch_list_nonce': $('#_ajax_fetch_list_nonce').val()
		});

		$.ajax({
			url: ajaxurl,
			global: false,
			dataType: 'json',
			data: args,
			success: function(response) {
				theExtraList.get(0).wpList.add( response.rows );
			}
		});
	};

	window.theExtraList = $('#the-extra-comment-list').wpList( { alt: '', delColor: 'none', addColor: 'none' } );
	window.theList = $('#the-comment-list').wpList( { alt: '', delBefore: delBefore, dimAfter: dimAfter, delAfter: delAfter, addColor: 'none' } )
		.bind('wpListDelEnd', function(e, s){
			var wpListsData = $(s.target).attr('data-wp-lists'), id = s.element.replace(/[^0-9]+/g, '');

			if ( wpListsData.indexOf(':trash=1') != -1 || wpListsData.indexOf(':spam=1') != -1 )
				$('#undo-' + id).fadeIn(300, function(){ $(this).show(); });
		});
};

window.commentReply = {
	cid : '',
	act : '',
	originalContent : '',

	init : function() {
		var row = $('#replyrow');

		$( '.cancel', row ).click( function() { return commentReply.revert(); } );
		$( '.save', row ).click( function() { return commentReply.send(); } );
		$( 'input#author-name, input#author-email, input#author-url', row ).keypress( function( e ) {
			if ( e.which == 13 ) {
				commentReply.send();
				e.preventDefault();
				return false;
			}
		});

		// add events
		$('#the-comment-list .column-comment > p').dblclick(function(){
			commentReply.toggle($(this).parent());
		});

		$('#doaction, #doaction2, #post-query-submit').click(function(){
			if ( $('#the-comment-list #replyrow').length > 0 )
				commentReply.close();
		});

		this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || '';
	},

	addEvents : function(r) {
		r.each(function() {
			$(this).find('.column-comment > p').dblclick(function(){
				commentReply.toggle($(this).parent());
			});
		});
	},

	toggle : function(el) {
		if ( 'none' !== $( el ).css( 'display' ) && ( $( '#replyrow' ).parent().is('#com-reply') || window.confirm( adminCommentsL10n.warnQuickEdit ) ) ) {
			$( el ).find( 'a.vim-q' ).click();
		}
	},

	revert : function() {

		if ( $('#the-comment-list #replyrow').length < 1 )
			return false;

		$('#replyrow').fadeOut('fast', function(){
			commentReply.close();
		});
	},

	close : function() {
		var commentRow = $(),
			replyRow = $( '#replyrow' );

		// replyrow is not showing?
		if ( replyRow.parent().is( '#com-reply' ) ) {
			return;
		}

		if ( this.cid ) {
			commentRow = $( '#comment-' + this.cid );
		}

		/*
		 * When closing the Quick Edit form, show the comment row and move focus
		 * back to the Quick Edit button.
		 */
		if ( 'edit-comment' === this.act ) {
			commentRow.fadeIn( 300, function() {
				commentRow
					.show()
					.find( '.vim-q' )
						.attr( 'aria-expanded', 'false' )
						.focus();
			} ).css( 'backgroundColor', '' );
		}

		// When closing the Reply form, move focus back to the Reply button.
		if ( 'replyto-comment' === this.act ) {
			commentRow.find( '.vim-r' )
				.attr( 'aria-expanded', 'false' )
				.focus();
		}

		// reset the Quicktags buttons
		if ( typeof QTags != 'undefined' )
			QTags.closeAllTags('replycontent');

		$('#add-new-comment').css('display', '');

		replyRow.hide();
		$( '#com-reply' ).append( replyRow );
		$('#replycontent').css('height', '').val('');
		$('#edithead input').val('');
		$( '.notice-error', replyRow )
			.addClass( 'hidden' )
			.find( '.error' ).empty();
		$( '.spinner', replyRow ).removeClass( 'is-active' );

		this.cid = '';
		this.originalContent = '';
	},

	open : function(comment_id, post_id, action) {
		var editRow, rowData, act, replyButton, editHeight,
			t = this,
			c = $('#comment-' + comment_id),
			h = c.height(),
			colspanVal = 0;

		if ( ! this.discardCommentChanges() ) {
			return false;
		}

		t.close();
		t.cid = comment_id;

		editRow = $('#replyrow');
		rowData = $('#inline-'+comment_id);
		action = action || 'replyto';
		act = 'edit' == action ? 'edit' : 'replyto';
		act = t.act = act + '-comment';
		t.originalContent = $('textarea.comment', rowData).val();
		colspanVal = $( '> th:visible, > td:visible', c ).length;

		// Make sure it's actually a table and there's a `colspan` value to apply.
		if ( editRow.hasClass( 'inline-edit-row' ) && 0 !== colspanVal ) {
			$( 'td', editRow ).attr( 'colspan', colspanVal );
		}

		$('#action', editRow).val(act);
		$('#comment_post_ID', editRow).val(post_id);
		$('#comment_ID', editRow).val(comment_id);

		if ( action == 'edit' ) {
			$( '#author-name', editRow ).val( $( 'div.author', rowData ).text() );
			$('#author-email', editRow).val( $('div.author-email', rowData).text() );
			$('#author-url', editRow).val( $('div.author-url', rowData).text() );
			$('#status', editRow).val( $('div.comment_status', rowData).text() );
			$('#replycontent', editRow).val( $('textarea.comment', rowData).val() );
			$( '#edithead, #editlegend, #savebtn', editRow ).show();
			$('#replyhead, #replybtn, #addhead, #addbtn', editRow).hide();

			if ( h > 120 ) {
				// Limit the maximum height when editing very long comments to make it more manageable.
				// The textarea is resizable in most browsers, so the user can adjust it if needed.
				editHeight = h > 500 ? 500 : h;
				$('#replycontent', editRow).css('height', editHeight + 'px');
			}

			c.after( editRow ).fadeOut('fast', function(){
				$('#replyrow').fadeIn(300, function(){ $(this).show(); });
			});
		} else if ( action == 'add' ) {
			$('#addhead, #addbtn', editRow).show();
			$( '#replyhead, #replybtn, #edithead, #editlegend, #savebtn', editRow ) .hide();
			$('#the-comment-list').prepend(editRow);
			$('#replyrow').fadeIn(300);
		} else {
			replyButton = $('#replybtn', editRow);
			$( '#edithead, #editlegend, #savebtn, #addhead, #addbtn', editRow ).hide();
			$('#replyhead, #replybtn', editRow).show();
			c.after(editRow);

			if ( c.hasClass('unapproved') ) {
				replyButton.text(adminCommentsL10n.replyApprove);
			} else {
				replyButton.text(adminCommentsL10n.reply);
			}

			$('#replyrow').fadeIn(300, function(){ $(this).show(); });
		}

		setTimeout(function() {
			var rtop, rbottom, scrollTop, vp, scrollBottom;

			rtop = $('#replyrow').offset().top;
			rbottom = rtop + $('#replyrow').height();
			scrollTop = window.pageYOffset || document.documentElement.scrollTop;
			vp = document.documentElement.clientHeight || window.innerHeight || 0;
			scrollBottom = scrollTop + vp;

			if ( scrollBottom - 20 < rbottom )
				window.scroll(0, rbottom - vp + 35);
			else if ( rtop - 20 < scrollTop )
				window.scroll(0, rtop - 35);

			$('#replycontent').focus().keyup(function(e){
				if ( e.which == 27 )
					commentReply.revert(); // close on Escape
			});
		}, 600);

		return false;
	},

	send : function() {
		var post = {},
			$errorNotice = $( '#replysubmit .error-notice' );

		$errorNotice.addClass( 'hidden' );
		$( '#replysubmit .spinner' ).addClass( 'is-active' );

		$('#replyrow input').not(':button').each(function() {
			var t = $(this);
			post[ t.attr('name') ] = t.val();
		});

		post.content = $('#replycontent').val();
		post.id = post.comment_post_ID;
		post.comments_listing = this.comments_listing;
		post.p = $('[name="p"]').val();

		if ( $('#comment-' + $('#comment_ID').val()).hasClass('unapproved') )
			post.approve_parent = 1;

		$.ajax({
			type : 'POST',
			url : ajaxurl,
			data : post,
			success : function(x) { commentReply.show(x); },
			error : function(r) { commentReply.error(r); }
		});
	},

	show : function(xml) {
		var t = this, r, c, id, bg, pid;

		if ( typeof(xml) == 'string' ) {
			t.error({'responseText': xml});
			return false;
		}

		r = wpAjax.parseAjaxResponse(xml);
		if ( r.errors ) {
			t.error({'responseText': wpAjax.broken});
			return false;
		}

		t.revert();

		r = r.responses[0];
		id = '#comment-' + r.id;

		if ( 'edit-comment' == t.act )
			$(id).remove();

		if ( r.supplemental.parent_approved ) {
			pid = $('#comment-' + r.supplemental.parent_approved);
			updatePending( -1, r.supplemental.parent_post_id );

			if ( this.comments_listing == 'moderated' ) {
				pid.animate( { 'backgroundColor':'#CCEEBB' }, 400, function(){
					pid.fadeOut();
				});
				return;
			}
		}

		if ( r.supplemental.i18n_comments_text ) {
			updateDashboardText( r.supplemental );
			updateInModerationText( r.supplemental );
			updateApproved( 1, r.supplemental.parent_post_id );
			updateCountText( 'span.all-count', 1 );
		}

		c = $.trim(r.data); // Trim leading whitespaces
		$(c).hide();
		$('#replyrow').after(c);

		id = $(id);
		t.addEvents(id);
		bg = id.hasClass('unapproved') ? '#FFFFE0' : id.closest('.widefat, .postbox').css('backgroundColor');

		id.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
			.animate( { 'backgroundColor': bg }, 300, function() {
				if ( pid && pid.length ) {
					pid.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
						.animate( { 'backgroundColor': bg }, 300 )
						.removeClass('unapproved').addClass('approved')
						.find('div.comment_status').html('1');
				}
			});

	},

	error : function(r) {
		var er = r.statusText,
			$errorNotice = $( '#replysubmit .notice-error' ),
			$error = $errorNotice.find( '.error' );

		$( '#replysubmit .spinner' ).removeClass( 'is-active' );

		if ( r.responseText )
			er = r.responseText.replace( /<.[^<>]*?>/g, '' );

		if ( er ) {
			$errorNotice.removeClass( 'hidden' );
			$error.html( er );
		}
	},

	addcomment: function(post_id) {
		var t = this;

		$('#add-new-comment').fadeOut(200, function(){
			t.open(0, post_id, 'add');
			$('table.comments-box').css('display', '');
			$('#no-comments').remove();
		});
	},

	/**
	 * Alert the user if they have unsaved changes on a comment that will be
	 * lost if they proceed.
	 *
	 * @returns {boolean}
	 */
	discardCommentChanges: function() {
		var editRow = $( '#replyrow' );

		if  ( this.originalContent === $( '#replycontent', editRow ).val() ) {
			return true;
		}

		return window.confirm( adminCommentsL10n.warnCommentChanges );
	}
};

$(document).ready(function(){
	var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk;

	setCommentsList();
	commentReply.init();

	$(document).on( 'click', 'span.delete a.delete', function( e ) {
		e.preventDefault();
	});

	if ( typeof $.table_hotkeys != 'undefined' ) {
		make_hotkeys_redirect = function(which) {
			return function() {
				var first_last, l;

				first_last = 'next' == which? 'first' : 'last';
				l = $('.tablenav-pages .'+which+'-page:not(.disabled)');
				if (l.length)
					window.location = l[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g, '')+'&hotkeys_highlight_'+first_last+'=1';
			};
		};

		edit_comment = function(event, current_row) {
			window.location = $('span.edit a', current_row).attr('href');
		};

		toggle_all = function() {
			$('#cb-select-all-1').data( 'wp-toggle', 1 ).trigger( 'click' ).removeData( 'wp-toggle' );
		};

		make_bulk = function(value) {
			return function() {
				var scope = $('select[name="action"]');
				$('option[value="' + value + '"]', scope).prop('selected', true);
				$('#doaction').click();
			};
		};

		$.table_hotkeys(
			$('table.widefat'),
			[
				'a', 'u', 's', 'd', 'r', 'q', 'z',
				['e', edit_comment],
				['shift+x', toggle_all],
				['shift+a', make_bulk('approve')],
				['shift+s', make_bulk('spam')],
				['shift+d', make_bulk('delete')],
				['shift+t', make_bulk('trash')],
				['shift+z', make_bulk('untrash')],
				['shift+u', make_bulk('unapprove')]
			],
			{
				highlight_first: adminCommentsL10n.hotkeys_highlight_first,
				highlight_last: adminCommentsL10n.hotkeys_highlight_last,
				prev_page_link_cb: make_hotkeys_redirect('prev'),
				next_page_link_cb: make_hotkeys_redirect('next'),
				hotkeys_opts: {
					disableInInput: true,
					type: 'keypress',
					noDisable: '.check-column input[type="checkbox"]'
				},
				cycle_expr: '#the-comment-list tr',
				start_row_index: 0
			}
		);
	}

	// Quick Edit and Reply have an inline comment editor.
	$( '#the-comment-list' ).on( 'click', '.comment-inline', function() {
		var $el = $( this ),
			action = 'replyto';

		if ( 'undefined' !== typeof $el.data( 'action' ) ) {
			action = $el.data( 'action' );
		}

		$( this ).attr( 'aria-expanded', 'true' );
		commentReply.open( $el.data( 'commentId' ), $el.data( 'postId' ), action );
	} );
});

})(jQuery);


text:
<?php

class Google_Service_Apigee_GoogleCloudApigeeV1SchemaSchemaElement extends Google_Model
{
  public $name;
  protected $propertiesType = 'Google_Service_Apigee_GoogleCloudApigeeV1SchemaSchemaProperty';
  protected $propertiesDataType = '';

  public function setName($name)
  {
    $this->name = $name;
  }
  public function getName()
  {
    return $this->name;
  }
  /**
   * @param Google_Service_Apigee_GoogleCloudApigeeV1SchemaSchemaProperty
   */
  public function setProperties(Google_Service_Apigee_GoogleCloudApigeeV1SchemaSchemaProperty $properties)
  {
    $this->properties = $properties;
  }
  /**
   * @return Google_Service_Apigee_GoogleCloudApigeeV1SchemaSchemaProperty
   */
  public function getProperties()
  {
    return $this->properties;
  }
}

redpajama_set_name: RedPajamaGithub


text:
Playing with [khttp](https://github.com/jkcclemens/khttp)

#### Integrating

Gradle,
```
repositories {
    maven { url 'https://jitpack.io' }
}
```
```
compile 'com.github.jkcclemens:khttp:0.1.0'
```

Maven,
```
<repositories>
    <repository>
	    <id>jitpack.io</id>
		<url>https://jitpack.io</url>
	</repository>
</repositories>
```
```
<dependency>
    <groupId>com.github.jkcclemens</groupId>
	<artifactId>khttp</artifactId>
	<version>0.1.0</version>
</dependency>
```

Impressive code,
```kotlin
val params = mapOf("page" to 2.toString())  // Parameters
val response = get("https://reqres.in/api/users", params = params)  // Send get request
val resultAsJson = response.jsonObject

for ((key, value) in response.headers) {
    println("$key == $value")
}

println(resultAsJson.getInt("per_page"))
println(resultAsJson.getInt("total"))

val data = resultAsJson.getJSONArray("data")
for (it in data) {
    println(it)
}

for (it in data) {
    val obj = it as JSONObject
    println(obj.getString("first_name"))
    println(obj.getString("last_name"))
    println(obj.getString("avatar"))
    println(obj.getInt("id"))
}

// Multipart file parameters
val files = listOf(File("file_name_with_path.extension").fileLike())
val reqPost = post("url_here", files = files)   // Sending multipart request
```

`params` are the parameters which will be attached to request.
For `get` method like ?key=value&key2=value2.....
It will take care of processing for other methods too.
Too easy, isn't it ? ;)

You can convert body directly to json body. Oh got rid of shitty stuffs used to do !!!

[Go Back](https://github.com/s4kibs4mi/KotlinSchool/blob/master/src/main/resources/tutorials/en/index.md)
###### Brought to you by Sakib Sami


text:
/*
 *  Include file space.h
 */
char	imagename[60];           /* name of input image file            */
char	out_file[60];            /* basename for output files           */
char	weight_file[60];         /* name of weight file                 */
char	id_file[60];             /* name of patch ID image              */
char	desc_file[60];           /* name of class descriptor file       */
char	file1[60];               /* name of basename.patch file         */
char	file2[60];               /* name of basename.class file         */
char	file3[60];               /* name of basename.land file          */
char	file4[60];               /* name of basename.full file          */
char	contrast_indices;        /* flag; calculate contrast indices    */
char	proximity;               /* flag; calculate proximity indices   */
char	id_image;                /* flag; ID image input                */
char	descriptors;             /* flag; descriptor file input         */
char	land_border;             /* flag; landscape border exists       */
char	do_nndist;               /* flag; calc nearest neigh indices    */
char	patch_stats;             /* flag; output patch statistics       */
char	class_stats;             /* flag; output class statistics       */
char	use_diags;               /* flag; use diagonals in patch finding*/
char	do_patchrich;            /* flag; calculate patch richness      */
char	*check;                  /* used in patch finding routine       */
char	**name;                  /* char descriptor for each class      */
char	bcode;                   /* flag; int, ext background present   */

short xpos[8] = {0,1,0,-1,1,1,-1,-1}; /* X,Y pos of 8 neighbors         */
short ypos[8] = {-1,0,1,0,-1,1,1,-1}; /* surrounding a cell             */

short	*image;                  /* pointer to input image data         */
short	*id;                     /* pointer to ID image                 */
short	*stackx;                 /* column location of patch cells      */
short	*stacky;                 /* row location of patch cells         */
short	*patchtype;              /* classes that exist in the landscape */
short	*patchid;                /* ID of each patch in the landscape   */
short	data_type;               /* file type of input image            */
short   background;              /* background value                    */
short	num_rows;                /* number of rows in input image       */
short	num_cols;                /* number of columns in input image    */
short	min_class;               /* min class (patch) value in image    */
short	max_class;               /* max class (patch) value in image    */
short	max_num_classes;         /* max class value possible            */
short	min_dist;                /* dist from edge in cells for corearea*/
short	min_wt;                  /* min class value in weight file      */
short	max_wt;                  /* max class value in weight file      */
short	num_wt;                  /* #classes in weight file             */

int	MAX_CLASSES;             /* max class value in image plus 1     */
int	MAX_PATCHES;             /* #patches in the landscape           */
int	MAX_PATCH_SIZE;          /* size of largest patch in landscape  */
int	NUM_CLASSES;             /* #classes in the landscape           */
int	total_num_classes;       /* #classes, including landscape border*/
int	num_patches;             /* #patches in a class                 */
int	total_patches;           /* #patches in the landscape           */
int	total_nn;                /* #patches in landscape with neighbors*/
int	boundary;                /* length of the landscape boundary    */
int	total_size;              /* total size of image in cells        */
int	total_core_patches;      /* total #corearea patches in landscape*/
int	total_num_patches;       /* total #patches in landscape         */
int	*edge;                   /* len of patch types bordering a patch*/
int	*edgetype;               /* len of patch types bordering a patch*/
int	*ext_npts;               /* #exterior cells for each patch      */
int	*core_area_patches;      /* #corearea patches for each patch    */

float	*perimeter;              /* perimeter of each patch             */
float	*core_area_index;        /* core area index of each patch       */
float	*shape;                  /* shape index of each patch           */
float	*fractal;                /* fractal dimension of each patch     */
float	*class_area;             /* area of the class being evaluated   */
float	*contrast;               /* weights of each combo of classes    */
float	*edge_contrast;          /* weighted edge len of each patch     */
float	*prox;                   /* proximity index for each patch      */
float	cellsize;                /* size of cells in image (in meters)  */
float	extra_contrast;          /* contrast of patch types in border   */
float	edge_dist;               /* distance from edge for corearea (m) */
float	search_radius;           /* search radius for proximity index(m)*/
float	total_maxarea;           /* area of largest patch in landscape  */
float	total_shape;             /* shape index for the landscape       */
float	total_aw_shape;          /* area-wt shape index for landscape   */
float	total_fract;             /* fractal dimension for the landscape */
float	total_aw_fract;          /* area-wt fractal dim for landscape   */
float	total_core_index;        /* core area index for landscape       */
float	total_contrast;          /* total edge contrast in landscape    */
float	total_aw_contrast;       /* area-wt edge contrast in landscape  */
float	total_contrast_edge;     /* total weighted edge len in landscape*/
float	total_prox;              /* mean proximity index for landscape  */
float	edcon;                   /* total contrast of border patches    */
float	bound_wght;              /* default weight to apply to all edges*/
float	all_edge;                /* edge length - includes all edge     */
float	true_edge;               /* edge length - true edges only       */
float	lshape_edge;             /* edge length for landscape shape     */
float	iji_edge;                /* edge length for inter/jux index     */

double	*area;                   /* area of each patch in a class       */
double	*core_area;              /* core area of each patch in a class  */
double	*near_neigh_dist;        /* nearest neigh dist for each patch   */
double	*xx;                     /* array of log(perimeter) for DLFD    */
double	*yy;                     /* array of log(area) for DLFD         */
double	classarea;               /* total class area                    */
double	total_area;              /* area of the landscape               */
double	total_area_sq;           /* landscape area squared              */
double	total_core_area;         /* total core area in the landscape    */
double	total_core_sq;           /* landscape core area squared         */
double	total_nndist;            /* sum of near neigh dist in landscape */
double	total_nndist_sq;         /* nearest neighbor distance squared   */


text:
package com.intellij.plugins.haxe.model;

import com.intellij.plugins.haxe.lang.psi.*;
import com.intellij.plugins.haxe.model.type.HaxeTypeResolver;
import com.intellij.plugins.haxe.model.type.ResultHolder;
import com.intellij.plugins.haxe.util.UsefulPsiTreeUtil;

public class HaxeLocalVarModel extends HaxeMemberModel {

  private HaxeLocalVarDeclaration element;

  public HaxeLocalVarModel(HaxeLocalVarDeclaration element) {
    super(element, element, UsefulPsiTreeUtil.getChild(element, HaxeLocalVarDeclarationPart.class));
    this.element = element;
  }

  @Override
  public HaxeClassModel getDeclaringClass() {
    final HaxeClass hClass = (HaxeClass)((HaxeLocalVarDeclaration)element).getContainingClass();
    return hClass != null ? hClass.getModel() : null;
  }
  @Override
  public ResultHolder getResultType() {
    final HaxeLocalVarDeclarationPart part = UsefulPsiTreeUtil.getChild(element, HaxeLocalVarDeclarationPart.class);
    final HaxeTypeTag typeTag = part != null ? part.getTypeTag() : null;
    final HaxeTypeOrAnonymous type = typeTag != null ? typeTag.getTypeOrAnonymous() : null;
    return type != null ? HaxeTypeResolver.getTypeFromTypeOrAnonymous(type) : null;

  }
  @Override
  public String getPresentableText(HaxeMethodContext context) {
    final ResultHolder type = getResultType();
    return type == null ? this.getName() : this.getName() + ":" + type;
  }

}


text:
/**
 * Logistic regression example by using batch gradient descent.
 */
package ml.shifu.guagua.example.lr;


text:
@interface NKFColor (AppColors)

// lists of primary colors to use for the app that can be easily referenced across the entire app
+ (NKFColor *)appColor;
+ (NKFColor *)appColor1;
+ (NKFColor *)appColor2;
+ (NKFColor *)appColor3;
+ (NKFColor *)appColor4;
+ (NSArray *)appColors;

+ (NKFColor *)redAppColor;
+ (NKFColor *)greenAppColor;
+ (NKFColor *)blueAppColor;
+ (NKFColor *)yellowAppColor;
+ (NKFColor *)magentaAppColor;
+ (NKFColor *)cyanAppColor;
+ (NKFColor *)blackAppColor;
+ (NKFColor *)whiteAppColor;

// user colors
- (void)saveColorNamed:(NSString *)name;
+ (void)saveColor:(NKFColor *)color named:(NSString *)name;
+ (void)deleteColorWithName:(NSString *)name;
+ (NSDictionary *)userColors;

@end


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_supermap_data_GeoRegionNative */

#ifndef _Included_com_supermap_data_GeoRegionNative
#define _Included_com_supermap_data_GeoRegionNative
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_New
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL Java_com_supermap_data_GeoRegionNative_jni_1New
  (JNIEnv *, jclass);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_Delete
 * Signature: (J)V
 */
JNIEXPORT void JNICALL Java_com_supermap_data_GeoRegionNative_jni_1Delete
  (JNIEnv *, jclass, jlong);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_Clone
 * Signature: (J)J
 */
JNIEXPORT jlong JNICALL Java_com_supermap_data_GeoRegionNative_jni_1Clone
  (JNIEnv *, jclass, jlong);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_GetArea
 * Signature: (J)D
 */
JNIEXPORT jdouble JNICALL Java_com_supermap_data_GeoRegionNative_jni_1GetArea
  (JNIEnv *, jclass, jlong);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_GetPartCount
 * Signature: (J)I
 */
JNIEXPORT jint JNICALL Java_com_supermap_data_GeoRegionNative_jni_1GetPartCount
  (JNIEnv *, jclass, jlong);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_GetPerimeter
 * Signature: (J)D
 */
JNIEXPORT jdouble JNICALL Java_com_supermap_data_GeoRegionNative_jni_1GetPerimeter
  (JNIEnv *, jclass, jlong);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_AddPart
 * Signature: (J[D[D)I
 */
JNIEXPORT jint JNICALL Java_com_supermap_data_GeoRegionNative_jni_1AddPart
  (JNIEnv *, jclass, jlong, jdoubleArray, jdoubleArray);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_ConvertToLine
 * Signature: (J)J
 */
JNIEXPORT jlong JNICALL Java_com_supermap_data_GeoRegionNative_jni_1ConvertToLine
  (JNIEnv *, jclass, jlong);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_GetPart
 * Signature: (J[D[D)I
 */
JNIEXPORT void JNICALL Java_com_supermap_data_GeoRegionNative_jni_1GetPart
  (JNIEnv *, jclass, jlong,jint, jdoubleArray, jdoubleArray);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_InsertPart
 * Signature: (JI[D[D)V
 */
JNIEXPORT jboolean JNICALL Java_com_supermap_data_GeoRegionNative_jni_1InsertPart
  (JNIEnv *, jclass, jlong, jint, jdoubleArray, jdoubleArray);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_RemovePart
 * Signature: (JI)V
 */
JNIEXPORT jboolean JNICALL Java_com_supermap_data_GeoRegionNative_jni_1RemovePart
  (JNIEnv *, jclass, jlong, jint);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_SetPart
 * Signature: (JI[D[D)V
 */
JNIEXPORT jboolean JNICALL Java_com_supermap_data_GeoRegionNative_jni_1SetPart
  (JNIEnv *, jclass, jlong, jint, jdoubleArray, jdoubleArray);

/*
 * Class:     com_supermap_data_GeoRegionNative
 * Method:    jni_GetPartPointCount
 * Signature: (JI)I
 */
JNIEXPORT jint JNICALL Java_com_supermap_data_GeoRegionNative_jni_1GetPartPointCount
  (JNIEnv *, jclass, jlong, jint);

/*
* Class:     com_supermap_data_GeoRegionNative
* Method:    jni_Clear
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_supermap_data_GeoRegionNative_jni_1Clear
(JNIEnv *, jclass, jlong);

#ifdef __cplusplus
}
#endif
#endif


text:
var _ = require('underscore');
var define = require('amdefine')(module);
define('frog/config', require('frog').singleton.config);

define([
    'frog',
    'frog/config'
], function (frog, config) {

    var schema = new frog.Schema({
        collection : 'users',
        document   : {
            name : {type : String, index : true, default : 'Mr Frog'}
        },
        options    : {
            strict : false
        }
    });

    return schema;

});


text:
<?php namespace Tarsana\Syntax\UnitTests;

use Tarsana\Syntax\ArraySyntax;
use Tarsana\Syntax\Factory as S;
use Tarsana\Syntax\NumberSyntax;
use Tarsana\Syntax\StringSyntax;

class ArraySyntaxTest extends TestCase {

    public function test_getters_and_setters()
    {
        $syntax = S::array()
            ->separator('/')
            ->syntax(S::number());

        $this->assertEquals('/', $syntax->separator());
        $this->assertTrue($syntax->syntax() instanceof NumberSyntax);
    }

    public function test_parse() {
        $syntax = new ArraySyntax;
        $this->assertParse($syntax, [
            ['input' => 'foo,BAR,baZ', 'result' => ['foo', 'BAR', 'baZ']],
            ['input' => 'foo:BAR,baZ', 'result' => ['foo:BAR', 'baZ']],
            ['input' => 'foo,"bar","baz,lorem",ipsum",yo"', 'result' => ['foo', 'bar', 'baz,lorem', 'ipsum",yo"']]
        ]);

        $syntax = new ArraySyntax(S::string(), ':');
        $this->assertParse($syntax, [
            ['input' => 'foo,BAR,baZ', 'result' => ['foo,BAR,baZ']],
            ['input' => 'foo:BAR,baZ', 'result' => ['foo', 'BAR,baZ']],
        ]);

        $syntax = new ArraySyntax(S::number(), '--');
        $this->assertParse($syntax, [
            ['input' => '5---6.5--20.4', 'result' => [5, -6.5, 20.4]],
        ]);

        $syntax = new ArraySyntax(S::number());
        $this->assertParse($syntax, [
            ['input' => '5,-6.5,20.4', 'result' => [5, -6.5, 20.4]],
            ['input' => '5,nan,20.4', 'errors' => [
                "Error while parsing '5,nan,20.4' as Array of (Number) separated by ',' at character 2: Unable to parse the item 'nan'",
                "Error while parsing 'nan' as Number at character 0: ". NumberSyntax::ERROR
            ]],
        ]);
    }

    public function test_dump() {
        $syntax = new ArraySyntax;
        $this->assertDump($syntax, [
            ['input' => ['foo','bar','baz'], 'result' => 'foo,bar,baz'],
            ['input' => 'foo', 'errors' => [
                "Error while dumping some input as Array of (String) separated by ',': " . ArraySyntax::ERROR
            ]],
            ['input' => ['foo', 15, 'lorem'], 'errors' => [
                "Error while dumping some input as Array of (String) separated by ',': Unable to dump item at key 1",
                "Error while dumping some input as String: " . StringSyntax::ERROR
            ]]
        ]);
        $syntax = new ArraySyntax(S::string(), ':');
        $this->assertDump($syntax, [
            ['input' => ['foo','bar','baz'], 'result' => 'foo:bar:baz'],
        ]);
    }

}


text:
import static org.fest.assertions.Assertions.assertThat;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.JsonNode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import play.libs.Json;
import ws.wamplay.callbacks.PubSubCallback;
import ws.wamplay.controllers.WAMPlayContoller;
import ws.wamplay.controllers.WAMPlayServer;
import ws.wamplay.models.WAMPlayClient;

public class PubSubTest {
	WAMPlayClient client;
	WAMPlayClient client2;
	String SIMPLE = "http://example.com/simple";
	String HELLO = "Hello, WAMP!";

	@Before
	public void setUp() {
		client = TestClientFactory.get();
		client2 = TestClientFactory.get();
	}

	@After
	public void tearDown() {
		client.kill();
		client2.kill();
		WAMPlayServer.reset();
	}

	@Test
	public void subscribeTest() {
		WAMPlayServer.addTopic(SIMPLE);

		subscribe(SIMPLE, client);
		assertThat(client.isSubscribed("http://example.com/simple")).isTrue();

		WAMPlayServer.addTopic("http://example.com/hello");
		subscribe("http://example.com/hello", client);
		assertThat(client.isSubscribed("http://example.com/hello")).isTrue();

		assertThat(client.isSubscribed("http://example.com/notatopic"))
				.isFalse();
	}

	private void subscribe(String topic, WAMPlayClient client) {
		JsonNode req = Json.parse("[5, \"" + topic + "\"]");
		WAMPlayServer.handleRequest(client, req);
	}

	@Test
	public void unsubscribeTest() {
		WAMPlayServer.addTopic(SIMPLE);

		assertThat(client.isSubscribed(SIMPLE)).isFalse();
		assertThat(client2.isSubscribed(SIMPLE)).isFalse();

		subscribe(SIMPLE, client);
		assertThat(client.isSubscribed(SIMPLE)).isTrue();
		assertThat(client2.isSubscribed(SIMPLE)).isFalse();

		unsubscribe(SIMPLE, client);
		assertThat(client.isSubscribed(SIMPLE)).isFalse();
		assertThat(client2.isSubscribed(SIMPLE)).isFalse();
	}

	private void unsubscribe(String topic, WAMPlayClient client) {
		JsonNode req = Json.parse("[6, \"" + topic + "\"]");
		WAMPlayServer.handleRequest(client, req);
	}

	@Test
	public void publishTest() {
		WAMPlayServer.addTopic(SIMPLE);
		subscribe(SIMPLE, client);
		subscribe(SIMPLE, client2);

		publishExcludeMe(SIMPLE, HELLO, client2, false);

		assertThat(client2.lastMessage().toString()).contains(
				HELLO);
		assertThat(client.lastMessage().toString()).contains(
				HELLO);
	}

	@Test
	public void publishExcludeMeTest() {
		WAMPlayServer.addTopic(SIMPLE);
		subscribe(SIMPLE, client);

		publishExcludeMe(SIMPLE, HELLO, client, true);
		assertThat(client.lastMessage().toString()).doesNotContain(HELLO);
	}

	@Test
	public void publishExcludeTest() {
		WAMPlayServer.addTopic(SIMPLE);
		subscribe(SIMPLE, client);
		String[] exclude = {client.getSessionID()};
		publishExclude(SIMPLE, HELLO, client, exclude);

		assertThat(client.lastMessage().toString()).doesNotContain(HELLO);
	}

	@Test
	public void publishEligibleTest() {
		WAMPlayServer.addTopic(SIMPLE);
		subscribe(SIMPLE, client);
		subscribe(SIMPLE, client2);

		String[] eligible = {client2.getSessionID()};

		publishEligible(SIMPLE, HELLO, client, eligible);

		assertThat(client.lastMessage().toString()).doesNotContain(HELLO);
		assertThat(client2.lastMessage().toString()).contains(HELLO);
	}

	@Test
	public void serverPublishTest(){
		WAMPlayServer.addTopic(SIMPLE);
		subscribe(SIMPLE, client);
		subscribe(SIMPLE, client2);

		List<String> eligible = new ArrayList<String>();
		eligible.add(client2.getSessionID());

		WAMPlayServer.publishEligible(SIMPLE, Json.toJson(HELLO), eligible);

		assertThat(client.lastMessage().toString()).doesNotContain(HELLO);
		assertThat(client2.lastMessage().toString()).contains(HELLO);

		WAMPlayServer.publish(SIMPLE, Json.toJson(HELLO));
		assertThat(client.lastMessage().toString()).contains(HELLO);
		assertThat(client.lastMessage().isArray()).isTrue();
	}

	private void publishExcludeMe(String topic, String message, WAMPlayClient client, boolean excludeMe) {
		List<Object> res = getPublishBeginning(topic, message);
		if (excludeMe) {
			res.add(excludeMe);
		}
		send(client, res);
	}

	private void publishExclude(String topic, String message, WAMPlayClient client, String[] exclude) {
		List<Object> res = getPublishBeginning(topic, message);
		res.add(exclude);
		send(client, res);
	}

	private void publishEligible(String topic, String message, WAMPlayClient client, String[] eligible) {
		List<Object> res = getPublishBeginning(topic, message);
		res.add(new String[0]);
		res.add(eligible);
		send(client, res);
	}

	private List<Object> getPublishBeginning(String topic, String message) {
		List<Object> res = new ArrayList<Object>();
		res.add(7);
		res.add(topic);
		res.add(message);

		return res;
	}

	private void send(WAMPlayClient client, List<Object> res) {
		JsonNode req = Json.toJson(res);
		WAMPlayServer.handleRequest(client, req);
	}

	@Test
	public void pubSubCallbackTest() {
		String topic = "http://example.com/capital";
		WAMPlayServer.addTopic(topic, new PubSubCallback() {

			@Override
			public boolean onSubscribe(String sessionID) {
				return true;
			}

			@Override
			public JsonNode onPublish(String sessionID, JsonNode eventJson) {
				if(eventJson.toString().contains("cancel")){
					return null;
				}
				return eventJson;
			}
		});

		subscribe(topic, client);

		publishExcludeMe(topic, "cancel this message", client, false);
		assertThat(client.lastMessage().toString()).doesNotContain("cancel");

		publishExcludeMe(topic, "not this message though", client, false);
		assertThat(client.lastMessage().toString()).contains("message");

	}

	@Test
	public void pubSubControllerTest(){
		WAMPlayContoller c = new TestPubSubController();
		WAMPlayServer.addController(c);

		String topic = "example.com/controller";

		subscribe(topic, client);

		publishExcludeMe(topic, "cancel this message", client, false);
		assertThat(client.lastMessage().toString()).doesNotContain("cancel");

		publishExcludeMe(topic, "not this message though", client, false);
		assertThat(client.lastMessage().toString()).contains("message");

		subscribe("example.com/easyTopic", client);
		publishExcludeMe("example.com/easyTopic", "test easyTopic", client, false);
		assertThat(client.lastMessage().toString()).contains("test easyTopic");

		subscribe("example.com/unsubscribable", client);
		publishExcludeMe("example.com/unsubscribable", "test unsubscribable", client, false);
		assertThat(client.lastMessage().toString()).doesNotContain("test unsubscribable");

	}
}


text:
package com.cra.figaro.test.experimental.particlebp

import org.scalatest.WordSpec
import org.scalatest.Matchers
import com.cra.figaro.algorithm.factored._
import com.cra.figaro.algorithm.factored.beliefpropagation._
import com.cra.figaro.language._
import com.cra.figaro.library.compound.If
import com.cra.figaro.library.compound.^^
import com.cra.figaro.library.atomic.discrete.{ Uniform => DUniform }
import com.cra.figaro.library.atomic.continuous.{ Uniform => CUniform }
import com.cra.figaro.library.compound.IntSelector
import com.cra.figaro.algorithm.UnsupportedAlgorithmException
import com.cra.figaro.library.atomic.continuous.Normal
import com.cra.figaro.experimental.particlebp.ParticleBeliefPropagation
import com.cra.figaro.algorithm.factored.ParticleGenerator
import com.cra.figaro.language.Name.stringToName
import com.cra.figaro.library.atomic.continuous.{ Uniform => CUniform }
import com.cra.figaro.library.atomic.discrete.{ Uniform => DUniform }
import com.cra.figaro.library.atomic.discrete.Geometric
import com.cra.figaro.library.atomic.continuous.Beta
import com.cra.figaro.algorithm.sampling.Importance
import com.cra.figaro.experimental.particlebp.AutomaticDensityEstimator
import com.cra.figaro.algorithm.sampling.ProbEvidenceSampler
import com.cra.figaro.ndtest._
import org.apache.commons.math3.distribution.MultivariateNormalDistribution
import akka.util.Timeout
import java.util.concurrent.TimeUnit

class PBPTest extends WordSpec with Matchers {

  val globalTol = 0.025
  val alpha = 0.05

  "Running ParticleBeliefPropagation" should {

    "resample after the inner loop" in {
      Universe.createNew()
      val n = Normal(0.0, 1.0)
      val bpb = ParticleBeliefPropagation(1, 1, n)
      bpb.runInnerLoop(Set(), Set())
      val pbpSampler = ParticleGenerator(Universe.universe)
      val samples = pbpSampler(n)
      bpb.resample
      samples should not be pbpSampler(n)
    }

    "resample according to the resampler values " in {
      def mean(p: List[(Double, Double)]) = (0.0 /: p)((c: Double, n: (Double, Double)) => c + n._1 * n._2)
      Universe.createNew()
      val n = Normal(0.0, 1.0)
      val pbpSampler = ParticleGenerator(Universe.universe, new AutomaticDensityEstimator, 100, 100)
      val samples = pbpSampler(n)
      pbpSampler.resample(n, samples, List(samples), 0.05)
      val newSamples = pbpSampler(n)
      mean(newSamples) should be(mean(samples) +- 0.1)
    }

    "change the factor structure with new samples on the outer loop" in {
      Universe.createNew()
      val n = Normal(2.0, 2.0)
      val number = Apply(n, (d: Double) => d.round.toInt)
      val items = Chain(number, (num: Int) => {
        val f = for { i <- 0 until num } yield Flip(0.5)
        Inject(f: _*)
      })
      val pbpSampler = ParticleGenerator(Universe.universe)
      pbpSampler.update(n, pbpSampler.numArgSamples, List[(Double, _)]((1.0, 2.0)))
      val bpb = ParticleBeliefPropagation(1, 1, items)
      bpb.runOuterLoop
      val fg_2 = bpb.bp.factorGraph.getNodes.filter(p => p.isInstanceOf[VariableNode]).toSet

      pbpSampler.update(n, pbpSampler.numArgSamples, List[(Double, _)]((1.0, 3.0)))
      val dependentElems = Set[Element[_]](n, number, items)
      bpb.runInnerLoop(dependentElems, Set())
      // Currently have to subtract 3 since the old factors for n = 2 also get created since they exist in the chain cache
      val fg_3 = bpb.bp.factorGraph.getNodes.filter(p => p.isInstanceOf[VariableNode]).toSet
      val diff = fg_3 -- fg_2
      diff.nonEmpty should equal(true)
    }

    /* Due to the way that factors are implemented for Chain, all
     * models that use chain will result in loops. To test a non-loopy
     * graph we have to not use chain, which IntSelector does not.
     */
    "with no loops in the factor graph give exact results" in {
      Universe.createNew()
      //com.cra.figaro.util.setSeed(13)
      val e1 = CUniform(1.5, 4.5)
      val ep = Apply(e1, (d: Double) => d.round.toInt)
      val e2 = IntSelector(ep)

      val bp = ParticleBeliefPropagation(5, 30, 100, 100, e2, e1, ep)
      bp.start

      val e2_0 = 0.33333333 * (0.5 + 0.3333333 + 0.25)
      val e2_1 = 0.33333333 * (0.5 + 0.3333333 + 0.25)
      val e2_2 = 0.33333333 * (0 + 0.3333333 + 0.25)
      val e2_3 = 0.33333333 * (0 + 0 + 0.25)

      val tol = 0.025
      val a = bp.distribution(e1).toList

      val b = bp.distribution(ep).toList
      bp.probability(e2, (i: Int) => i == 0) should be(e2_0 +- tol)
      bp.probability(e2, (i: Int) => i == 1) should be(e2_1 +- tol)
      bp.probability(e2, (i: Int) => i == 2) should be(e2_2 +- tol)
      bp.probability(e2, (i: Int) => i == 3) should be(e2_3 +- tol)
    }

    "correctly retrieve the last messages to recompute sample densities" in {
      Universe.createNew()
      val n = Normal(2.0, 2.0)
      val number = Apply(n, (d: Double) => d.round.toInt)
      val items = Chain(number, (num: Int) => {
        val f = for { i <- 0 until num } yield Flip(0.5)
        Inject(f: _*)
      })
      val bpb = ParticleBeliefPropagation(1, 1, items)
      bpb.runInnerLoop(Set(), Set())
      val msgs = bpb.getLastMessagesToNode(n)
      msgs.size should be > 1
      msgs(1).numVars should be(1)
      msgs(1).contents.map(_._2).sum should be(0.0 +- .01)
    }

    "with no conditions or constraints produce the correct result for a one time algorithm" in {
      val ndtest = new NDTest {
        override def oneTest = {
          Universe.createNew()
          val u = CUniform(0.3, 0.9)
          val f = Flip(u)
          val a = If(f, Select(0.3 -> 1, 0.7 -> 2), Constant(2))
          val result = test(f, 1, 30, 100, 100, (b: Boolean) => b, 0.6, globalTol)
          update(result, NDTest.TTEST, "NoConditionsOrConstraints", 0.6, alpha)
        }
      }
      ndtest.run(10)
    }

    "with a condition on a dependent element produce the result with the correct probability for a one time algorithm" in {
      val ndtest = new NDTest {
        override def oneTest = {
          Universe.createNew()
          val u = CUniform(0.3, 0.9)
          val f = Flip(u)
          val a = If(f, Select(0.3 -> 1, 0.7 -> 2), Constant(2))
          a.setCondition((i: Int) => i == 2)
          // U(true) = \int_{0.2}^{1.0) 0.7 p = 0.35 * 0.96
          // U(false) = \int_{0.2}^{1.0) (1-p)
          val u1 = 0.35 * 0.96
          val u2 = 0.32
          val result = test(f, 10, 30, 100, 100, (b: Boolean) => b, u1 / (u1 + u2), globalTol)
          update(result - (u1 / (u1 + u2)), NDTest.TTEST, "ConditionOnDependentElement", 0.0, alpha)
        }
      }
      ndtest.run(10)
    }

    "with a constraint on a dependent element produce the result with the correct probability for a one time algorithm" in {
      val ndtest = new NDTest {
        override def oneTest = {
          Universe.createNew()
          val u = CUniform(0.3, 0.9)
          val f = Flip(u)
          val a = If(f, Select(0.3 -> 1, 0.7 -> 2), Constant(2))
          a.setConstraint((i: Int) => i.toDouble)
          // U(true) = \int_{0.2}^{1.0} (0.3 + 2 * 0.7) p = 0.85 * 0.96
          // U(false) = \int_{0.2}^(1.0) (2 * (1-p)) = 0.64
          val u1 = 0.85 * 0.96
          val u2 = 0.64
          val result = test(f, 10, 30, 100, 100, (b: Boolean) => b, u1 / (u1 + u2), globalTol)

          update(result - (u1 / (u1 + u2)), NDTest.TTEST, "ConstraintOnDependentElement", 0.00, alpha)
        }
      }
      ndtest.run(10)

    }

    "with no conditions or constraints produce the correct result for a anytime algorithm" in {
      Universe.createNew()
      val u = CUniform(0.3, 0.9)
      val f = Flip(u)
      val a = If(f, Select(0.3 -> 1, 0.7 -> 2), Constant(2))
      test(f, 1000, 500, 100, 100, (b: Boolean) => b, 0.6, globalTol, false) should be(0.6 +- globalTol)
    }

    "with a condition on a dependent element produce the result with the correct probability for an anytime algorithm" in {
      val ndtest = new NDTest {
        override def oneTest = {
          Universe.createNew()
          val u = CUniform(0.3, 0.9)
          val f = Flip(u)
          val a = If(f, Select(0.3 -> 1, 0.7 -> 2), Constant(2))
          a.setCondition((i: Int) => i == 2)
          // U(true) = \int_{0.2}^{1.0) 0.7 p = 0.35 * 0.96
          // U(false) = \int_{0.2}^{1.0) (1-p)
          val u1 = 0.35 * 0.96
          val u2 = 0.32
          val result = test(f, 5000, 500, 100, 100, (b: Boolean) => b, u1 / (u1 + u2), globalTol, false)
          update(result, NDTest.TTEST, "ConditionOnDependentElement", u1 / (u1 + u2), alpha)
        }
      }
      ndtest.run(10)
    }

    "with a constraint on a dependent element produce the result with the correct probability for an anytime algorithm" in {
      val ndtest = new NDTest {
        override def oneTest = {
          Universe.createNew()
          val u = CUniform(0.3, 0.9)
          val f = Flip(u)
          val a = If(f, Select(0.3 -> 1, 0.7 -> 2), Constant(2))
          a.setConstraint((i: Int) => i.toDouble)
          // U(true) = \int_{0.2}^{1.0} (0.3 + 2 * 0.7) p = 0.85 * 0.96
          // U(false) = \int_{0.2}^(1.0) (2 * (1-p)) = 0.64
          val u1 = 0.85 * 0.96
          val u2 = 0.64
          val result = test(f, 5000, 500, 100, 100, (b: Boolean) => b, u1 / (u1 + u2), globalTol, false)
          update(result, NDTest.TTEST, "ConstraintOnDependentElement", u1 / (u1 + u2), alpha)
        }
      }
      ndtest.run(10)
    }

    "with an element that uses another element multiple times, " +
      "always produce the same value for the different uses" in {
        Universe.createNew()
        val f = CUniform(0.3, 0.9)
        val e = f === f
        test(e, 1, 30, 100, 100, (b: Boolean) => b, 1.0, globalTol) should be(1.0 +- globalTol)
      }

    "with a constraint on an element that is used multiple times, only factor in the constraint once" in {
      Universe.createNew()
      val f1 = Flip(0.5)
      val f2 = Flip(0.3)
      val e1 = f1 === f1
      val e2 = f1 === f2
      val d = Dist(0.5 -> e1, 0.5 -> e2)
      f1.setConstraint((b: Boolean) => if (b) 3.0; else 2.0)
      // Probability that f1 is true = 0.6
      // Probability that e1 is true = 1.0
      // Probability that e2 is true = 0.6 * 0.3 + 0.4 * 0.7 = 0.46
      // Probability that d is true = 0.5 * 1 + 0.5 * 0.46 = 0.73
      test(d, 1, 30, 100, 100, (b: Boolean) => b, 0.73, globalTol) should be(0.73 +- globalTol)
    }

    "on a different universe from the current universe, produce the correct result" in {
      val ndtest = new NDTest {
        override def oneTest = {
          val u1 = Universe.createNew()
          val u = CUniform(0.3, 0.9)
          val f = Flip(u)
          val a = If(f, Select(0.3 -> 1, 0.7 -> 2), Constant(2))
          Universe.createNew()
          val algorithm = ParticleBeliefPropagation(1, 20, 100, 100, f)(u1)
          algorithm.start()
          val result = algorithm.probability(f, (b: Boolean) => b)
          algorithm.kill()
          update(result, NDTest.TTEST, "DifferentUniverse", 0.6, alpha)
        }
      }
      ndtest.run(10)

    }

    /*
    "with a posterior different than the prior, converge upon the correct answer on a discrete variable" in {
      Universe.createNew()
      val fp = Geometric(0.9)
      val f = Flip(Apply(fp, (i: Int) => 1.0/(1.0+math.exp(-1*i.toDouble/10))))
      val s1 = Select(0.1 -> 1, 0.9 -> 2)
      val s2 = Select(0.7 -> 1, 0.2 -> 2, 0.1 -> 3)
      val c = Chain(f, (b: Boolean) => if (b) s1; else s2)
      c.observe(1)
      // ans obtained by importance sampling = 7.49
      val algorithm = ParticleBeliefPropagation(10, 40, 50, 50, fp)
      algorithm.start()
      algorithm.expectation(fp, (i: Int) => i.toDouble) should be(7.49 +- globalTol)
    }
    *
    */

    "with a posterior different than the prior, converge upon the correct posterior distribution of a continuous variable" in {
      val ndtest = new NDTest {
        override def oneTest = {
          Universe.createNew()
          val fp = CUniform(0.0, 1.0)
          val f = Flip(fp)
          val s1 = Select(0.1 -> 1, 0.9 -> 2)
          val s2 = Select(0.7 -> 1, 0.2 -> 2, 0.1 -> 3)
          val c = Chain(f, (b: Boolean) => if (b) s1; else s2)
          c.observe(1)
          // ans = \int_0_1 [-.6*x + .7 dx]*x / \int_0_1 [-.6*x + .7 dx] = .15/.4 = .375
          val algorithm = ParticleBeliefPropagation(10, 40, 100, 100, fp)
          algorithm.start()
          // algorithm.expectation(fp, (i: Double) => i) should be(.375 +- globalTol)
          val result = algorithm.expectation(fp, (i: Double) => i)
          algorithm.kill

          update(result, NDTest.TTEST, "PosteriorDifferentThanPrior", 0.375, alpha)
        }
      }
      ndtest.run(10)
    }

    "with a posterior different than the prior, reduce the variance of the posterior as compared to BP" in {
      val origCov = 8.0
      val mvn = new MultivariateNormalDistribution(Array(0.0, 0.0), Array(Array(8.0, origCov), Array(origCov, 16.0)))
      Universe.createNew()
      val locX = CUniform(20, 80)("X", Universe.universe)
      val locY = CUniform(20, 80)("Y", Universe.universe)
      val loc = ^^(locX, locY)
      loc.addConstraint((l: (Double, Double)) => {
        mvn.density(Array((l._1 - 40.0), (l._2 - 40.0)))
      })
      val algorithm = ParticleBeliefPropagation(10, 4, 15, 15, loc, locX, locY)
      algorithm.start()
      val locE = algorithm.expectation(loc, (d: (Double, Double)) => d._1 * d._2)
      val cov = locE - algorithm.mean(locX) * algorithm.mean(locY)

      ParticleGenerator.clear
      val algorithm2 = ParticleBeliefPropagation(1, 20, 15, 15, loc, locX, locY)
      algorithm2.start()
      val locE2 = algorithm2.expectation(loc, (d: (Double, Double)) => d._1 * d._2)
      val cov2 = locE - algorithm2.mean(locX) * algorithm2.mean(locY)
      (math.abs(cov - origCov) < math.abs(origCov - cov2)) should be(true)

    }

    "with a dependent universe, correctly take into account probability of evidence in the dependent universe" in {
      Universe.createNew()
      val x = IntSelector(Constant(10))
      val y = IntSelector(Constant(10))
      val x1 = Apply(x, (i: Int) => i < 1)
      val y1 = Apply(y, (i: Int) => i < 2)
      val dependentUniverse = new Universe(List(x1, y1))
      val u1 = CUniform(0.0, 1.0)("", dependentUniverse)
      val u2 = CUniform(0.0, 2.0)("", dependentUniverse)

      val a = CachingChain(x1, y1, (x: Boolean, y: Boolean) => if (x || y) u1; else u2)("a", dependentUniverse)
      val condition = (d: Double) => d < 0.5
      val ve = ParticleBeliefPropagation(List((dependentUniverse, List(NamedEvidence("a", Condition(condition))))),
        (u: Universe, e: List[NamedEvidence[_]]) => () => ProbEvidenceSampler.computeProbEvidence(10000, e)(u),
        1, 40, x1)
      ve.start()
      val peGivenXTrue = 0.5
      val peGivenXFalse = 0.2 * 0.5 + 0.8 * 0.25
      val unnormalizedPXTrue = 0.1 * peGivenXTrue
      val unnormalizedPXFalse = 0.9 * peGivenXFalse
      val pXTrue = unnormalizedPXTrue / (unnormalizedPXTrue + unnormalizedPXFalse)
      ve.probability(x1, true) should be(pXTrue +- globalTol)
      ve.kill()
    }

    "with a contingent condition, correctly take into account the contingency" in {
      Universe.createNew()
      val x = Flip(0.1)
      val y = Flip(0.2)
      y.setCondition((b: Boolean) => b, List(Element.ElemVal(x, true)))
      // Probability of y should be (0.1 * 0.2 + 0.9 * 0.2) / (0.1 * 0.2 + 0.9 * 0.2 + 0.9 * 0.8) (because the case where x is true and y is false has been ruled out)
      val ve = ParticleBeliefPropagation(3, 50, y)
      ve.start()
      ve.probability(y, true) should be(((0.1 * 0.2 + 0.9 * 0.2) / (0.1 * 0.2 + 0.9 * 0.2 + 0.9 * 0.8)) +- globalTol)
    }

  }

  /*
  "MaxProductBeliefPropagation" should {
    "compute the most likely values of all the variables given the conditions and constraints" in {
      Universe.createNew()
      val e1 = Flip(0.5)
      e1.setConstraint((b: Boolean) => if (b) 3.0; else 1.0)
      val e2 = If(e1, Flip(0.4), Flip(0.9))
      val e3 = If(e1, Flip(0.52), Flip(0.4))
      val e4 = e2 === e3
      e4.observe(true)
      // p(e1=T,e2=T,e3=T) = 0.75 * 0.4 * 0.52
      // p(e1=T,e2=F,e3=F) = 0.75 * 0.6 * 0.48
      // p(e1=F,e2=T,e3=T) = 0.25 * 0.9 * 0.4
      // p(e1=F,e2=F,e3=F) = 0.25 * 0.1 * 0.6
      // MPE: e1=T,e2=F,e3=F,e4=T
      val alg = MPEBeliefPropagation(20)
      alg.start()
      alg.mostLikelyValue(e1) should equal(true)
      alg.mostLikelyValue(e2) should equal(false)
      alg.mostLikelyValue(e3) should equal(false)
      alg.mostLikelyValue(e4) should equal(true)
    }

  }
  *
  */

  def test[T](target: Element[T], outer: Int, inner: Int,
    argSamples: Int, totalSamples: Int,
    predicate: T => Boolean, prob: Double, tol: Double, oneTime: Boolean = true): Double = {
    val algorithm = if (oneTime) {
      ParticleBeliefPropagation(outer, inner, argSamples, totalSamples, target)
    } else {
      val alg = ParticleBeliefPropagation(inner.toLong, argSamples, totalSamples, target)
      alg.messageTimeout = Timeout(30000, TimeUnit.MILLISECONDS)
      alg
    }
    algorithm.start()
    if (!oneTime) Thread.sleep(outer.toLong)
    algorithm.stop
    //    algorithm.probability(target, predicate) should be(prob +- tol)

    val result = algorithm.probability(target, predicate)
    algorithm.kill

    result
  }
}


text:
            <img src="<?php echo base_url("static/img/rakus_v2/logo_rakus.gif") ?>" width="38"  alt=""/>

Project Manager and Engineer Leader wanted

                        RAKUS Vietnam Co,Ltd.

Apply in 1 step!

                    <a href="<?php echo base_url() ?>"><img src="<?php echo base_url("static/img/logo.jpg") ?>" width="313" height="85" class="img-responsive-logo"  alt="JapanWorks"/>
                        <?php /* echo ($isHome) ? "
": ""?><?php echo $this->lang->line("slogan") ?><?php echo ($isHome) ? "
": "" */ ?>

<a href="<?php echo(MAIN_SITE); ?>"><img src="<?php echo base_url("static/img/power_vnw.png") ?>" width="180" height="54" alt="" class="img-responsive"/>


text:
static NSArray* DSFirstNames;
static NSArray* DSLastNames;

@implementation DSMockDataGenerator

- (NSString*)firstname {
    if (!DSFirstNames) {
        DSFirstNames = @[@"Julia", @"Steffi", @"Anna", @"Katharina", @"Katrin", @"Christian", @"Sebastian", @"Jan", @"Daniel", @"Stefan"];
    }
    return DSFirstNames[arc4random() % DSFirstNames.count];
}

- (NSString*)lastname {
    if (!DSLastNames) {
        DSLastNames = @[@"Müller", @"Schmidt", @"Schneider", @"Fischer", @"Weber", @"Meyer", @"Wagner", @"Becker", @"Schulz", @"Hoffmann"];
    }
    return DSLastNames[arc4random() % DSLastNames.count];
}

- (id)initWithManagedObjectContext:(NSManagedObjectContext*)context {
    self = [super init];
    if (!self) return nil;

    _managedObjectContext = context;
    return self;
}

- (NSArray*)getUsers:(NSUInteger)count {
    return [self getManagedObjects:count forClass:[DSUser class] withBlock:^(DSUser *user) {
        user.firstname = [self firstname];
        user.lastname = [self lastname];
        user.mail = [NSString stringWithFormat:@"%@.%@@example.com", user.firstname, user.lastname, nil];
        user.registered = [NSDate date];
        [user addImagesObject:[self getUserImage]];
    }];
}

- (NSArray*)getAuths:(NSUInteger)count {
    return [self getManagedObjects:count forClass:[DSAuth class] withBlock:^(DSAuth *auth) {
    }];
}

- (NSArray*)getManagedObjects:(NSUInteger)count forClass:(Class)classname withBlock:(void (^)(id object))customize {
    NSEntityDescription* entityDescription = [NSEntityDescription entityForName:NSStringFromClass(classname) inManagedObjectContext:self.managedObjectContext];
    NSMutableArray* objects = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i < count; i++) {
        NSManagedObject* object = [[classname alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext];
        customize(object);
        [objects addObject:object];
    }
    return [NSArray arrayWithArray:objects];
}

- (DSUserImage*)getUserImage {
    return (DSUserImage*)[self getImageForClass:[DSUserImage class] withURL:@"http://placekitten.com" width:(320 + arc4random() % 200) height:(320 + arc4random() % 200)];
}

- (DSImage*)getImageForClass:(Class)classname withURL:(NSString*)baseURL width:(int)width height:(int)height {
    NSEntityDescription* entityDescription = [NSEntityDescription entityForName:NSStringFromClass(classname) inManagedObjectContext:self.managedObjectContext];
    DSImage* image = [[classname alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext];
    NSString* maybeGray = (arc4random() % 4 > 0) ? @"" : @"/g";
    image.name = [NSString stringWithFormat:@"%@%@/%i/%i", baseURL, maybeGray, width, height, nil];
    image.width = [NSNumber numberWithInt:width];
    image.height = [NSNumber numberWithInt:height];
    image.mimetype = @"image/jpeg";
    image.created = [NSDate date];
    return image;
}

@end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Abstractions.Prompt
{
    using System.Collections.Generic;

    /// <summary>
    /// The repository handles retrieving of commands from the entire DNN installation
    /// </summary>
    public interface ICommandRepository
    {
        /// <summary>
        /// Gets a list of all found commands.
        /// </summary>
        /// <returns>List of ICommand</returns>
        IEnumerable<ICommand> GetCommands();
        /// <summary>
        /// Get the command. Returns null if no command found for the name.
        /// </summary>
        /// <param name="commandName">Name of the command (commonly in verb-noun format)</param>
        /// <returns>An IConsoleCommand or null</returns>
        IConsoleCommand GetCommand(string commandName);
        /// <summary>
        /// Get help for the specified command
        /// </summary>
        /// <param name="consoleCommand">Command to get help for</param>
        /// <returns>ICommandHelp class that can be used by the client to compile a help text</returns>
        ICommandHelp GetCommandHelp(IConsoleCommand consoleCommand);
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Class CI_FTP | Reserv</title>

	<link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e">

		Overview

Packages

						CodeIgniter

						Drivers

						Libraries

						None

						Reserv

Classes

CI_Benchmark

CI_Cache

CI_Cache_apc

CI_Cache_dummy

CI_Cache_file

CI_Cache_memcached

CI_Calendar

CI_Cart

CI_Config

CI_Controller

CI_Driver

CI_Driver_Library

CI_Email

CI_Encrypt

CI_Exceptions

CI_Form_validation

CI_FTP

CI_Hooks

CI_Image_lib

CI_Input

CI_Javascript

CI_Jquery

CI_Lang

CI_Loader

CI_Log

CI_Migration

CI_Model

CI_Output

CI_Pagination

CI_Parser

CI_Profiler

CI_Router

CI_Security

CI_Session

CI_SHA1

CI_Table

CI_Trackback

CI_Unit_test

CI_Upload

CI_URI

CI_User_agent

CI_Utf8

CI_Xmlrpc

CI_Xmlrpcs

CI_Zip

Report_api

REST_Controller

	<form id="search">
		<input type="hidden" name="cx" value="">
		<input type="hidden" name="ie" value="UTF-8">
		<input type="text" name="q" class="text" placeholder="Search">
	</form>

				Overview

Package

Class

				Tree

Class CI_FTP

FTP Class

		Package: CodeIgniter\Libraries

				Category:
				Libraries

				Author:
				EllisLab Dev Team

				Link:
				http://codeigniter.com/user_guide/libraries/ftp.html

			Located at system/libraries/Ftp.php

Methods summary

			 public

		#
		__construct(  <var>$config</var> = array() )

Constructor - Sets Preferences

Constructor - Sets Preferences

The constructor can be passed an array of config values

			 public

		#
		initialize( array <var>$config</var> = array() )

Initialize preferences

Initialize preferences

Parameters

<var>$config</var>

			 public

			boolean

		#
		connect( array <var>$config</var> = array() )

FTP Connect

FTP Connect

Parameters

<var>$config</var>

connection values

Returns

					boolean

			 public

			boolean

		#
		_login( )

FTP Login

FTP Login

Returns

					boolean

			 public

			boolean

		#
		_is_conn( )

Validates the connection ID

Validates the connection ID

Returns

					boolean

			 public

			boolean

		#
		changedir( string <var>$path</var> = '', boolean <var>$supress_debug</var> = FALSE )

Change directory

Change directory

The second parameter lets us momentarily turn off debugging so that
this function can be used to test for the existence of a folder
without throwing an error.  There's no FTP equivalent to is_dir()
so we do it by trying to change to a particular directory.
Internally, this parameter is only used by the "mirror" function below.

Parameters

<var>$path</var>

<var>$supress_debug</var>

Returns

					boolean

			 public

			boolean

		#
		mkdir( string <var>$path</var> = '',  <var>$permissions</var> = NULL )

Create a directory

Create a directory

Parameters

<var>$path</var>

<var>$permissions</var>

Returns

					boolean

			 public

			boolean

		#
		upload( string <var>$locpath</var>, string <var>$rempath</var>, string <var>$mode</var> = 'auto',  <var>$permissions</var> = NULL )

Upload a file to the server

Upload a file to the server

Parameters

<var>$locpath</var>

<var>$rempath</var>

<var>$mode</var>

<var>$permissions</var>

Returns

					boolean

			 public

			boolean

		#
		download( string <var>$rempath</var>, string <var>$locpath</var>, string <var>$mode</var> = 'auto' )

Download a file from a remote server to the local server

Download a file from a remote server to the local server

Parameters

<var>$rempath</var>

<var>$locpath</var>

<var>$mode</var>

Returns

					boolean

			 public

			boolean

		#
		rename( string <var>$old_file</var>, string <var>$new_file</var>, boolean <var>$move</var> = FALSE )

Rename (or move) a file

Rename (or move) a file

Parameters

<var>$old_file</var>

<var>$new_file</var>

<var>$move</var>

Returns

					boolean

			 public

			boolean

		#
		move( string <var>$old_file</var>, string <var>$new_file</var> )

Move a file

Move a file

Parameters

<var>$old_file</var>

<var>$new_file</var>

Returns

					boolean

			 public

			boolean

		#
		delete_file( string <var>$filepath</var> )

Rename (or move) a file

Rename (or move) a file

Parameters

<var>$filepath</var>

Returns

					boolean

			 public

			boolean

		#
		delete_dir( string <var>$filepath</var> )

Delete a folder and recursively delete everything (including sub-folders)
containted within it.

Delete a folder and recursively delete everything (including sub-folders)
containted within it.

Parameters

<var>$filepath</var>

Returns

					boolean

			 public

			boolean

		#
		chmod( string <var>$path</var>, string <var>$perm</var> )

Set file permissions

Set file permissions

Parameters

<var>$path</var>

file path

<var>$perm</var>

permissions

Returns

					boolean

			 public

			array

		#
		list_files(  <var>$path</var> = '.' )

FTP List files in the specified directory

FTP List files in the specified directory

Returns

					array

			 public

			boolean

		#
		mirror( string <var>$locpath</var>, string <var>$rempath</var> )

Read a directory and recreate it remotely

Read a directory and recreate it remotely

This function recursively reads a folder and everything it contains (including
sub-folders) and creates a mirror via FTP based on it.  Whatever the directory structure
of the original file path will be recreated on the server.

Parameters

<var>$locpath</var>

to source with trailing slash

<var>$rempath</var>

to destination - include the base folder with trailing slash

Returns

					boolean

			 public

			string

		#
		_getext( string <var>$filename</var> )

Extract the file extension

Extract the file extension

Parameters

<var>$filename</var>

Returns

					string

			 public

			string

		#
		_settype( string <var>$ext</var> )

Set the upload type

Set the upload type

Parameters

<var>$ext</var>

Returns

					string

			 public

			boolean

		#
		close( )

Close the connection

Close the connection

Returns

					boolean

			 public

			boolean

		#
		_error( string <var>$line</var> )

Display error message

Display error message

Parameters

<var>$line</var>

Returns

					boolean

Properties summary

			public
			string

				<var>$hostname</var>

				#
				''

			public
			string

				<var>$username</var>

				#
				''

			public
			string

				<var>$password</var>

				#
				''

			public
			integer

				<var>$port</var>

				#
				21

			public
			boolean

				<var>$passive</var>

				#
				TRUE

			public
			boolean

				<var>$debug</var>

				#
				FALSE

			public
			boolean

				<var>$conn_id</var>

				#
				FALSE

		Reserv API documentation generated by ApiGen


text:
@interface ChartboostInterstitialCustomEvent : MPInterstitialCustomEvent <ChartboostDelegate>

@end


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

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Voice</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Voice: voice

  Values:
  Cau
  CauPass
  CauPassRcp
  CauRcp
  Mid
  Pass
  PassRcp
  Rcp

Voice is a feature of verbs that helps map the traditional syntactic functions,
such as subject and object, to semantic roles, such as agent and patient.

(This feature, as defined currently, cannot correctly handle voice features on Tatar verbs.)
The above combinations (of camel-case voice values) are a temporary solution to indicate "multiple
voice" features, but they are certainly not the best way to indicate
these features.
See #197 and
#125
for the discussion.

Pass: passive voice

Passive voice demotes a subject to an oblique argument, and promotes an object to the subject position.

Examples

ичек ачылды  "the door was opened"

PassRcp: combination of passive and reciprocal voices

This language-specific value indicates that a verb with a reciprocal suffix is passivized.

Examples

аңла-ш-ыл-ды "alright" (lit: (it was) mutually understood)

Rcp: reciprocal voice

A reciprocal verb describes an event in which two agents (or groups of agents) perform the same action upon each other.

The reciprocal is expressed by the suffix -ыш/еш however,
the verb roots that can become reciprocal is limited.

Examples

күрешербез "we will see each other"

Cau: causative voice

In causative constructions the subject is the entity "causing" the action. It generally translate to English as 'cause/make/have/let/allow' someone to perform action described by the main verb.

Examples

аңлаттым "I explained (it)" (lit. "I made him/her/them understand it")

бәяне арттырдым "I raised the price" (lit. "I made the price increase")

CauPass: passive causative voice

This language-specific value indicates that a verb has been first causativized, then passivized.
The meaning is "the subject was caused (by somebody) to do the action."

Examples

шул мәсьәлә аңла-т-ыл-ды "The problem was explained"

CauRcp: causative reciprocal voice

This language-specific value indicates that a verb with a reciprocal suffix is causativized.
The meaning is "the subject was caused (by somebody) to do the action."

It describes an event in which two agents (or groups of agents) perform the same action upon each other and another entity causes the action.

Examples

ул мине аңа белән тан-ыш-тыр-ды "He introduced him/her to me" (lit: "He made me get to know with him/her")

CauPassRcp: causative reciprocal passive voice

This language-specific value indicates that a verb with a reciprocal suffix is passivized and causativized.
The meaning is "the subject was caused (by somebody) to do the action."

It describes an event in which two agents (or groups of agents) perform the same action upon each other and another entity causes the action.

Examples

Укучылар эвакуация планы белән тан-ыш-тыр-ыл-ды "The students got familiarized with the evacuation plan" (lit: "The students were made to get to know with the evacuation plan")

Mid: middle voice

This voice often has the same morpheme as the passive voice, but the middle voice does not reflect passivization.
In the middle voice, the subject is both the actor and the undergoer.

Examples

Вирустан ничек сакланырга? "How should we protect ourselves from the virus?"

Voice in other languages:

[abq]

[am]

[arr]

[bej]

[bg]

[ceb]

[cs]

[el]

[eme]

[en]

[fi]

[fr]

[gn]

[gub]

[hu]

[hy]

[myu]

[qpm]

[qtd]

[quc]

[ru]

[sv]

[tl]

[tpn]

[tr]

[tt]

[u]

[uk]

[urb]

[urj]

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
==============================
Django Admin Bootstrapped Plus
==============================

*Django Admin Bootstrapped Plus* is a small Django app
which provides a *vertical sidebar* to the standard Django admin pages,
as provided by the required app
`Django Admin Bootstrapped <https://github.com/django-admin-bootstrapped/django-admin-bootstrapped>`_.

The vertical sidebar provides a stack of links to all models, grouped by the installed apps.

See `Django 9cms <https://github.com/Wtower/django-ninecms>`_ for screenshot.

Dependencies
------------

- Python (3.4+)
- Django (1.8+): Web framework
- django-admin-bootstrapped (2.5+): provide a nicer admin interface experience

Quick how-to
------------

This is a quick guide on how to use it.

1. Install django-admin-bootstrapped-plus::

     $ pip install django-admin-bootstrapped-plus

   or download source and place in project root

2. Dependencies (resolved by pip)::

     Django==1.8.7
     django-admin-bootstrapped==2.5.6

3. Settings

   You need to install the app in ``INSTALLED_APPS`` before admin_bootstrapped and before admin,
   so that Django loads the templates properly::

     INSTALLED_APPS = (
         'admin_bootstrapped_plus',
         'django_admin_bootstrapped',
         'django.contrib.admin',
         # ...
     )

4. Start the development server and visit http://127.0.0.1:8000/admin/

That's it.

Footnote
--------

Any contribution to the project is highly appreciated and the best will be done to respond to it.


text:
from django.test import TestCase

from oscar.apps.catalogue.reviews import forms
from oscar.test.factories import create_product, UserFactory

class TestReviewForm(TestCase):

    def setUp(self):
        self.product = create_product()
        self.reviewer = UserFactory()
        self.data = {
            'title': '  This product is lovely',
            'body': 'I really like this cheese',
            'score': 0,
            'name': 'JR Hartley',
            'email': 'hartley@example.com'
        }

    def test_cleans_title(self):
        form = forms.ProductReviewForm(
            product=self.product, user=self.reviewer, data=self.data)
        self.assertTrue(form.is_valid())
        review = form.save()
        self.assertEqual("This product is lovely", review.title)

class TestVoteForm(TestCase):

    def setUp(self):
        self.product = create_product()
        self.reviewer = UserFactory()
        self.voter = UserFactory()
        self.review = self.product.reviews.create(
            title='This is nice',
            score=3,
            body="This is the body",
            user=self.reviewer)

    def test_allows_real_users_to_vote(self):
        form = forms.VoteForm(self.review, self.voter, data={'delta': 1})
        self.assertTrue(form.is_valid())

    def test_prevents_users_from_voting_more_than_once(self):
        self.review.vote_up(self.voter)
        form = forms.VoteForm(self.review, self.voter, data={'delta': 1})
        self.assertFalse(form.is_valid())
        self.assertTrue(len(form.errors['__all__']) > 0)

    def test_prevents_users_voting_on_their_own_reviews(self):
        form = forms.VoteForm(self.review, self.reviewer, data={'delta': 1})
        self.assertFalse(form.is_valid())
        self.assertTrue(len(form.errors['__all__']) > 0)


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="oro_workflow_transition_log")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class WorkflowTransitionRecord
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="WorkflowItem", inversedBy="transitionRecords")
     * @ORM\JoinColumn(name="workflow_item_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $workflowItem;

    /**
     * @var string
     *
     * @ORM\Column(name="transition", type="string", length=255, nullable=true)
     */
    protected $transitionName;

    /**
     * @var WorkflowStep
     *
     * @ORM\ManyToOne(targetEntity="WorkflowStep")
     * @ORM\JoinColumn(name="step_from_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $stepFrom;

    /**
     * @var WorkflowStep
     *
     * @ORM\ManyToOne(targetEntity="WorkflowStep")
     * @ORM\JoinColumn(name="step_to_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $stepTo;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="transition_date", type="datetime")
     */
    protected $transitionDate;

    /**
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param WorkflowStep $stepFrom
     * @return WorkflowTransitionRecord
     */
    public function setStepFrom($stepFrom)
    {
        $this->stepFrom = $stepFrom;
        return $this;
    }

    /**
     * @return WorkflowStep
     */
    public function getStepFrom()
    {
        return $this->stepFrom;
    }

    /**
     * @param WorkflowStep $stepTo
     * @return WorkflowTransitionRecord
     */
    public function setStepTo($stepTo)
    {
        $this->stepTo = $stepTo;
        return $this;
    }

    /**
     * @return WorkflowStep
     */
    public function getStepTo()
    {
        return $this->stepTo;
    }

    /**
     * @param string $transitionName
     * @return WorkflowTransitionRecord
     */
    public function setTransitionName($transitionName)
    {
        $this->transitionName = $transitionName;
        return $this;
    }

    /**
     * @return string
     */
    public function getTransitionName()
    {
        return $this->transitionName;
    }

    /**
     * @param mixed $workflowItem
     * @return WorkflowTransitionRecord
     */
    public function setWorkflowItem($workflowItem)
    {
        $this->workflowItem = $workflowItem;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getWorkflowItem()
    {
        return $this->workflowItem;
    }

    /**
     * @return \DateTime
     */
    public function getTransitionDate()
    {
        return $this->transitionDate;
    }

    /**
     * @ORM\PrePersist
     */
    public function prePersist()
    {
        $this->transitionDate = new \DateTime('now', new \DateTimeZone('UTC'));
    }
}


text:
from django import template

from classytags.arguments import Argument
from classytags.core import Options
from classytags.helpers import AsTag

from cms.wizards.wizard_pool import wizard_pool

register = template.Library()

class WizardProperty(AsTag):
    name = 'cms_wizard'

    options = Options(
        Argument('wizard_id'),
        Argument('property', required=False, default=None),
        'as',
        Argument('varname', required=False, resolve=False),
    )

    def get_value(self, context, wizard_id, property=None):
        """
        If called with a «property» returns the property of the wizard
        identified by «wizard_id». If no «property», just return the entire
        wizard object.
        """
        try:
            wizard = wizard_pool.get_entry(wizard_id)
        except ValueError:
            wizard = None

        if wizard:
            if property in ['description', 'title', 'weight']:
                # getters
                getter = getattr(wizard, "get_{0}".format(property), None)
                return getter()
            elif property in ['id', 'form', 'model', 'template_name']:
                # properties
                return getattr(wizard, property, None)
            else:
                return wizard
        return None

register.tag(WizardProperty)


text:
        <meta http-equiv="content-type" content="text/html; charset=utf8">
        <link rel="stylesheet" type="text/css" href="../../css/abbozza.css">
        <title>abbozza! - Dokumentation</title>

Dokumentation

Einstellungen

Allgemeine Informationen

                © 2015/16 Michael Brinkmeier

                michael.brinkmeier@uni-osnabrueck.de

                AG Didaktik der Informatik

                Institut für Informatik

                Universität Osnabrück