text:
@interface PXObjectValueWrapperTests : XCTestCase

@end

@implementation PXObjectValueWrapperTests

+ (void)initialize
{
    [PixateFreestyle initializePixateFreestyle];
}

- (void)setUp
{
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown
{
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

#pragma mark - Automatic Setup Tests

- (void)testColorGetterAutoWrapped
{
    PXPropertyTestClass *object = [[PXPropertyTestClass alloc] init];
    PXObjectValueWrapper *wrapper = [[PXObjectValueWrapper alloc] initWithObject:object];
    [wrapper addExports];

    id<PXExpressionValue> result = [wrapper valueForPropertyName:@"color"];

    XCTAssertTrue([@"rgba(1,0,0,0)" isEqualToString:result.description], @"Colors do not match");
}

- (void)testColorSetterAutoWrapped
{
    PXPropertyTestClass *object = [[PXPropertyTestClass alloc] init];
    PXObjectValueWrapper *wrapper = [[PXObjectValueWrapper alloc] initWithObject:object];
    [wrapper addExports];

    PXHSBColorValue *color = [[PXHSBColorValue alloc] initWithHue:180.0 saturation:0.5 brightness:0.75];
    [wrapper setValue:color forPropertyName:@"color"];
    id<PXExpressionValue> result = [wrapper valueForPropertyName:@"color"];

    XCTAssertTrue([@"rgba(0.75,0.375,0.375,0)" isEqualToString:result.description], @"Colors do not match");
}

- (void)testColorValueGetterAutoWrapped
{
    PXPropertyTestClass *object = [[PXPropertyTestClass alloc] init];
    PXObjectValueWrapper *wrapper = [[PXObjectValueWrapper alloc] initWithObject:object];
    [wrapper addExports];

    id<PXExpressionValue> result = [wrapper valueForPropertyName:@"pxColor"];

    XCTAssertTrue([@"hsba(180,0.5,0.75,1)" isEqualToString:result.description], @"Colors do not match");
}

- (void)testColorValueSetterAutoWrapped
{
    PXPropertyTestClass *object = [[PXPropertyTestClass alloc] init];
    PXObjectValueWrapper *wrapper = [[PXObjectValueWrapper alloc] initWithObject:object];
    [wrapper addExports];

    PXHSBColorValue *color = [[PXHSBColorValue alloc] initWithHue:90.0 saturation:0.25 brightness:0.5];
    [wrapper setValue:color forPropertyName:@"pxColor"];
    id<PXExpressionValue> result = [wrapper valueForPropertyName:@"pxColor"];

    XCTAssertTrue([@"hsba(90,0.25,0.5,1)" isEqualToString:result.description], @"Colors do not match");
}

@end


text:
<?php

/**
 * This manages and represents a bunch of categories.
 * @package    sfLucenePlugin
 * @subpackage Category
 * @author     Carl Vondrick <carl@carlsoft.net>
 * @version SVN: $Id$
 */

class sfLuceneCategories
{
  /**
   * Holds the writer
   */
  protected $writer;

  /**
   * Holds all the instances of the categories
   */
  protected $categories = array();

  /**
   * If true, the list has been modified.
   */
  protected $modified = false;

  /**
   * Singleton constructor
   * @param sfLucene $search The search instance to tie to
   * @param sfLuceneStorage $writer The writer (optional)
   */
  public function __construct($search, $writer = null)
  {
    if (!($search instanceof sfLucene))
    {
      throw new sfLuceneException('Search must be an instance of sfLucene');
    }

    if ($writer == null)
    {
      $writer = new sfLuceneStorageFilesystem(sfConfig::get('sf_cache_dir') . DIRECTORY_SEPARATOR . $search->getParameter('index_location') . DIRECTORY_SEPARATOR . 'categories.php');
    }

    if (!($writer instanceof sfLuceneStorage))
    {
      throw new sfLuceneException('Writer must be an instance of sfLuceneStorage');
    }

    $this->writer = $writer;

    $this->load();
  }

  public function __destruct()
  {
    $this->save();
  }

  /**
   * Returns an instance of the category object.  If it does not exist, it creates
   * an empty one.
   */
  public function getCategory($category)
  {
    if (!isset($this->categories[$category]))
    {
      $this->categories[$category] = new sfLuceneCategory($this, $category);
    }

    return $this->categories[$category];
  }

  public function getAllCategories()
  {
    return $this->categories;
  }

  public function flagAsModified()
  {
    $this->modified = true;
  }

  public function isModified()
  {
    return $this->modified;
  }

  public function load()
  {
    $data = $this->writer->read();

    if ($data)
    {
      eval($data);

      if (!isset($categories) || !is_array($categories))
      {
        throw new sfLuceneException('Categories file found, but it was corrupt.');
      }

      $this->categories = array();

      foreach ($categories as $category => $count)
      {
        $this->categories[$category] = new sfLuceneCategory($this, $category, $count);
      }
    }

    return $this;
  }

  /**
   * Writes the list to disk
   */
  public function save()
  {
    if ($this->modified)
    {
      // build data
      $data = "\$categories = array();";

      foreach ($this->categories as $category)
      {
        if ($category->worthSaving())
        {
          $data .= $category->getPhp();
        }
      }

      $this->writer->write($data);

      $this->modified = false;
    }

    return $this;
  }

  /**
   * Clears the entire list
   */
  public function clear()
  {
    $this->categories = array();

    $this->modified = true;

    return $this;
  }
}

redpajama_set_name: RedPajamaGithub


text:
We believe in reproducible research. We want our peers and colleagues to be able to inspect our methods, recreate our computations, and verify our results. To that end, **all the software tools we work with are freely available (zero cost) to anyone in the world**, with most of those tools also being open-source.

Here's what we think of as our [solution stack](http://en.wikipedia.org/wiki/Solution_stack) for data analysis.

### Version Control

- [Git](http://git-scm.com/)
- [Github.com](https://github.com/)
- The Github apps for [Mac](https://mac.github.com/) and [Windows](https://windows.github.com/)

To us, it's important that we preserve every historical stage of our data analysis, especially if we need to revert something we did. Git gives us a fast, industry-standard way to do that. We can version *everything*: code, images, even arbitrary binary files. And while some of us are command-line ninjas, we do most of our interaction with Git through the wonderful apps developed by the Github folks.

The most important advantage of using Git? We can throw our projects on Github and that gives us all sorts of advantages for collaboration: [pull requests](https://help.github.com/articles/using-pull-requests) for code review, discussion threads, and [issue trackers](https://github.com/blog/831-issues-2-0-the-next-generation). Heck, just [read the list of Github features](https://github.com/features) if you're not already convinced.

### Data Analysis in Python

- [Python](https://www.python.org/)
- [Pandas Data Analysis Library for Python](http://pandas.pydata.org/)
- [iPython Notebook](http://ipython.org/notebook.html)
- [Enthought Canopy Express](https://www.enthought.com/canopy-express/)

Python forms the core of the data analysis you'll see throughout this book. And, much of the code uses syntax from Pandas, a fantastic data analysis system built atop Python's excellent [Numpy](http://www.numpy.org/) (pronounced "Num-pie") and [Scipy](http://www.scipy.org/) packages.

But while Python is the language we speak, essentially all of this analysis was carried out in iPython Notebook. iPython Notebook is an amazing piece of software that lets code, plots, and documentation all live within the same dynamic document.

We use a turnkey version of Python called Enthough Canopy Express because it comes pre-loaded with everything we need: Numpy, Scipy, Pandas, and iPython. It's ready to go out of the box, and it's free.

### Data Analysis in R (not covered in this book)

- [The R Project for Statistical Computing](http://www.r-project.org/)
- [RStudio](http://www.rstudio.com/)

We don't always depart from Python, but when we do we use R. R is a powerful, open-source statistical programming language, and RStudio is a fantastic integrated development environment (IDE) for working in R. One of R's core strengths is its vast ecosystem of user-contributed packages. Odds are that if you want to do something special in R, there's a package for it. As of June 1, 2014 the R Package Archive has more than 5,000 packages available for use.

### Dissemination of Results

- [Github.com](https://github.com/)
- [iPython Notebook Viewer](http://nbviewer.ipython.org/) (for Python Analyses)
- [Markdown](http://en.wikipedia.org/wiki/Markdown) and [RMarkdown](http://www.rstudio.com/ide/docs/authoring/using_markdown)
- [Rpubs](https://rpubs.com/) (for R analyses)

Markdown is a simplified markup syntax originally developed by [John Gruber](http://daringfireball.net/projects/markdown/) and [Aaron Swartz](http://en.wikipedia.org/wiki/Aaron_Swartz). It's the backbone of all the text we write. (This entire book was written in Markdown!). We like it because it's a plaintext format that lets humans easily read and write rich text.

Also, you'll notice some repeat tools here, and there's a good reason for that. All of the above tools work together for sharing our work. The general workflow is:

1. Write a [literate document](http://en.wikipedia.org/wiki/Literate_programming) with code, plots, and narrative all in one
2. Version the document with git
3. Push the repository to Github, where it can be shared
4. Optionally, create a persistent link using a publication service

When we work in Python, we use iPython to create [literate documents](http://en.wikipedia.org/wiki/Literate_programming) with raw Python code, annotated with Markdown. If we version those notebooks with git, we can then easily push the code repository to Github. And, with the repository on Github we can point iPython Notebook Viewer to our file. Whenever our file updates, the iPython Notebook Viewer page automatically updates too, so our analysis can evolve over time.

We use a similar workflow for R, which has its own publication service for RMarkdown Documents called [Rpubs](https://rpubs.com/).


text:
<?php

class TimberPost extends TimberCore {

	var $ImageClass = 'TimberImage';
	var $PostClass = 'TimberPost';
	var $_can_edit;
	var $_get_terms;

	var $_custom_imported = false;

	public static $representation = 'post';

	/**
	*  If you send the contructor nothing it will try to figure out the current post id based on being inside The_Loop
	* @param mixed $pid
	* @return \TimberPost TimberPost object -- woo!
	*/
	function __construct($pid = null) {
		if ($pid === null && get_the_ID()){
			$pid = get_the_ID();
			$this->ID = $pid;
		} else if ($pid === null && have_posts()) {
			ob_start();
			the_post();
			$pid = get_the_ID();
			$this->ID = $pid;
			ob_end_clean();
		}
		if (is_numeric($pid)) {
			$this->ID = $pid;
		}
		$this->init($pid);
	}

	function init($pid = false) {
		if ($pid === false) {
			$pid = get_the_ID();
		}
		$post_info = $this->get_info($pid);
		$this->import($post_info);
	}

	/**
	*  Get the URL that will edit the current post/object
	*/
	function get_edit_url() {
		if ($this->can_edit()) {
			return '/wp-admin/post.php?post=' . $this->ID . '&action=edit';
		}
		return false;
	}

	/**
	*  updates the post_meta of the current object with the given value
	*
	* @param string $field
	* @param mixed $value
	* @nodoc
	*/
	function update($field, $value) {
		if (isset($this->ID)) {
			update_post_meta($this->ID, $field, $value);
			$this->$field = $value;
		}
	}

  /**
   *  takes a mix of integer (post ID), string (post slug), or object to return a WordPress post object from WP's built-in get_post() function
   *
   * @param mixed $pid
   * @return WP_Post on success
   */
	private function prepare_post_info($pid = 0) {
		if (is_string($pid) || is_numeric($pid) || (is_object($pid) && !isset($pid->post_title)) || $pid === 0) {
			$pid = self::check_post_id($pid);
			$post = get_post($pid);
			if ($post) {
				return $post;
			} else {
				$post = get_page($pid);
				return $post;
			}
		}
		//we can skip if already is WP_Post
		return $pid;
	}

	/**
	*  helps you find the post id regardless of whetehr you send a string or whatever
	*
	* @param mixed $pid;
	* @return integer ID number of a post
	*/
	private function check_post_id($pid) {
		if (is_numeric($pid) && $pid === 0) {
			$pid = get_the_ID();
			return $pid;
		}
		if (!is_numeric($pid) && is_string($pid)) {
			$pid = self::get_post_id_by_name($pid);
			return $pid;
		}
		if (!$pid) {
			return null;
		}
		return $pid;
	}

	/**
	*  get_post_id_by_name($post_name)
	* @nodoc
	*/

	function get_post_id_by_name($post_name) {
		global $wpdb;
		$query = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_name = %s LIMIT 1", $post_name);
		$result = $wpdb->get_row($query);
		return $result->ID;
	}

  /**
   *  ## get a preview of your post, if you have an excerpt it will use that,
   *  ## otherwise it will pull from the post_content
   *
{{post.get_preview(50)}}

   */

	function get_preview($len = 50, $force = false, $readmore = 'Read More', $strip = true) {
		$text = '';
		$trimmed = false;
		if (isset($this->post_excerpt) && strlen($this->post_excerpt)) {
			if ($force) {
				$text = TimberHelper::trim_words($this->post_excerpt, $len);
				$trimmed = true;
			} else {
				$text = $this->post_excerpt;
			}
		}
		if (!strlen($text)) {
			$text = TimberHelper::trim_words($this->get_content(), $len, false);
			$trimmed = true;
		}
		if (!strlen(trim($text))) {
			return $text;
		}
		if ($strip) {
			$text = trim(strip_tags($text));
		}
		if (strlen($text)) {
			$text = trim($text);
			$last = $text[strlen($text) - 1];
			if ($last != '.' && $trimmed) {
				$text .= ' … ';
			}
			if (!$strip){
				$last_p_tag = strrpos($text, '
');
				$text = substr($text, 0, $last_p_tag);
				if ($last != '.' && $trimmed) {
					$text .= ' … ';
				}
			}

			$text .= ' get_permalink() . '" class="read-more">' . $readmore . '';
			if (!$strip){
				$text .= '
';
			}
		}
		return $text;
	}

  /**
   *  gets the post custom and attaches it to the current object
   * @param integer $pid a post ID number
   * @nodoc
   */
  	function import_custom($pid = false){
  		if (!$pid){
  			$pid = $this->ID;
  		}
  		$customs = $this->get_post_custom($pid);
  		$this->import($customs);
  	}

	function get_post_custom($pid) {
		$customs = get_post_custom($pid);
		if (!is_array($customs) || empty($customs)){
			return;
		}
		foreach ($customs as $key => $value) {
			$v = $value[0];
			$customs[$key] = maybe_unserialize($v);
		}
		return $customs;
	}

	/**
	*  ## get the featured image as a TimberImage
	*
	*/

	function get_thumbnail() {
		if (function_exists('get_post_thumbnail_id')) {
			$tid = get_post_thumbnail_id($this->ID);
		if ($tid) {
			return new $this->ImageClass($tid);
			}
		}
		return null;
	}

	function get_permalink() {
		if (isset($this->permalink)){
			return $this->permalink;
		}
		$this->permalink = get_permalink($this->ID);
		return $this->permalink;
	}

	function get_link() {
		if (isset($this->path)) {
			return $this->path;
		}
		return null;
	}

	function get_parent() {
		if (!$this->post_parent) {
			return false;
		}
		return new $this->PostClass($this->post_parent);
	}

	/**
	*  ## Gets a User object from the author of the post
	*
{{post.get_author.name}}

	*/

	function get_author() {
		if (isset($this->post_author)) {
			return new TimberUser($this->post_author);
		}
		return false;
	}

	function get_info($pid) {
		$post = $this->prepare_post_info($pid);
		if (!isset($post->post_status)) {
			return null;
		}
		$post->slug = $post->post_name;
		$post->status = $post->post_status;
		$customs = $this->get_post_custom($post->ID);
		$post = (object) array_merge((array) $post, (array) $customs);
		return $post;
	}

	function get_display_date($use = 'post_date') {
		return date(get_option('date_format'), strtotime($this->$use));
	}

	function get_children($post_type = 'any', $childPostClass = false) {
		if ($childPostClass == false) {
			$childPostClass = $this->PostClass;
		}
		if ($post_type == 'parent') {
			$post_type = $this->post_type;
		}
		$children = get_children('post_parent=' . $this->ID . '&post_type=' . $post_type);
		foreach ($children as &$child) {
			$child = new $childPostClass($child->ID);
		}
		$children = array_values($children);
		return $children;
	}

	/**
	*  {% for comment in post.get_comments %}
	*
{{comment.content}}

	*  {% endfor %}
	*/

	function get_comments($ct = 0, $order = 'wp', $type = 'comment', $status = 'approve', $CommentClass = 'TimberComment') {
		$args = array('post_id' => $this->ID, 'status' => $status, 'order' => $order);
		if ($ct > 0) {
			$args['number'] = $ct;
		}
		if ($order == 'wp'){
			$args['order'] = get_option('comment_order');
		}
		$comments = get_comments($args);
		foreach ($comments as &$comment) {
			$comment = new $CommentClass($comment);
		}
		return $comments;
	}

	/**
	*

	*  {% for category in post.get_categories %}
	*
{{category.name}}

	*  {% endfor %}
	*

	*/

	function get_categories() {
		return $this->get_terms('category');
	}

	function get_category() {
		$cats = $this->get_categories();
		if (count($cats) && isset($cats[0])) {
			return $cats[0];
		}
		return null;
	}

	/** # get terms is good
	*
	*/

	function get_terms($tax = '', $merge = true, $TermClass = 'TimberTerm') {
		if (is_string($tax)){
			if (isset($this->_get_terms) && isset($this->_get_terms[$tax])){
				return $this->_get_terms[$tax];
			}
		}
		if (!strlen($tax) || $tax == 'all' || $tax == 'any') {
			$taxs = get_object_taxonomies($this->post_type);
		} else if (is_array($tax)) {
			$taxs = $tax;
		} else {
			$taxs = array($tax);
		}
		$ret = array();
		foreach ($taxs as $tax) {
			if ($tax == 'tags' || $tax == 'tag') {
				$tax = 'post_tag';
			} else if ($tax == 'categories') {
				$tax = 'category';
			}
			$terms = wp_get_post_terms($this->ID, $tax);
			foreach ($terms as &$term) {
				$term = new $TermClass($term->term_id);
			}
			if ($merge && is_array($terms)) {
				$ret = array_merge($ret, $terms);
			} else if (count($terms)) {
				$ret[$tax] = $terms;
			}
		}
		if (!isset($this->_get_terms)){
			$this->_get_terms = array();
		}
		$this->_get_terms[$tax] = $ret;
		return $ret;
	}

	function get_image($field) {
		return new $this->ImageClass($this->$field);
	}

	/**
	*  ## Gets an array of tags for you to use
	*

	*  {% for tag in post.tags %}
	*
{{tag.name}}

	*  {% endfor %}
	*

	*/

	function get_tags() {
		return $this->get_terms('tags');
	}

	/**
	*  ## Outputs the title with filters applied
	*
{{post.get_title}}

	*/

	function get_title() {
		$title = $this->post_title;
		return apply_filters('the_title', $title);
	}

	/**
	*  ## Displays the content of the post with filters, shortcodes and wpautop applied
	*
{{post.get_content}}

	*/

	function get_content($len = 0, $page = 0) {
		$content = $this->post_content;
		if ($len) {
			$content = wp_trim_words($content, $len);
		}
		if ($page) {
			$contents = explode('', $content);
			$page--;
			if (count($contents) > $page) {
				$content = $contents[$page];
			}
		}
		return apply_filters('the_content', ($content));
	}

	function get_post_type() {
		return get_post_type_object($this->post_type);
	}

	function get_comment_count() {
		if (isset($this->ID)) {
			return get_comments_number($this->ID);
		} else {
			return 0;
		}
	}

	//This is for integration with Elliot Condon's wonderful ACF
	function get_field($field_name) {
		if (function_exists('get_field')){
			return get_field($field_name, $this->ID);
		}
		return get_post_meta($this->ID, $field, true);
	}

	function import_field($field_name) {
		$this->$field_name = $this->get_field($field_name);
	}

	//Aliases
	function author() {
		return $this->get_author();
	}

	function categories() {
		return $this->get_terms('category');
	}

	function category() {
		return $this->get_category();
	}

	function children() {
		return $this->get_children();
	}

	function comments(){
		return $this->get_comments();
	}

	function content() {
		return $this->get_content();
	}

	function display_date(){
		return date(get_option('date_format'), strtotime($this->post_date));
	}

	function link() {
		return $this->get_permalink();
	}

	function path(){
		$path = TimberHelper::get_rel_url($this->get_permalink());
		return TimberHelper::preslashit($path);
	}

	function permalink() {
		return $this->get_permalink();
	}

	function terms($tax = '') {
		return $this->get_terms($tax);
	}

	function tags() {
		return $this->get_tags();
	}

	function thumbnail() {
		return $this->get_thumbnail();
	}

	function title() {
		return $this->get_title();
	}

	//Deprecated
	function get_path() {
		return $this->get_link();
	}

}


text:
#pragma once
#include <aws/dax/DAX_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/dax/model/Parameter.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace DAX
{
namespace Model
{
  class AWS_DAX_API DescribeParametersResult
  {
  public:
    DescribeParametersResult();
    DescribeParametersResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DescribeParametersResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Provides an identifier to allow retrieval of paginated results.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
Provides an identifier to allow retrieval of paginated results.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
Provides an identifier to allow retrieval of paginated results.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
Provides an identifier to allow retrieval of paginated results.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
Provides an identifier to allow retrieval of paginated results.

     */
    inline DescribeParametersResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
Provides an identifier to allow retrieval of paginated results.

     */
    inline DescribeParametersResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
Provides an identifier to allow retrieval of paginated results.

     */
    inline DescribeParametersResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

    /**
     *
A list of parameters within a parameter group. Each element in the list
     * represents one parameter.

     */
    inline const Aws::Vector<Parameter>& GetParameters() const{ return m_parameters; }

    /**
     *
A list of parameters within a parameter group. Each element in the list
     * represents one parameter.

     */
    inline void SetParameters(const Aws::Vector<Parameter>& value) { m_parameters = value; }

    /**
     *
A list of parameters within a parameter group. Each element in the list
     * represents one parameter.

     */
    inline void SetParameters(Aws::Vector<Parameter>&& value) { m_parameters = std::move(value); }

    /**
     *
A list of parameters within a parameter group. Each element in the list
     * represents one parameter.

     */
    inline DescribeParametersResult& WithParameters(const Aws::Vector<Parameter>& value) { SetParameters(value); return *this;}

    /**
     *
A list of parameters within a parameter group. Each element in the list
     * represents one parameter.

     */
    inline DescribeParametersResult& WithParameters(Aws::Vector<Parameter>&& value) { SetParameters(std::move(value)); return *this;}

    /**
     *
A list of parameters within a parameter group. Each element in the list
     * represents one parameter.

     */
    inline DescribeParametersResult& AddParameters(const Parameter& value) { m_parameters.push_back(value); return *this; }

    /**
     *
A list of parameters within a parameter group. Each element in the list
     * represents one parameter.

     */
    inline DescribeParametersResult& AddParameters(Parameter&& value) { m_parameters.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_nextToken;

    Aws::Vector<Parameter> m_parameters;
  };

} // namespace Model
} // namespace DAX
} // namespace Aws


text:
<?php

/* TopxiaWebBundle:Default:navigation-li.html.twig */
class __TwigTemplate_7010611c14f72b0d0b35ad532b244e5eaba02eb34e2daa44ca267eda2d46d859 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_aaa82869710af2fafc48276b215a4074de84394facd4727825e148d8491b0a7f = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_aaa82869710af2fafc48276b215a4074de84394facd4727825e148d8491b0a7f->enter($__internal_aaa82869710af2fafc48276b215a4074de84394facd4727825e148d8491b0a7f_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "TopxiaWebBundle:Default:navigation-li.html.twig"));

        // line 1
        echo "
getContext($context, "subNavs"))) {
            echo "nav-hover";
        }
        if (((isset($context["siteNav"]) ? $context["siteNav"] : $this->getContext($context, "siteNav")) && ((isset($context["siteNav"]) ? $context["siteNav"] : $this->getContext($context, "siteNav")) == $this->getAttribute((isset($context["nav"]) ? $context["nav"] : $this->getContext($context, "nav")), "url", array())))) {
            echo " active ";
        }
        echo "\">
  getAttribute((isset($context["nav"]) ? $context["nav"] : $this->getContext($context, "nav")), "url", array())) {
            echo twig_escape_filter($this->env, $this->env->getExtension('Topxia\WebBundle\Twig\Extension\WebExtension')->navigationUrlFilter($this->getAttribute((isset($context["nav"]) ? $context["nav"] : $this->getContext($context, "nav")), "url", array())), "html", null, true);
        } else {
            echo "javascript:;";
        }
        echo "\" ";
        if ($this->getAttribute((isset($context["nav"]) ? $context["nav"] : $this->getContext($context, "nav")), "isNewWin", array())) {
            echo "target=\"_blank\"";
        }
        echo ">";
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["nav"]) ? $context["nav"] : $this->getContext($context, "nav")), "name", array()), "html", null, true);
        echo " ";
        if ((isset($context["subNavs"]) ? $context["subNavs"] : $this->getContext($context, "subNavs"))) {
            echo " ";
        }
        echo "
  ";
        // line 3
        if ((isset($context["subNavs"]) ? $context["subNavs"] : $this->getContext($context, "subNavs"))) {
            // line 4
            echo "

      ";
            // line 5
            $context['_parent'] = $context;
            $context['_seq'] = twig_ensure_traversable((isset($context["subNavs"]) ? $context["subNavs"] : $this->getContext($context, "subNavs")));
            foreach ($context['_seq'] as $context["_key"] => $context["subNav"]) {
                if ($this->getAttribute($context["subNav"], "isOpen", array())) {
                    // line 6
                    echo "
env, $this->env->getExtension('Topxia\WebBundle\Twig\Extension\WebExtension')->navigationUrlFilter($this->getAttribute($context["subNav"], "url", array())), "html", null, true);
                    echo "\"  ";
                    if ($this->getAttribute($context["subNav"], "isNewWin", array())) {
                        echo "target=\"_blank\"";
                    }
                    echo ">";
                    echo twig_escape_filter($this->env, $this->getAttribute($context["subNav"], "name", array()), "html", null, true);
                    echo "

      ";
                }
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['subNav'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
            // line 8
            echo "

  ";
        }
        // line 10
        echo "
";

        $__internal_aaa82869710af2fafc48276b215a4074de84394facd4727825e148d8491b0a7f->leave($__internal_aaa82869710af2fafc48276b215a4074de84394facd4727825e148d8491b0a7f_prof);

    }

    public function getTemplateName()
    {
        return "TopxiaWebBundle:Default:navigation-li.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  80 => 10,  76 => 8,  60 => 6,  55 => 5,  52 => 4,  50 => 3,  32 => 2,  22 => 1,);
    }

    public function getSource()
    {
        return "

  {{ nav.name }} {% if subNavs %} {% endif %}
  {% if subNavs %}

      {% for subNav in subNavs if subNav.isOpen %}

{{ subNav.name }}

      {% endfor %}

  {% endif %}

";
    }
}


text:
layout: tagpage
scripts: [mathjax, toggle]
lang: en
permalink: /tags/nepali-diary
chosen_tag: "Nepali diary"
ref: "tag nepalske zapisky"
---


text:
package http_prometheus

import (
	"net/http"

	"github.com/improbable-eng/go-httpwares/tags"
)

type meta struct {
	name, handler, method, host, path string
}

func reqMeta(req *http.Request, opts *options, inbound bool) *meta {
	m := &meta{name: opts.name, method: req.Method}

	var tags map[string]interface{}
	if inbound {
		tags = http_ctxtags.ExtractInbound(req).Values()
	} else {
		tags = http_ctxtags.ExtractOutbound(req).Values()
	}
	var v interface{}
	if m.name == "" {
		v, _ = tags[http_ctxtags.TagForCallService]
		m.name, _ = v.(string)
	}
	v, _ = tags[http_ctxtags.TagForHandlerName]
	hname, _ := v.(string)
	if hname != "" {
		v, _ = tags[http_ctxtags.TagForHandlerGroup]
		hgroup, _ := v.(string)
		if hgroup == "" {
			hgroup = "unknown"
		}
		m.handler = hgroup + "." + hname
	}

	if opts.hosts {
		m.host = req.URL.Host
		if m.host == "" {
			m.host = req.Host
		}
	}
	if opts.paths {
		m.path = req.URL.Path
	}
	return m
}


text:
'use strict';

// Declare app level module which depends on filters, and services
var myApp = angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives','jenkins','ngRoute']);

myApp.config(['$routeProvider', function($routeProvider) {
	//Environments
    $routeProvider.when('/environments', {
    	templateUrl: 'partials/environments.html',
    	controller: Environment_Ctrl
    });
    $routeProvider.when('/environment/:id?', {
    	templateUrl: 'partials/environment/get.html',
    	controller: EnvironmentCtrl
    });
    //Device
    $routeProvider.when('/device/:deviceType/:envId/:deviceId?', {
    	templateUrl: 'partials/devices/get.html',
    	controller: DeviceCtrl
    });
    $routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: MyCtrl2});
    $routeProvider.otherwise({redirectTo: '/view1'});
  }]);


text:
package it.unibz.krdb.obda.owlrefplatform.core;

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

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * A class that represents the preferences which can be modified by the user.
 */
public class QuestPreferences extends Properties {

	// TODO create a configuration listener to handle changes in these values
	private static final long	serialVersionUID		= -5954970472045517594L;

	private static final String	DEFAULT_PROPERTIESFILE	= "QuestDefaults.properties";

	public static final String	REFORMULATION_TECHNIQUE	= "org.obda.owlreformulationplatform.reformulationTechnique";
	public static final String	ABOX_MODE				= "org.obda.owlreformulationplatform.aboxmode";
	public static final String	DBTYPE					= "org.obda.owlreformulationplatform.dbtype";
//	public static final String	DATA_LOCATION			= "org.obda.owlreformulationplatform.datalocation";
	public static final String  OBTAIN_FROM_ONTOLOGY	= "org.obda.owlreformulationplatform.obtainFromOntology";
	public static final String  OBTAIN_FROM_MAPPINGS	= "org.obda.owlreformulationplatform.obtainFromMappings";
	public static final String  OPTIMIZE_EQUIVALENCES 	= "org.obda.owlreformulationplatform.optimizeEquivalences";

	/**
	 * Options to specify base IRI.
	 *
	 * @see Base IRI
	 */
	public static final String  BASE_IRI             	= "org.obda.owlreformulationplatform.baseiri";

	public static final String OBTAIN_FULL_METADATA = "OBTAIN_FULL_METADATA";

    public static final String SQL_GENERATE_REPLACE = "org.obda.owlreformulationplatform.sqlGenerateReplace";
	public static final String DISTINCT_RESULTSET = "org.obda.owlreformulationplatform.distinctResultSet";

	public static final String  REWRITE 	= "rewrite";

//	public static final String  OPTIMIZE_TBOX_SIGMA 	= "org.obda.owlreformulationplatform.optimizeTboxSigma";
//	public static final String 	CREATE_TEST_MAPPINGS 	= "org.obda.owlreformulationplatform.createTestMappings";

	public static final String STORAGE_LOCATION = "STORAGE_LOCATION";

	public static final String JDBC_URL = "JDBC_URL";

	public static final String DBNAME = "DBNAME";

	public static final String DBUSER = "DBUSER";

	public static final String DBPASSWORD = "DBPASSWORD";

	public static final String JDBC_DRIVER = "JDBC_DRIVER";

	public static final String PRINT_KEYS = "PRINT_KEYS";

	// Tomcat connection pool properties
	public static final String MAX_POOL_SIZE = "max_pool_size";
	public static final String INIT_POOL_SIZE = "initial_pool_size";
	public static final String REMOVE_ABANDONED = "remove_abandoned";
	public static final String ABANDONED_TIMEOUT = "abandoned_timeout";
	public static final String KEEP_ALIVE = "keep_alive";

	private Logger				log						= LoggerFactory.getLogger(QuestPreferences.class);

	public QuestPreferences() {
		try {
			readDefaultPropertiesFile();
		} catch (IOException e1) {
			log.error("Error reading default properties for resoner.");
			log.debug(e1.getMessage(), e1);
		}
	}

	public QuestPreferences(Properties values) {
		this();
		this.putAll(values);
	}

	public void readDefaultPropertiesFile() throws IOException {
		InputStream in = QuestPreferences.class.getResourceAsStream(DEFAULT_PROPERTIESFILE);
		readDefaultPropertiesFile(in);
	}

	/**
	 * Reads the properties from the input stream and sets them as default.
	 *
	 * @param in
	 *            The input stream.
	 */
	public void readDefaultPropertiesFile(InputStream in) throws IOException {
		this.load(in);
	}

	/**
	 * Returns the current value for the given parameter.
	 *
	 * @param var
	 *            The parameter value.
	 * @return The current value.
	 */
	public Object getCurrentValue(String var) {
		return get(var);
	}

	/**
	 * Returns the current value as boolean for the given parameter.
	 *
	 * @param var
	 *            The parameter value.
	 * @return The current value as boolean if possible null otherwise.
	 */
	public boolean getCurrentBooleanValueFor(String var) {
		String value = (String) getCurrentValue(var);
		return Boolean.parseBoolean(value);
	}

	/**
	 * Returns the current value as an integer for the given parameter.
	 *
	 * @param var
	 *            The parameter value.
	 * @return The current value as an integer if possible null otherwise.
	 */
	public int getCurrentIntegerValueFor(String var) {
		String value = (String) getCurrentValue(var);
		return Integer.parseInt(value);
	}

	/**
	 * Updates the current value of the given parameter to the given object
	 *
	 * @param var
	 *            The parameter.
	 * @param obj
	 *            The new current value.
	 */
	public void setCurrentValueOf(String var, Object obj) {
		put(var, obj);
	}

	public List<String> getReformulationPlatformPreferencesKeys(){
		ArrayList<String> keys = new ArrayList<String>();
		keys.add(REFORMULATION_TECHNIQUE);
		keys.add(ABOX_MODE);
		keys.add(DBTYPE);
//		keys.add(DATA_LOCATION);
		keys.add(OBTAIN_FROM_ONTOLOGY);
		keys.add(OBTAIN_FROM_MAPPINGS);
		keys.add(OPTIMIZE_EQUIVALENCES);
//		keys.add(OPTIMIZE_TBOX_SIGMA);
//		keys.add(CREATE_TEST_MAPPINGS);

		return keys;
	}
}


text:
{% extends "base.html" %}

{% block content %}

{% load staticfiles %}
{% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static "style_comments.css" %} ">

  x

{% load staticfiles %}

userfoo

 Subject of report

    	15-01-20 17:21
        UVA Community, PHP Hater

 Here is the short description of report.Here is the short description of report

    {% load staticfiles %}

       	Like

 xxx users like this report.

userfoo:hi~

                                2014-02-19 14:36
                                1 like
                                reply

userfoo2:hi~~~

                                2014-02-19 14:36
                                1 like
                                reply

                     <textarea class="comment" autocomplete="off">Comments</textarea>
                    <button class="btn">Reply</button>
                    0/140

{% endblock %}


text:
class RemoveDayEndtimeImmutableAddDescriptionToBlock < ActiveRecord::Migration
  def change
    remove_column :blocks, :day
    remove_column :blocks, :end_time
    remove_column :blocks, :immutable

    add_column    :blocks, :description, :text
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/rl_navigation"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#ff2AB7C9">

        <ImageView
            android:id="@+id/iv_left"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp"
            android:visibility="gone"
            android:src="@drawable/ic_more_left" />

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="更多"
            android:textColor="#ff040404"
            android:textSize="18sp"
            android:textStyle="bold" />

        <ImageView
            android:id="@+id/iv_right"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="20dp"
            android:src="@drawable/ic_more_right" />

    </RelativeLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp" />

</LinearLayout>


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "Background.h"
#include "sep.h"

void sep_back_c_java(JNIEnv *env, jclass cls, jobject obj, jclass bkmapcls, jobject bkmap, sepbackmap *p){
  /*set the globalback and globalrms field as return value*/
  jfieldID id_gback = (*env)->GetFieldID(env, bkmapcls, "globalback", "F");
  assert(id_gback != NULL);
  (*env)->SetFloatField(env, bkmap, id_gback, p->globalback);

  jfieldID id_rms = (*env)->GetFieldID(env, bkmapcls, "globalrms", "F");
  assert(id_rms != NULL);
  (*env)->SetFloatField(env, bkmap, id_rms, p->globalrms);

  /*set the w and h field as return value*/
  jfieldID id_w = (*env)->GetFieldID(env, bkmapcls, "w", "I");
  (*env)->SetIntField(env, bkmap, id_w, p->w);
  jfieldID id_h = (*env)->GetFieldID(env, bkmapcls, "h", "I");
  (*env)->SetIntField(env, bkmap, id_h, p->h);

  /*set the bw and bh field as return value*/
  jfieldID id_bw = (*env)->GetFieldID(env, bkmapcls, "bw", "I");
  (*env)->SetIntField(env, bkmap, id_bw, p->bw);
  jfieldID id_bh = (*env)->GetFieldID(env, bkmapcls, "bh", "I");
  (*env)->SetIntField(env, bkmap, id_bh, p->bh);

  /*set the nx, ny, and n field as return value*/
  jfieldID id_nx = (*env)->GetFieldID(env, bkmapcls, "nx", "I");
  (*env)->SetIntField(env, bkmap, id_nx, p->nx);
  jfieldID id_ny = (*env)->GetFieldID(env, bkmapcls, "ny", "I");
  (*env)->SetIntField(env, bkmap, id_ny, p->ny);
  jfieldID id_n = (*env)->GetFieldID(env, bkmapcls, "n", "I");
  (*env)->SetIntField(env, bkmap, id_n, p->n);

  jmethodID setBackID = (*env)->GetMethodID(env, bkmapcls, "setBack", "([F)V");
  jfloatArray backArray = (*env)->NewFloatArray(env, p->n);
  (*env)->SetFloatArrayRegion(env, backArray, 0, p->n, p->back);
  (*env)->CallVoidMethod(env, bkmap, setBackID, backArray);

  jmethodID setDbackID = (*env)->GetMethodID(env, bkmapcls, "setDback", "([F)V");
  jfloatArray dbackArray = (*env)->NewFloatArray(env, p->n);
  (*env)->SetFloatArrayRegion(env, dbackArray, 0, p->n, p->dback);
  (*env)->CallVoidMethod(env, bkmap, setDbackID, dbackArray);

  jmethodID setSigmaID = (*env)->GetMethodID(env, bkmapcls, "setSigma", "([F)V");
  jfloatArray sigmaArray = (*env)->NewFloatArray(env, p->n);
  (*env)->SetFloatArrayRegion(env, sigmaArray, 0, p->n, p->sigma);
  (*env)->CallVoidMethod(env, bkmap, setSigmaID, sigmaArray);

  jmethodID setDsigmaID = (*env)->GetMethodID(env, bkmapcls, "setDsigma", "([F)V");
  jfloatArray dsigmaArray = (*env)->NewFloatArray(env, p->n);
  (*env)->SetFloatArrayRegion(env, dsigmaArray, 0, p->n, p->dsigma);
  (*env)->CallVoidMethod(env, bkmap, setDsigmaID, dsigmaArray);
}

void sep_back_java_c(JNIEnv *env, jclass bkmapcls, jobject bkmap, sepbackmap *p, jfloatArray back, jfloatArray dback, jfloatArray sigma, jfloatArray dsigma){
  jfieldID id_h = (*env)->GetFieldID(env, bkmapcls, "h", "I");
  jint h = (*env)->GetIntField(env, bkmap, id_h);
  jfieldID id_w = (*env)->GetFieldID(env, bkmapcls, "w", "I");
  jint w = (*env)->GetIntField(env, bkmap, id_w);

  jfieldID id_bh = (*env)->GetFieldID(env, bkmapcls, "bh", "I");
  jint bh = (*env)->GetIntField(env, bkmap, id_bh);
  jfieldID id_bw = (*env)->GetFieldID(env, bkmapcls, "bw", "I");
  jint bw = (*env)->GetIntField(env, bkmap, id_bw);

  jfieldID id_nx = (*env)->GetFieldID(env, bkmapcls, "nx", "I");
  jint nx = (*env)->GetIntField(env, bkmap, id_nx);
  jfieldID id_ny = (*env)->GetFieldID(env, bkmapcls, "ny", "I");
  jint ny = (*env)->GetIntField(env, bkmap, id_ny);
  jfieldID id_n = (*env)->GetFieldID(env, bkmapcls, "n", "I");
  jint n = (*env)->GetIntField(env, bkmap, id_n);

  jfieldID id_gback = (*env)->GetFieldID(env, bkmapcls, "globalback", "F");
  jfloat gback = (*env)->GetFloatField(env, bkmap, id_gback);
  jfieldID id_rms = (*env)->GetFieldID(env, bkmapcls, "globalrms", "F");
  jfloat rms = (*env)->GetFloatField(env, bkmap, id_rms);

  /*need to implement new array access functions here*/
  jfloat *backarray = (jfloat *)(*env)->GetFloatArrayElements(env, back, NULL);
  jfloat *dbackarray = (jfloat *)(*env)->GetFloatArrayElements(env, dback, NULL);
  jfloat *sigmaarray = (jfloat *)(*env)->GetFloatArrayElements(env, sigma, NULL);
  jfloat *dsigmaarray = (jfloat *)(*env)->GetFloatArrayElements(env, dsigma, NULL);

  p->h = h;
  p->w = w;
  p->bh = bh;
  p->bw = bw;
  p->nx = nx;
  p->ny = ny;
  p->n = n;
  p->globalback = gback;
  p->globalrms = rms;

  jfloat *bp = p->back;
  jfloat *dbp = p->dback;
  jfloat *sp = p->sigma;
  jfloat *dsp = p->dsigma;

  memcpy(bp, backarray, sizeof(float)*(p->n));
  memcpy(dbp, dbackarray, sizeof(float)*(p->n));
  memcpy(sp, sigmaarray, sizeof(float)*(p->n));
  memcpy(dsp, dsigmaarray, sizeof(float)*(p->n));
}

JNIEXPORT jint JNICALL Java_Background_sep_1makeback
(JNIEnv *env, jobject obj, jbyteArray data, jobjectArray maskdata, jint dtype, jint mdtype, jint w, jint h, jint
 bw, jint bh, jdouble mthresh, jint fw, jint fh, jdouble fthresh, jobject backmap){

  int len = (*env)->GetArrayLength(env, data);
  jbyte *array = (jbyte *)(*env)->GetByteArrayElements(env, data, NULL);

  jboolean *mask;
  jbooleanArray dim = NULL;
  jbooleanArray oneDim = NULL;
  if(maskdata == NULL){
    mask = (void *)NULL;
  }
  else{
    /*parse the mask matrix*/
    int mlen1 = (*env)->GetArrayLength(env, maskdata);
    dim = (jbooleanArray)(*env)->GetObjectArrayElement(env, maskdata, 0);
    int mlen2 = (*env)->GetArrayLength(env, dim);
    printf("mlen2: %d\n", mlen2);
    mask = malloc(sizeof(jboolean)* mlen1 * mlen2);
    for(int i=0; i<mlen1; i++){
      oneDim = (jbooleanArray)(*env)->GetObjectArrayElement(env, maskdata, i);
      jboolean *element=(*env)->GetBooleanArrayElements(env, oneDim, 0);
      memcpy(mask+i*mlen2, element, sizeof(jboolean)*mlen2);
    }
  }

  /*printf("%d\n", len);
  for(int i=0; i<len; i++)
    printf("%d, ", (unsigned char)mask[i]);
  printf("\n");*/

  sepbackmap *p = (sepbackmap *)malloc(sizeof(sepbackmap));
  p->w = w;
  p->h = h;
  p->bw = bw;
  p->bh = bh;

  int status = sep_makeback(array, mask, dtype, mdtype, w, h, bw, bh, mthresh, fw, fh, fthresh, &p);

  //printf("%d\n", status);
  printf("C sep_makeback: %d\t%d\t%f\t%f\t%d\t%d\t%d\t%d\n", p->w, p->h, p->globalback, p->globalrms, p->bw, p->bh, p->nx, p->ny);
  printf("C sep_makeback back: %f\t dback: %f\n", *(p->back), *(p->dback));

  /*Finding the sepbackmap field in the Background class*/
  jclass cls = (*env)->GetObjectClass(env, obj);
  assert(cls != NULL);
  jfieldID id_bkmap = (*env)->GetFieldID(env, cls, "bkgmap", "LSepbackmap;");
  assert(id_bkmap != NULL);
  jobject bkmap = (*env)->GetObjectField(env, obj, id_bkmap);
  assert(bkmap != NULL);
  jclass bkmapcls = (*env)->GetObjectClass(env, bkmap);
  assert(bkmapcls != NULL);

  sep_back_c_java(env, cls, obj, bkmapcls, bkmap, p);

  float *fp = p->back;
  for(int i=0; i<p->n; i++){
    printf("back: %f\t", *(fp++));
  }
  printf("\n");

  fp = p->dback;
  for(int i=0; i<p->n; i++){
    printf("dback: %f\t", *(fp++));
  }
  printf("\n");

  fp = p->sigma;
  for(int i=0; i<p->n; i++){
    printf("sigma: %f\t", *(fp++));
  }
  printf("\n");

  fp = p->dsigma;
  for(int i=0; i<p->n; i++){
    printf("dsigma: %f\t", *(fp++));
  }
  printf("\n");
  free(array);
  free(p);

  if(mask != NULL){
    printf("C makeback: free mask\n");
    free(mask);
  }

  return status;
}

JNIEXPORT jint JNICALL Java_Background_sep_1backarray
  (JNIEnv *env, jobject obj, jobject bkmap, jbyteArray data, jint dtype, jfloatArray back, jfloatArray dback, jfloatArray sigma, jfloatArray dsigma){

  int len = (*env)->GetArrayLength(env, data);
  jbyte *array = (jbyte *)(*env)->GetByteArrayElements(env, data, NULL);

  jclass cls = (*env)->GetObjectClass(env, bkmap);
  assert(cls != NULL);

  int backLen = (*env)->GetArrayLength(env, back);
  sepbackmap *p = (sepbackmap *)malloc(sizeof(sepbackmap));
  p->back = malloc(sizeof(float)*backLen);
  p->dback = malloc(sizeof(float)*backLen);
  p->sigma = malloc(sizeof(float)*backLen);
  p->dsigma = malloc(sizeof(float)*backLen);

  sep_back_java_c(env, cls, bkmap, p, back, dback, sigma, dsigma);

  printf("C sep_backarray: %d\t%d\t%f\t%f\t%d\t%d\n", p->w, p->h, p->globalback, p->globalrms, p->bw, p->bh);
  printf("C sep_backarray: nx: %d \t ny: %d \t n: %d\n", p->nx, p->ny, p->n);
  printf("C sep_backarray: back: %f \t dback: %f\n", *(p->back), *(p->dback));
  printf("C sep_backarray: sigma: %f \t dsigma: %f\n", *(p->sigma), *(p->dsigma));

  int status = sep_backarray(p, array, dtype);
  printf("status: %d\n", status);
  (*env)->SetByteArrayRegion(env, data, 0, len, array);

  printf("%d, \n", array[0]);

  /*for(int i=0; i<len/8; i++){
    double d;
    memcpy(&d, (jbyte *)(array+i*8), sizeof(double));
    printf("%f, ", d);
  }*/

  free(array);
  free(p);
  return status;
}

JNIEXPORT jint JNICALL Java_Background_sep_1subbackarray
  (JNIEnv *env, jobject obj, jobject bkgmap, jobjectArray data, jint dtype, jfloatArray back, jfloatArray dback, jfloatArray sigma, jfloatArray dsigma)
{
  int len = (*env)->GetArrayLength(env, data);
  jbyte *array = (jbyte *)(*env)->GetByteArrayElements(env, data, NULL);

  jclass cls = (*env)->GetObjectClass(env, bkgmap);
  assert(cls != NULL);

  int backLen = (*env)->GetArrayLength(env, back);
  sepbackmap *p = (sepbackmap *)malloc(sizeof(sepbackmap));
  p->back = malloc(sizeof(float)*backLen);
  p->dback = malloc(sizeof(float)*backLen);
  p->sigma = malloc(sizeof(float)*backLen);
  p->dsigma = malloc(sizeof(float)*backLen);

  sep_back_java_c(env, cls, bkgmap, p, back, dback, sigma, dsigma);

  printf("C sep_subbackarray: %d\t%d\t%f\t%f\t%d\t%d\n", p->w, p->h, p->globalback, p->globalrms, p->bw, p->bh);
  printf("C sep_subbackarray: nx: %d \t ny: %d \t n: %d\n", p->nx, p->ny, p->n);
  printf("C sep_subbackarray: back: %f \t dback: %f\n", *(p->back), *(p->dback));
  printf("C sep_subbackarray: sigma: %f \t dsigma: %f\n", *(p->sigma), *(p->dsigma));

  int status = sep_subbackarray(p, array, dtype);
  (*env)->SetByteArrayRegion(env, data, 0, len, array);

  /*printf("C sep_subbackarray: result\n");
  double *dp = (double *)array;
  for(int i=0; i<len/8; i++){
    printf("%f, ", dp[i]);
  }
  printf("\n");*/

  return status;
}


text:
===============
Creating an App
===============

This guide will walk you through the steps of creating an app on the Messenger
Platform, and is largely based on Facebook's `quickstart guide`_. When you have
completed it, you will have a Facebook app set up for local hosting, ready to
develop.

First-time setup
----------------

1. Ensure you are logged into your Facebook account, which will be used for
   development. The category should be 'Apps for Messenger'.
2. Go to the Facebook `Apps`_ page and select 'Add a New App' to create your new
   development app.
3. Create a page for your app at `Create a Page`_.
4. Navigate to your App Dashboard. In the sidebar, select 'Messenger' and
   scroll down to 'Token Generation'. Select your page to generate a *page
   access token*, which will allow access to the Send API. Make a note of this
   token.
5. Think of a *verify token* for the Messenger Platform. This can be any string,
   and is used by Facebook to authenticate with your server.
6. Install `ngrok`_. You will use this to create an internet-accessible tunnel
   to the local server.
7. Install Boomerang, following :ref:`installation`.
8. Create a file called ``main.py`` and insert the following code to create an
   example echo server::

     from boomerang import Messenger, messages, events

     # Set the app's API access tokens, provided by Facebook
     VERIFY_TOKEN = 'your_webhook_token_here'
     PAGE_TOKEN = 'your_page_access_token_here'

     # Initialise the server
     app = Messenger(VERIFY_TOKEN, PAGE_TOKEN)

     @app.handle(events.MESSAGE_RECEIVED)
     async def message_received(self, message):

     # Print the received message
     print('Received message from {0}'.format(message.user_id))
     print('> {0}'.format(message.text))

     # Inform the sender that their message is being processed
     await self.acknowledge(message)

     # Return the message's text to respond
     return message.text

     app.run(hostname='0.0.0.0', debug=True)

   Your *verify token* and *page access token* should replace those in the code
   above.

Starting a development session
------------------------------

The following steps must be taken before each local development session. It may
look like a lot, but one you follow the process once it only takes 2-3 minutes.

1. Run ngrok. On a Unix system, the following command is used:

   .. code-block:: console

      $ ./ngrok http 0.0.0.0:8000

2. Make a note of your *secure forwarding URL*, which ngrok will display. It
   should start with ``https://`` and look something like
   ``https://47f86ce2.ngrok.io``.
3. Go to your App Dashboard. If this is your first time setting up a webhook
   for the app, select 'Messenger' in the sidebar, then 'Setup Webhooks'.
   Otherwise, select 'Webhooks' in the sidebar and 'Edit' to edit the existing
   subscription.
4. The *Callback URL* is simply your *secure forwarding URL* combined with
   ``/webhook``, like ``https://47f86ce2.ngrok.io/webhook``.
5. The *Verify Token* is your *verify token* that you thought up during initial
   set-up.
6. The necessary subscription field for the echo server is 'messages', but it
   doesn't hurt to select all the options beginning with 'message' and
   'messaging'.
7. Select 'Messenger' in the sidebar, scroll to the 'Webhooks' section and
   select your page to subscribe to the webhook.
8. Run the script:

   .. code-block:: console

      $ python main.py

   This will run the server locally on the default port. Ngrok will connect the
   *secure forwarding url* to this local server.

You're all set! The server can be stopped and restarted at will during
development. If ngrok is stopped, however, re-running it will change your
*secure forwarding url* and you will need to change the *Callback URL* in the
App Dashboard.

Ngrok is very helpful when testing your server. It can even be used to replay
requests made by Facebook for local testing. See `the website`_ for more!

.. _quickstart guide:
   https://developers.facebook.com/docs/messenger-platform/guides/quick-start
.. _Apps: https://developers.facebook.com/apps
.. _Create a Page: https://www.facebook.com/pages/create
.. _ngrok: https://ngrok.com/
.. _the website: https://ngrok.com/docs#replay


text:
"""Virtual adversarial training:a regularization method for supervised and semi-supervised learning.

Application to SSL of https://arxiv.org/abs/1704.03976
"""

import functools
import os

from absl import app
from absl import flags
from easydict import EasyDict
from libml import utils, data, layers, models
import tensorflow as tf
from third_party import vat_utils

FLAGS = flags.FLAGS

class VAT(models.MultiModel):

    def model(self, lr, wd, ema, warmup_pos, vat, vat_eps, entmin_weight, **kwargs):
        hwc = [self.dataset.height, self.dataset.width, self.dataset.colors]
        x_in = tf.placeholder(tf.float32, [None] + hwc, 'x')
        y_in = tf.placeholder(tf.float32, [None] + hwc, 'y')
        l_in = tf.placeholder(tf.int32, [None], 'labels')
        wd *= lr
        warmup = tf.clip_by_value(tf.to_float(self.step) / (warmup_pos * (FLAGS.train_kimg << 10)), 0, 1)

        classifier = functools.partial(self.classifier, **kwargs)
        l = tf.one_hot(l_in, self.nclass)
        logits_x = classifier(x_in, training=True)
        post_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)  # Take only first call to update batch norm.
        logits_y = classifier(y_in, training=True)
        delta_y = vat_utils.generate_perturbation(y_in, logits_y, lambda x: classifier(x, training=True), vat_eps)
        logits_student = classifier(y_in + delta_y, training=True)
        logits_teacher = tf.stop_gradient(logits_y)
        loss_vat = layers.kl_divergence_from_logits(logits_student, logits_teacher)
        loss_vat = tf.reduce_mean(loss_vat)
        loss_entmin = tf.reduce_mean(tf.distributions.Categorical(logits=logits_y).entropy())

        loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=l, logits=logits_x)
        loss = tf.reduce_mean(loss)
        tf.summary.scalar('losses/xe', loss)
        tf.summary.scalar('losses/vat', loss_vat)
        tf.summary.scalar('losses/entmin', loss_entmin)

        ema = tf.train.ExponentialMovingAverage(decay=ema)
        ema_op = ema.apply(utils.model_vars())
        ema_getter = functools.partial(utils.getter_ema, ema)
        post_ops.append(ema_op)
        post_ops.extend([tf.assign(v, v * (1 - wd)) for v in utils.model_vars('classify') if 'kernel' in v.name])

        train_op = tf.train.AdamOptimizer(lr).minimize(loss + loss_vat * warmup * vat + entmin_weight * loss_entmin,
                                                       colocate_gradients_with_ops=True)
        with tf.control_dependencies([train_op]):
            train_op = tf.group(*post_ops)

        # Tuning op: only retrain batch norm.
        skip_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
        classifier(x_in, training=True)
        train_bn = tf.group(*[v for v in tf.get_collection(tf.GraphKeys.UPDATE_OPS)
                              if v not in skip_ops])

        return EasyDict(
            x=x_in, y=y_in, label=l_in, train_op=train_op, tune_op=train_bn,
            classify_raw=tf.nn.softmax(classifier(x_in, training=False)),  # No EMA, for debugging.
            classify_op=tf.nn.softmax(classifier(x_in, getter=ema_getter, training=False)))

def main(argv):
    del argv  # Unused.
    dataset = data.DATASETS[FLAGS.dataset]()
    log_width = utils.ilog2(dataset.width)
    model = VAT(
        os.path.join(FLAGS.train_dir, dataset.name),
        dataset,
        lr=FLAGS.lr,
        wd=FLAGS.wd,
        arch=FLAGS.arch,
        warmup_pos=FLAGS.warmup_pos,
        batch=FLAGS.batch,
        nclass=dataset.nclass,
        ema=FLAGS.ema,
        smoothing=FLAGS.smoothing,
        vat=FLAGS.vat,
        vat_eps=FLAGS.vat_eps,
        entmin_weight=FLAGS.entmin_weight,

        scales=FLAGS.scales or (log_width - 2),
        filters=FLAGS.filters,
        repeat=FLAGS.repeat)
    model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10)

if __name__ == '__main__':
    utils.setup_tf()
    flags.DEFINE_float('wd', 0.02, 'Weight decay.')
    flags.DEFINE_float('vat', 0.3, 'VAT weight.')
    flags.DEFINE_float('vat_eps', 6, 'VAT perturbation size.')
    flags.DEFINE_float('entmin_weight', 0.06, 'Entropy minimization weight.')
    flags.DEFINE_float('warmup_pos', 0.4, 'Relative position at which constraint loss warmup ends.')
    flags.DEFINE_float('ema', 0.999, 'Exponential moving average of params.')
    flags.DEFINE_float('smoothing', 0.1, 'Label smoothing.')
    flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.')
    flags.DEFINE_integer('filters', 32, 'Filter size of convolutions.')
    flags.DEFINE_integer('repeat', 4, 'Number of residual layers per stage.')
    FLAGS.set_default('dataset', 'cifar10.3@250-5000')
    FLAGS.set_default('batch', 64)
    FLAGS.set_default('lr', 0.002)
    FLAGS.set_default('train_kimg', 1 << 16)
    app.run(main)


text:
/**
 * This application demonstrates how to perform basic operations on files with
 * the Google Cloud Storage API.
 *
 * For more information, see the README.md under /storage and the documentation
 * at https://cloud.google.com/storage/docs.
 */

'use strict';

const Storage = require('@google-cloud/storage');

// [START storage_list_files]
function listFiles (bucketName) {
  // Instantiates a client
  const storage = Storage();

  // References an existing bucket, e.g. "my-bucket"
  const bucket = storage.bucket(bucketName);

  // Lists files in the bucket
  return bucket.getFiles()
    .then((results) => {
      const files = results[0];

      console.log('Files:');
      files.forEach((file) => console.log(file.name));

      return files;
    });
}
// [END storage_list_files]

// [START storage_list_files_with_prefix]
function listFilesByPrefix (bucketName, prefix, delimiter) {
  // Instantiates a client
  const storage = Storage();

  // References an existing bucket, e.g. "my-bucket"
  const bucket = storage.bucket(bucketName);

  /**
   * This can be used to list all blobs in a "folder", e.g. "public/".
   *
   * The delimiter argument can be used to restrict the results to only the
   * "files" in the given "folder". Without the delimiter, the entire tree under
   * the prefix is returned. For example, given these blobs:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * If you just specify prefix = '/a', you'll get back:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * However, if you specify prefix='/a' and delimiter='/', you'll get back:
   *
   *   /a/1.txt
   */
  const options = {
    prefix: prefix
  };
  if (delimiter) {
    options.delimiter = delimiter;
  }

  // Lists files in the bucket, filtered by a prefix
  return bucket.getFiles(options)
    .then((results) => {
      const files = results[0];

      console.log('Files:');
      files.forEach((file) => console.log(file.name));

      return files;
    });
}
// [END storage_list_files_with_prefix]

// [START storage_upload_file]
function uploadFile (bucketName, fileName) {
  // Instantiates a client
  const storage = Storage();

  // References an existing bucket, e.g. "my-bucket"
  const bucket = storage.bucket(bucketName);

  // Uploads a local file to the bucket, e.g. "./local/path/to/file.txt"
  return bucket.upload(fileName)
    .then((results) => {
      const file = results[0];

      console.log(`File ${file.name} uploaded.`);

      return file;
    });
}
// [END storage_upload_file]

// [START storage_download_file]
function downloadFile (bucketName, srcFileName, destFileName) {
  // Instantiates a client
  const storage = Storage();

  // References an existing bucket, e.g. "my-bucket"
  const bucket = storage.bucket(bucketName);

  // References an existing file, e.g. "file.txt"
  const file = bucket.file(srcFileName);

  const options = {
    // The path to which the file should be downloaded, e.g. "./file.txt"
    destination: destFileName
  };

  // Downloads the file
  return file.download(options)
    .then(() => {
      console.log(`File ${file.name} downloaded to ${destFileName}.`);
    });
}
// [END storage_download_file]

// [START storage_delete_file]
function deleteFile (bucketName, fileName) {
  // Instantiates a client
  const storage = Storage();

  // References an existing bucket, e.g. "my-bucket"
  const bucket = storage.bucket(bucketName);

  // References an existing file, e.g. "file.txt"
  const file = bucket.file(fileName);

  // Deletes the file from the bucket
  return file.delete()
    .then(() => {
      console.log(`File ${fileName} deleted.`);
    });
}
// [END storage_delete_file]

// [START storage_get_metadata]
function getMetadata (bucketName, fileName) {
  // Instantiates a client
  const storage = Storage();

  // References an existing bucket, e.g. "my-bucket"
  const bucket = storage.bucket(bucketName);

  // References an existing file, e.g. "file.txt"
  const file = bucket.file(fileName);

  // Gets the metadata for the file
  return file.getMetadata()
    .then((results) => {
      const metadata = results[0];

      console.log(`File: ${metadata.name}`);
      console.log(`Bucket: ${metadata.bucket}`);
      console.log(`Storage class: ${metadata.storageClass}`);
      console.log(`ID: ${metadata.id}`);
      console.log(`Size: ${metadata.size}`);
      console.log(`Updated: ${metadata.updated}`);
      console.log(`Generation: ${metadata.generation}`);
      console.log(`Metageneration: ${metadata.metageneration}`);
      console.log(`Etag: ${metadata.etag}`);
      console.log(`Owner: ${metadata.owner}`);
      console.log(`Component count: ${metadata.component_count}`);
      console.log(`Crc32c: ${metadata.crc32c}`);
      console.log(`md5Hash: ${metadata.md5Hash}`);
      console.log(`Cache-control: ${metadata.cacheControl}`);
      console.log(`Content-type: ${metadata.contentType}`);
      console.log(`Content-disposition: ${metadata.contentDisposition}`);
      console.log(`Content-encoding: ${metadata.contentEncoding}`);
      console.log(`Content-language: ${metadata.contentLanguage}`);
      console.log(`Metadata: ${metadata.metadata}`);

      return metadata;
    });
}
// [END storage_get_metadata]

// [START storage_make_public]
function makePublic (bucketName, fileName) {
  // Instantiates a client
  const storage = Storage();

  // References an existing bucket, e.g. "my-bucket"
  const bucket = storage.bucket(bucketName);

  // References an existing file, e.g. "file.txt"
  const file = bucket.file(fileName);

  // Makes the file public
  return file.makePublic()
    .then(() => {
      console.log(`File ${file.name} is now public.`);
    });
}
// [END storage_make_public]

// [START storage_generate_signed_url]
function generateSignedUrl (bucketName, fileName) {
  // Instantiates a client
  const storage = Storage();

  // References an existing bucket, e.g. "my-bucket"
  const bucket = storage.bucket(bucketName);

  // References an existing file, e.g. "file.txt"
  const file = bucket.file(fileName);

  // These options will allow temporary read access to the file
  const options = {
    action: 'read',
    expires: '03-17-2025'
  };

  // Get a signed URL for the file
  return file.getSignedUrl(options)
    .then((results) => {
      const url = results[0];

      console.log(`The signed url for ${file.name} is ${url}.`);

      return url;
    });
}
// [END storage_generate_signed_url]

// [START storage_move_file]
function moveFile (bucketName, srcFileName, destFileName) {
  // Instantiates a client
  const storage = Storage();

  // References an existing bucket, e.g. "my-bucket"
  const bucket = storage.bucket(bucketName);

  // References an existing file, e.g. "file.txt"
  const file = bucket.file(srcFileName);

  // Moves the file within the bucket
  return file.move(destFileName)
    .then(() => {
      console.log(`File ${file.name} moved to ${destFileName}.`);
    });
}
// [END storage_move_file]

// [START storage_copy_file]
function copyFile (srcBucketName, srcFileName, destBucketName, destFileName) {
  // Instantiates a client
  const storage = Storage();

  // References an existing bucket, e.g. "my-bucket"
  const bucket = storage.bucket(srcBucketName);

  // References an existing file, e.g. "file.txt"
  const file = bucket.file(srcFileName);

  // References another existing bucket, e.g. "my-other-bucket"
  const destBucket = storage.bucket(destBucketName);

  // Creates a reference to a destination file, e.g. "file.txt"
  const destFile = destBucket.file(destFileName);

  // Copies the file to the other bucket
  return file.copy(destFile)
    .then((results) => {
      const file = results[0];

      console.log(`File ${srcFileName} copied to ${file.name} in ${destBucket.name}.`);

      return file;
    });
}
// [END storage_copy_file]

require(`yargs`)
  .demand(1)
  .command(
    `list <bucketName> [prefix] [delimiter]`,
    `Lists files in a bucket, optionally filtering by a prefix.`,
    {},
    (opts) => {
      if (opts.prefix) {
        listFilesByPrefix(opts.bucketName, opts.prefix, opts.delimiter);
      } else {
        listFiles(opts.bucketName);
      }
    }
  )
  .command(
    `upload <bucketName> <srcFileName>`,
    `Uploads a local file to a bucket.`,
    {},
    (opts) => uploadFile(opts.bucketName, opts.srcFileName)
  )
  .command(
    `download <bucketName> <srcFileName> <destFileName>`,
    `Downloads a file from a bucket.`,
    {},
    (opts) => downloadFile(opts.bucketName, opts.srcFileName, opts.destFileName)
  )
  .command(
    `delete <bucketName> <fileName>`,
    `Deletes a file from a bucket.`,
    {},
    (opts) => deleteFile(opts.bucketName, opts.fileName)
  )
  .command(
    `get-metadata <bucketName> <fileName>`,
    `Gets the metadata for a file.`,
    {},
    (opts) => getMetadata(opts.bucketName, opts.fileName)
  )
  .command(
    `make-public <bucketName> <fileName>`,
    `Makes a file public.`,
    {},
    (opts) => makePublic(opts.bucketName, opts.fileName)
  )
  .command(
    `generate-signed-url <bucketName> <fileName>`,
    `Generates a signed URL for a file.`,
    {},
    (opts) => generateSignedUrl(opts.bucketName, opts.fileName)
  )
  .command(
    `move <bucketName> <srcFileName> <destFileName>`,
    `Moves a file to a new location within the same bucket, i.e. rename the file.`,
    {},
    (opts) => moveFile(opts.bucketName, opts.srcFileName, opts.destFileName)
  )
  .command(
    `copy <srcBucketName> <srcFileName> <destBucketName> <destFileName>`,
    `Copies a file in a bucket to another bucket.`,
    {},
    (opts) => copyFile(opts.srcBucketName, opts.srcFileName, opts.destBucketName, opts.destFileName)
  )
  .example(`node $0 list my-bucket`, `Lists files in "my-bucket".`)
  .example(`node $0 list my-bucket public/`, `Lists files in "my-bucket" filtered by prefix "public/".`)
  .example(`node $0 upload my-bucket ./file.txt`, `Uploads "./file.txt" to "my-bucket".`)
  .example(`node $0 download my-bucket file.txt ./file.txt`, `Downloads "gs://my-bucket/file.txt" to "./file.txt".`)
  .example(`node $0 delete my-bucket file.txt`, `Deletes "gs://my-bucket/file.txt".`)
  .example(`node $0 get-metadata my-bucket file.txt`, `Gets the metadata for "gs://my-bucket/file.txt".`)
  .example(`node $0 make-public my-bucket file.txt`, `Makes "gs://my-bucket/file.txt" public.`)
  .example(`node $0 move my-bucket file.txt file2.txt`, `Renames "gs://my-bucket/file.txt" to "gs://my-bucket/file2.txt".`)
  .example(`node $0 copy my-bucket file.txt my-other-bucket file.txt`, `Copies "gs://my-bucket/file.txt" to "gs://my-other-bucket/file.txt".`)
  .wrap(120)
  .recommendCommands()
  .epilogue(`For more information, see https://cloud.google.com/storage/docs`)
  .help()
  .strict()
  .argv;


text:
// /db/repl/rs.h

#pragma once

#include "mongo/db/commands.h"
#include "mongo/db/index.h"
#include "mongo/db/repl/oplogreader.h"
#include "mongo/db/repl/optime.h"
#include "mongo/db/repl/rs_config.h"
#include "mongo/db/repl/rs_exception.h"
#include "mongo/db/repl/rs_member.h"
#include "mongo/db/repl/rs_sync.h"
#include "mongo/util/concurrency/list.h"
#include "mongo/util/concurrency/msg.h"
#include "mongo/util/concurrency/thread_pool.h"
#include "mongo/util/concurrency/value.h"
#include "mongo/util/net/hostandport.h"

/**
 * Order of Events
 *
 * On startup, if the --replSet option is present, startReplSets is called.
 * startReplSets forks off a new thread for replica set activities.  It creates
 * the global theReplSet variable and calls go() on it.
 *
 * theReplSet's constructor changes the replica set's state to RS_STARTUP,
 * starts the replica set manager, and loads the config (if the replica set
 * has been initialized).
 */

namespace mongo {

    class Cloner;
    class DBClientConnection;
    struct HowToFixUp;
    class ReplSetImpl;
    struct Target;
    extern bool replSet; // true if using repl sets
    extern class ReplSet *theReplSet; // null until initialized
    extern Tee *rsLog;
    class ReplSetCmdline;

    // Main entry point for replica sets
    void startReplSets(ReplSetCmdline *replSetCmdline);

    /* member of a replica set */
    class Member : public List1<Member>::Base {
    private:
        ~Member(); // intentionally unimplemented as should never be called -- see List1<>::Base.
        Member(const Member&);
    public:
        Member(HostAndPort h, unsigned ord, const ReplSetConfig::MemberCfg *c, bool self);

        string fullName() const { return h().toString(); }
        const ReplSetConfig::MemberCfg& config() const { return _config; }
        ReplSetConfig::MemberCfg& configw() { return _config; }
        const HeartbeatInfo& hbinfo() const { return _hbinfo; }
        HeartbeatInfo& get_hbinfo() { return _hbinfo; }
        string lhb() const { return _hbinfo.lastHeartbeatMsg; }
        MemberState state() const { return _hbinfo.hbstate; }
        const HostAndPort& h() const { return _h; }
        unsigned id() const { return _hbinfo.id(); }

        bool potentiallyHot() const { return _config.potentiallyHot(); } // not arbiter, not priority 0
        void summarizeMember(stringstream& s) const;
        // If we could sync from this member.  This doesn't tell us anything about the quality of
        // this member, just if they are a possible sync target.
        bool syncable() const;

    private:
        friend class ReplSetImpl;
        ReplSetConfig::MemberCfg _config;
        const HostAndPort _h;
        HeartbeatInfo _hbinfo;
    };

    class Manager : public task::Server {
        ReplSetImpl *rs;
        bool busyWithElectSelf;
        int _primary;

        /** @param two - if true two primaries were seen.  this can happen transiently, in addition to our
                         polling being only occasional.  in this case null is returned, but the caller should
                         not assume primary itself in that situation.
        */
        const Member* findOtherPrimary(bool& two);

        void noteARemoteIsPrimary(const Member *);
        void checkElectableSet();
        void checkAuth();
        virtual void starting();
    public:
        Manager(ReplSetImpl *rs);
        virtual ~Manager();
        void msgReceivedNewConfig(BSONObj);
        void msgCheckNewState();
    };

    class GhostSync : public task::Server {
        struct GhostSlave : boost::noncopyable {
            GhostSlave() : last(0), slave(0), init(false) { }
            OplogReader reader;
            OpTime last;
            Member* slave;
            bool init;
        };
        /**
         * This is a cache of ghost slaves
         */
        typedef map< mongo::OID,shared_ptr<GhostSlave> > MAP;
        MAP _ghostCache;
        RWLock _lock; // protects _ghostCache
        ReplSetImpl *rs;
        virtual void starting();
    public:
        GhostSync(ReplSetImpl *_rs) : task::Server("rsGhostSync"), _lock("GhostSync"), rs(_rs) {}
        ~GhostSync() {
            log() << "~GhostSync() called" << rsLog;
        }

        /**
         * Replica sets can sync in a hierarchical fashion, which throws off w
         * calculation on the master.  percolate() faux-syncs from an upstream
         * node so that the primary will know what the slaves are up to.
         *
         * We can't just directly sync to the primary because it could be
         * unreachable, e.g., S1--->S2--->S3--->P.  S2 should ghost sync from S3
         * and S3 can ghost sync from the primary.
         *
         * Say we have an S1--->S2--->P situation and this node is S2.  rid
         * would refer to S1.  S2 would create a ghost slave of S1 and connect
         * it to P (_currentSyncTarget). Then it would use this connection to
         * pretend to be S1, replicating off of P.
         */
        void percolate(const BSONObj& rid, const OpTime& last);
        void associateSlave(const BSONObj& rid, const int memberId);
        void updateSlave(const mongo::OID& id, const OpTime& last);
        void clearCache();
    };

    class Consensus {
        ReplSetImpl &rs;
        struct LastYea {
            LastYea() : when(0), who(0xffffffff) { }
            time_t when;
            unsigned who;
        };
        static SimpleMutex lyMutex;
        Guarded<LastYea,lyMutex> ly;
        unsigned yea(unsigned memberId); // throws VoteException
        void electionFailed(unsigned meid);
        void _electSelf();
        bool weAreFreshest(bool& allUp, int& nTies);
        bool sleptLast; // slept last elect() pass
    public:
        Consensus(ReplSetImpl *t) : rs(*t) {
            sleptLast = false;
            steppedDown = 0;
        }

        /* if we've stepped down, this is when we are allowed to try to elect ourself again.
           todo: handle possible weirdnesses at clock skews etc.
        */
        time_t steppedDown;

        int totalVotes() const;
        bool aMajoritySeemsToBeUp() const;
        bool shouldRelinquish() const;
        void electSelf();
        void electCmdReceived(BSONObj, BSONObjBuilder*);
        void multiCommand(BSONObj cmd, list<Target>& L);
    };

    /**
     * most operations on a ReplSet object should be done while locked. that
     * logic implemented here.
     *
     * Order of locking: lock the replica set, then take a rwlock.
     */
    class RSBase : boost::noncopyable {
    public:
        const unsigned magic;
        void assertValid() { verify( magic == 0x12345677 ); }
    private:
        mongo::mutex m;
        int _locked;
        ThreadLocalValue<bool> _lockedByMe;
    protected:
        RSBase() : magic(0x12345677), m("RSBase"), _locked(0) { }
        ~RSBase() {
            /* this can happen if we throw in the constructor; otherwise never happens.  thus we log it as it is quite unusual. */
            log() << "replSet ~RSBase called" << rsLog;
        }

    public:
        class lock {
            RSBase& rsbase;
            auto_ptr<scoped_lock> sl;
        public:
            lock(RSBase* b) : rsbase(*b) {
                if( rsbase._lockedByMe.get() )
                    return; // recursive is ok...

                sl.reset( new scoped_lock(rsbase.m) );
                DEV verify(rsbase._locked == 0);
                rsbase._locked++;
                rsbase._lockedByMe.set(true);
            }
            ~lock() {
                if( sl.get() ) {
                    verify( rsbase._lockedByMe.get() );
                    DEV verify(rsbase._locked == 1);
                    rsbase._lockedByMe.set(false);
                    rsbase._locked--;
                }
            }
        };

        /* for asserts */
        bool locked() const { return _locked != 0; }

        /* if true, is locked, and was locked by this thread. note if false, it could be in the lock or not for another
           just for asserts & such so we can make the contracts clear on who locks what when.
           we don't use these locks that frequently, so the little bit of overhead is fine.
        */
        bool lockedByMe() { return _lockedByMe.get(); }
    };

    class ReplSetHealthPollTask;

    /* safe container for our state that keeps member pointer and state variables always aligned */
    class StateBox : boost::noncopyable {
    public:
        struct SP { // SP is like pair<MemberState,const Member *> but nicer
            SP() : state(MemberState::RS_STARTUP), primary(0) { }
            MemberState state;
            const Member *primary;
        };
        const SP get() {
            rwlock lk(m, false);
            return sp;
        }
        MemberState getState() const {
            rwlock lk(m, false);
            return sp.state;
        }
        const Member* getPrimary() const {
            rwlock lk(m, false);
            return sp.primary;
        }
        void change(MemberState s, const Member *self) {
            rwlock lk(m, true);
            if( sp.state != s ) {
                log() << "replSet " << s.toString() << rsLog;
            }
            sp.state = s;
            if( s.primary() ) {
                sp.primary = self;
            }
            else {
                if( self == sp.primary )
                    sp.primary = 0;
            }
        }
        void set(MemberState s, const Member *p) {
            rwlock lk(m, true);
            sp.state = s;
            sp.primary = p;
        }
        void setSelfPrimary(const Member *self) { change(MemberState::RS_PRIMARY, self); }
        void setOtherPrimary(const Member *mem) {
            rwlock lk(m, true);
            verify( !sp.state.primary() );
            sp.primary = mem;
        }
        void noteRemoteIsPrimary(const Member *remote) {
            rwlock lk(m, true);
            verify(!sp.state.primary());
            sp.primary = remote;
        }
        StateBox() : m("StateBox") { }
    private:
        RWLock m;
        SP sp;
    };

    void parseReplsetCmdLine(const std::string& cfgString,
                             string& setname,
                             vector<HostAndPort>& seeds,
                             set<HostAndPort>& seedSet);

    /** Parameter given to the --replSet command line option (parsed).
        Syntax is "<setname>/<seedhost1>,<seedhost2>"
        where setname is a name and seedhost is "<host>[:<port>]" */
    class ReplSetCmdline {
    public:
        ReplSetCmdline(const std::string& cfgString) { parseReplsetCmdLine(cfgString, setname, seeds, seedSet); }
        string setname;
        vector<HostAndPort> seeds;
        set<HostAndPort> seedSet;
    };

    /* information about the entire repl set, such as the various servers in the set, and their state */
    /* note: We currently do not free mem when the set goes away - it is assumed the replset is a
             singleton and long lived.
    */
    class ReplSetImpl : protected RSBase {
    public:
        /** info on our state if the replset isn't yet "up".  for example, if we are pre-initiation. */
        enum StartupStatus {
            PRESTART=0, LOADINGCONFIG=1, BADCONFIG=2, EMPTYCONFIG=3,
            EMPTYUNREACHABLE=4, STARTED=5, SOON=6
        };
        static StartupStatus startupStatus;
        static DiagStr startupStatusMsg;
        static string stateAsHtml(MemberState state);

        /* todo thread */
        void msgUpdateHBInfo(HeartbeatInfo);

        StateBox box;

        OpTime lastOpTimeWritten;
        long long lastH; // hash we use to make sure we are reading the right flow of ops and aren't on an out-of-date "fork"
        bool forceSyncFrom(const string& host, string& errmsg, BSONObjBuilder& result);
        // Check if the current sync target is suboptimal. This must be called while holding a mutex
        // that prevents the sync source from changing.
        bool shouldChangeSyncTarget(const OpTime& target) const;

        /**
         * Find the closest member (using ping time) with a higher latest optime.
         */
        const Member* getMemberToSyncTo();
        void veto(const string& host, unsigned secs=10);
        bool gotForceSync();
        void goStale(const Member* m, const BSONObj& o);
    private:
        set<ReplSetHealthPollTask*> healthTasks;
        void endOldHealthTasks();
        void startHealthTaskFor(Member *m);

        Consensus elect;
        void relinquish();
        void forgetPrimary();
    protected:
        bool _stepDown(int secs);
        bool _freeze(int secs);
    private:
        void assumePrimary();
        void loadLastOpTimeWritten(bool quiet=false);
        void changeState(MemberState s);

        Member* _forceSyncTarget;

        bool _blockSync;
        void blockSync(bool block);

        // set of electable members' _ids
        set<unsigned> _electableSet;
    protected:
        // "heartbeat message"
        // sent in requestHeartbeat respond in field "hbm"
        char _hbmsg[256]; // we change this unlocked, thus not an stl::string
        time_t _hbmsgTime; // when it was logged
    public:
        void sethbmsg(const std::string& s, int logLevel = 0);

        /**
         * Election with Priorities
         *
         * Each node (n) keeps a set of nodes that could be elected primary.
         * Each node in this set:
         *
         *  1. can connect to a majority of the set
         *  2. has a priority greater than 0
         *  3. has an optime within 10 seconds of the most up-to-date node
         *     that n can reach
         *
         * If a node fails to meet one or more of these criteria, it is removed
         * from the list.  This list is updated whenever the node receives a
         * heartbeat.
         *
         * When a node sends an "am I freshest?" query, the node receiving the
         * query checks their electable list to make sure that no one else is
         * electable AND higher priority.  If this check passes, the node will
         * return an "ok" response, if not, it will veto.
         *
         * If a node is primary and there is another node with higher priority
         * on the electable list (i.e., it must be synced to within 10 seconds
         * of the current primary), the node (or nodes) with connections to both
         * the primary and the secondary with higher priority will issue
         * replSetStepDown requests to the primary to allow the higher-priority
         * node to take over.
         */
        void addToElectable(const unsigned m) { lock lk(this); _electableSet.insert(m); }
        void rmFromElectable(const unsigned m) { lock lk(this); _electableSet.erase(m); }
        bool iAmElectable() { lock lk(this); return _electableSet.find(_self->id()) != _electableSet.end(); }
        bool isElectable(const unsigned id) { lock lk(this); return _electableSet.find(id) != _electableSet.end(); }
        Member* getMostElectable();
    protected:
        /**
         * Load a new config as the replica set's main config.
         *
         * If there is a "simple" change (just adding a node), this shortcuts
         * the config. Returns true if the config was changed.  Returns false
         * if the config doesn't include a this node.  Throws an exception if
         * something goes very wrong.
         *
         * Behavior to note:
         *  - locks this
         *  - intentionally leaks the old _cfg and any old _members (if the
         *    change isn't strictly additive)
         */
        bool initFromConfig(ReplSetConfig& c, bool reconf=false);
        void _fillIsMaster(BSONObjBuilder&);
        void _fillIsMasterHost(const Member*, vector<string>&, vector<string>&, vector<string>&);
        const ReplSetConfig& config() { return *_cfg; }
        string name() const { return _name; } /* @return replica set's logical name */
        MemberState state() const { return box.getState(); }
        void _fatal();
        void _getOplogDiagsAsHtml(unsigned server_id, stringstream& ss) const;
        void _summarizeAsHtml(stringstream&) const;
        void _summarizeStatus(BSONObjBuilder&) const; // for replSetGetStatus command

        /* call afer constructing to start - returns fairly quickly after launching its threads */
        void _go();

    private:
        string _name;
        const vector<HostAndPort> *_seeds;
        ReplSetConfig *_cfg;

        /**
         * Finds the configuration with the highest version number and attempts
         * load it.
         */
        bool _loadConfigFinish(vector<ReplSetConfig*>& v);
        /**
         * Gather all possible configs (from command line seeds, our own config
         * doc, and any hosts listed therein) and try to initiate from the most
         * recent config we find.
         */
        void loadConfig();

        list<HostAndPort> memberHostnames() const;
        bool iAmArbiterOnly() const { return myConfig().arbiterOnly; }
        bool iAmPotentiallyHot() const {
          return myConfig().potentiallyHot() && // not an arbiter
            elect.steppedDown <= time(0) && // not stepped down/frozen
            state() == MemberState::RS_SECONDARY; // not stale
        }
    protected:
        Member *_self;
        bool _buildIndexes;       // = _self->config().buildIndexes

        ReplSetImpl();
        /* throws exception if a problem initializing. */
        void init(ReplSetCmdline&);

        void setSelfTo(Member *); // use this as it sets buildIndexes var
    private:
        List1<Member> _members; // all members of the set EXCEPT _self.
        ReplSetConfig::MemberCfg _config; // config of _self
        unsigned _id; // _id of _self

        int _maintenanceMode; // if we should stay in recovering state
    public:
        // this is called from within a writelock in logOpRS
        unsigned selfId() const { return _id; }
        Manager *mgr;
        GhostSync *ghost;
        /**
         * This forces a secondary to go into recovering state and stay there
         * until this is called again, passing in "false".  Multiple threads can
         * call this and it will leave maintenance mode once all of the callers
         * have called it again, passing in false.
         */
        bool setMaintenanceMode(const bool inc);

        // Records a new slave's id in the GhostSlave map, at handshake time.
        void registerSlave(const BSONObj& rid, const int memberId);
    private:
        Member* head() const { return _members.head(); }
    public:
        const Member* findById(unsigned id) const;
        Member* findByName(const std::string& hostname) const;
    private:
        void _getTargets(list<Target>&, int &configVersion);
        void getTargets(list<Target>&, int &configVersion);
        void startThreads();
        friend class FeedbackThread;
        friend class CmdReplSetElect;
        friend class Member;
        friend class Manager;
        friend class GhostSync;
        friend class Consensus;

    private:
        bool _syncDoInitialSync_clone(Cloner &cloner, const char *master,
                                      const list<string>& dbs, bool dataPass);
        bool _syncDoInitialSync_applyToHead( replset::SyncTail& syncer, OplogReader* r ,
                                             const Member* source, const BSONObj& lastOp,
                                             BSONObj& minValidOut);
        void _syncDoInitialSync();
        void syncDoInitialSync();
        void _syncThread();
        void syncTail();
        unsigned _syncRollback(OplogReader& r);
        void syncFixUp(HowToFixUp& h, OplogReader& r);

        // keep a list of hosts that we've tried recently that didn't work
        map<string,time_t> _veto;
        // persistent pool of worker threads for writing ops to the databases
        threadpool::ThreadPool _writerPool;
        // persistent pool of worker threads for prefetching
        threadpool::ThreadPool _prefetcherPool;

    public:
        // Allow index prefetching to be turned on/off
        enum IndexPrefetchConfig {
            PREFETCH_NONE=0, PREFETCH_ID_ONLY=1, PREFETCH_ALL=2
        };

        void setIndexPrefetchConfig(const IndexPrefetchConfig cfg) {
            _indexPrefetchConfig = cfg;
        }
        IndexPrefetchConfig getIndexPrefetchConfig() {
            return _indexPrefetchConfig;
        }

        static const int replWriterThreadCount;
        static const int replPrefetcherThreadCount;
        threadpool::ThreadPool& getPrefetchPool() { return _prefetcherPool; }
        threadpool::ThreadPool& getWriterPool() { return _writerPool; }

        static const int maxSyncSourceLagSecs;

        const ReplSetConfig::MemberCfg& myConfig() const { return _config; }
        bool tryToGoLiveAsASecondary(OpTime&); // readlocks
        void syncRollback(OplogReader& r);
        void syncThread();
        const OpTime lastOtherOpTime() const;

        /**
         * When a member reaches its minValid optime it is in a consistent state.  Thus, minValid is
         * set as the last step in initial sync.  At the beginning of initial sync, _initialSyncFlag
         * is appended onto minValid to indicate that initial sync was started but has not yet
         * completed.
         * minValid is also used during "normal" sync: the last op in each batch is used to set
         * minValid, to indicate that we are in a consistent state when the batch has been fully
         * applied.
         */
        static void setMinValid(BSONObj obj);
        static OpTime getMinValid();
        static void clearInitialSyncFlag();
        static bool getInitialSyncFlag();
        static void setInitialSyncFlag();

        int oplogVersion;
    private:
        IndexPrefetchConfig _indexPrefetchConfig;

        static const char* _initialSyncFlagString;
        static const BSONObj _initialSyncFlag;
    };

    class ReplSet : public ReplSetImpl {
    public:
        static ReplSet* make(ReplSetCmdline& replSetCmdline);
        virtual ~ReplSet() {}

        // for the replSetStepDown command
        bool stepDown(int secs) { return _stepDown(secs); }

        // for the replSetFreeze command
        bool freeze(int secs) { return _freeze(secs); }

        string selfFullName() {
            verify( _self );
            return _self->fullName();
        }

        virtual bool buildIndexes() const { return _buildIndexes; }

        /* call after constructing to start - returns fairly quickly after launching its threads */
        void go() { _go(); }
        void shutdown();

        void fatal() { _fatal(); }
        virtual bool isPrimary() { return box.getState().primary(); }
        virtual bool isSecondary() {  return box.getState().secondary(); }
        MemberState state() const { return ReplSetImpl::state(); }
        string name() const { return ReplSetImpl::name(); }
        virtual const ReplSetConfig& config() { return ReplSetImpl::config(); }
        void getOplogDiagsAsHtml(unsigned server_id, stringstream& ss) const { _getOplogDiagsAsHtml(server_id,ss); }
        void summarizeAsHtml(stringstream& ss) const { _summarizeAsHtml(ss); }
        void summarizeStatus(BSONObjBuilder& b) const  { _summarizeStatus(b); }
        void fillIsMaster(BSONObjBuilder& b) { _fillIsMaster(b); }
        threadpool::ThreadPool& getPrefetchPool() { return ReplSetImpl::getPrefetchPool(); }
        threadpool::ThreadPool& getWriterPool() { return ReplSetImpl::getWriterPool(); }

        /**
         * We have a new config (reconfig) - apply it.
         * @param comment write a no-op comment to the oplog about it.  only
         * makes sense if one is primary and initiating the reconf.
         *
         * The slaves are updated when they get a heartbeat indicating the new
         * config.  The comment is a no-op.
         */
        void haveNewConfig(ReplSetConfig& c, bool comment);

        /**
         * Pointer assignment isn't necessarily atomic, so this needs to assure
         * locking, even though we don't delete old configs.
         */
        const ReplSetConfig& getConfig() { return config(); }

        bool lockedByMe() { return RSBase::lockedByMe(); }

        // heartbeat msg to send to others; descriptive diagnostic info
        string hbmsg() const {
            if( time(0)-_hbmsgTime > 120 ) return "";
            return _hbmsg;
        }

    protected:
        ReplSet();
    };

    /**
     * Base class for repl set commands.  Checks basic things such if we're in
     * rs mode before the command does its real work.
     */
    class ReplSetCommand : public Command {
    protected:
        ReplSetCommand(const char * s, bool show=false) : Command(s, show) { }
        virtual bool slaveOk() const { return true; }
        virtual bool adminOnly() const { return true; }
        virtual bool logTheOp() { return false; }
        virtual LockType locktype() const { return NONE; }
        virtual void help( stringstream &help ) const { help << "internal"; }

        bool check(string& errmsg, BSONObjBuilder& result) {
            if( !replSet ) {
                errmsg = "not running with --replSet";
                if( cmdLine.configsvr ) {
                    result.append("info", "configsvr"); // for shell prompt
                }
                return false;
            }

            if( theReplSet == 0 ) {
                result.append("startupStatus", ReplSet::startupStatus);
                string s;
                errmsg = ReplSet::startupStatusMsg.empty() ? "replset unknown error 2" : ReplSet::startupStatusMsg.get();
                if( ReplSet::startupStatus == 3 )
                    result.append("info", "run rs.initiate(...) if not yet done for the set");
                return false;
            }

            return true;
        }
    };

    /**
     * does local authentication
     * directly authorizes against AuthenticationInfo
     */
    void replLocalAuth();

    /** inlines ----------------- */

    inline Member::Member(HostAndPort h, unsigned ord, const ReplSetConfig::MemberCfg *c, bool self) :
        _config(*c), _h(h), _hbinfo(ord) {
        verify(c);
        if( self )
            _hbinfo.health = 1.0;
    }

    inline bool ignoreUniqueIndex(IndexDetails& idx) {
        if (!idx.unique()) {
            return false;
        }
        if (!theReplSet) {
            return false;
        }
        // see SERVER-6671
        MemberState ms = theReplSet->state();
        if (! ((ms == MemberState::RS_STARTUP2) ||
               (ms == MemberState::RS_RECOVERING) ||
               (ms == MemberState::RS_ROLLBACK))) {
            return false;
        }
        // 2 is the oldest oplog version where operations
        // are fully idempotent.
        if (theReplSet->oplogVersion < 2) {
            return false;
        }
        // Never ignore _id index
        if (idx.isIdIndex()) {
            return false;
        }

        return true;
    }

}