text:
package com.loginradius.sdk.models.responsemodels.userprofile.objects;
import com.google.gson.annotations.SerializedName;

	// <summary>
	//	Response containing Definition for Complete Professional Position data
	// </summary>
	public class ProfessionalPosition {

		@SerializedName("Company")
        private PositionCompany company;

		@SerializedName("EndDate")
        private String endDate;

		@SerializedName("IsCurrent")
        private String isCurrent;

		@SerializedName("Location")
        private String location;

		@SerializedName("Position")
        private String position;

		@SerializedName("StartDate")
        private String startDate;

		@SerializedName("Summary")
        private String summary;

		// <summary>
		//	Company of the professional position
		// </summary>
		public PositionCompany getCompany() {
			return company;
		}
		// <summary>
		//	Company of the professional position
		// </summary>
		public void setCompany(PositionCompany company) {
			this.company = company;
		}
		// <summary>
		//	End date of the professional position
		// </summary>
		public String getEndDate() {
			return endDate;
		}
		// <summary>
		//	End date of the professional position
		// </summary>
		public void setEndDate(String endDate) {
			this.endDate = endDate;
		}
		// <summary>
		//	Is current or not
		// </summary>
		public String getIsCurrent() {
			return isCurrent;
		}
		// <summary>
		//	Is current or not
		// </summary>
		public void setIsCurrent(String isCurrent) {
			this.isCurrent = isCurrent;
		}
		// <summary>
		//	Location of the professional position
		// </summary>
		public String getLocation() {
			return location;
		}
		// <summary>
		//	Location of the professional position
		// </summary>
		public void setLocation(String location) {
			this.location = location;
		}
		// <summary>
		//	Position
		// </summary>
		public String getPosition() {
			return position;
		}
		// <summary>
		//	Position
		// </summary>
		public void setPosition(String position) {
			this.position = position;
		}
		// <summary>
		//	Start date of the professional position
		// </summary>
		public String getStartDate() {
			return startDate;
		}
		// <summary>
		//	Start date of the professional position
		// </summary>
		public void setStartDate(String startDate) {
			this.startDate = startDate;
		}
		// <summary>
		//	Summary of the professional position
		// </summary>
		public String getSummary() {
			return summary;
		}
		// <summary>
		//	Summary of the professional position
		// </summary>
		public void setSummary(String summary) {
			this.summary = summary;
		}
    }


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

	<title>CodeMirror UI | Test Page</title>

	<link rel="stylesheet" href="lib/CodeMirror-2.3/lib/codemirror.css">

  <link rel="stylesheet" href="lib/CodeMirror-2.3/mode/javascript/javascript.css">

	<link rel="stylesheet" href="css/codemirror-ui.css" type="text/css" media="screen" />

CodeMirror UI

		CodeMirrorUI is a simple interface written by Jeremy Green to act as a
		wrapper around the CodeMirror text editor widget by Marijn Haverbeke.
		CodeMirror is a syntax highlighter and formatter that makes it much easier to edit source code in a browser.
		ComeMirrorUI is a wrapper that adds interface functionality for many functions that are already built into CodeMirror itself.
		Functionality includes undo, redo, jump to line, reindent selection, and reindent entire document.
		Two options for find/replace are also available.  It is based on the MirrorFrame example that Marijn included with CodeMirror.

		This editor is enabled with the pop up find/replace widget.

	<textarea id="code1" cols="120" rows="20">
	// Here you see some JavaScript code. Mess around with it to get
	// acquainted with CodeMirror's features.

	// Press enter inside the object and your new line will be suitably
	// indented.
	var keyBindings = {
	  enter: "newline-and-indent",
	  tab: "reindent-selection",
	  ctrl_z: "undo",
	  ctrl_y: "redo",
	  ctrl_backspace: "undo-for-safari (which blocks ctrl-z)",
	  ctrl_bracket: "highlight-brackets",
	  ctrl_shift_bracket: "jump-to-matching-bracket"
	};

	// Press tab on the next line and the wrong indentation will be fixed.
	      var regex = /foo|bar/i;

	function example(x) {
	  // Local variables get a different colour than global ones.
	  var y = 44.4;
	  return x + y - z;
	}
	</textarea>

Easily Configurable

		The editor above was created with code like this:

//first set up some variables
var textarea = document.getElementById('code1');
var uiOptions = { path : 'js/', searchMode : 'popup' }
var codeMirrorOptions = { mode: "javascript" }

//then create the editor
var editor = new CodeMirrorUI(textarea,uiOptions,codeMirrorOptions);

		Creating a new CodeMirrorUI is easy, you just call:

new CodeMirrorUI(textarea,uiOptions,codeMirrorOptions);

Params for new CodeMirrorUI()

			textarea - Either a DOM element of the ID of a DOM element that should be replaced with the editor UI.

			uiOptions - Options for the CodeMirrorUI object.

					path - String - The path to the codemirror-ui js directory (relative to the current document).

					searchMode - String - Options are 'inline' or 'popup'

					buttons - Array - An array of button names that should be included in the button bar.

			codeMirrorOptions - Standard optiosn that you would pass to any CodeMirror constructor.  See the CodeMirror manual for more details;

Installing

		To install CodeMirrorUI you can just copy the codemirror-ui directory into your web app.
		It includes a version of CodeMirror, or you can use your own version if you'd prefer.

		Then include a link to the stylesheet and javascript files in your document. Something like this:

// First the CodeMirror stuff
<script src="lib/CodeMirror-2.3/lib/codemirror.js" type="text/javascript"></script>
<script src="lib/CodeMirror-2.3/lib/util/searchcursor.js" type="text/javascript"></script>
<link rel="stylesheet" href="lib/CodeMirror-2.3/lib/codemirror.css">
<script src="lib/CodeMirror-2.3/mode/javascript/javascript.js"></script>
<link rel="stylesheet" href="lib/CodeMirror-2.3/mode/javascript/javascript.css">

//Then the CodeMirrorUI stuff
<script src="js/codemirror-ui.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/codemirror-ui.css" type="text/css" media="screen" />

    Note: The find/replace functionality relies on the searchcursor add on.

		From there you can create an editor as shown above.  It is especially easy to replace any calls to
		"CodeMirror.fromTextArea(...)" with a "new CodeMirrorUI(...)".

Another example

		This editor is enabled with a save button and the 'inline' search widget.
    You can pass a function as the 'saveCallback' option which will be called when the save button is clicked.

		The button for the popup search widget has been removed,
		along with the button for 'reindent selection'.

	<textarea id="code2" cols="120" rows="30">
	// Here you see some JavaScript code. Mess around with it to get
	// acquainted with CodeMirror's features.

	// Press enter inside the object and your new line will be suitably
	// indented.
	var keyBindings = {
	  enter: "newline-and-indent",
	  tab: "reindent-selection",
	  ctrl_z: "undo",
	  ctrl_y: "redo",
	  ctrl_backspace: "undo-for-safari (which blocks ctrl-z)",
	  ctrl_bracket: "highlight-brackets",
	  ctrl_shift_bracket: "jump-to-matching-bracket"
	};

	// Press tab on the next line and the wrong indentation will be fixed.
	      var regex = /foo|bar/i;

	function example(x) {
	  // Local variables get a different colour than global ones.
	  var y = 44.4;
	  return x + y - z;
	}
	</textarea>

		The uiOptions param for the editor above looks like this:

var uiOptions = {
  path : 'js/',
  searchMode = 'inline',
  buttons : ['save','undo','redo','jump','reindent','about'],
  saveCallback : function(){ alert("Some saving goes here.  Probably AJAX or something fancy."); }
}

		View the source of this page to see the actual code used to get these editors in action.

Find the code @ Github

	https://github.com/jagthedrummer/codemirror-ui

Acknowledgements

Marijn Haverbeke - CodeMirror

		Thanks to Marijn Haverbeke for creating and releasing CodeMirror in the first place.
		Whithout his excellent contribution to the community this project would have no reason to exist.

Mark James - Silk Icons

	I used the Silk icon set from Mark James of famfamfam.com fame.

Versions

    All version up to and including 0.0.7 are based on CodeMirror 1.

    Versions 0.0.8 and newer are based on CodeMirror 2.

License

    CodeMirror UI is provided under the MIT License.  See the LICENSE file for full details.

Known Usage

    The following sites/apps are using CodeMirrorUI.
    Please let me know if you'd like to be added to this list.

aPeel

		CodeMirrorUI is a production of OctoLabs

redpajama_set_name: RedPajamaGithub


text:
public class Program {
  MainClass main_class;
  ClassDeclList class_decls;

  Program(MainClass mc, ClassDeclList cdl)
  {
    main_class = mc;
    class_decls = cdl;
  }
}

public abstract class Stmt {
  Stmt() {

  }
}

public class If extends Stmt {
  Exp cond;
  Stmt true_stmt;
  Stmt false_stmt;

  public If(Exp c, Stmt t, Stmt f) {
    cond = c;
    true_stmt = t;
    false_stmt = f;
  }
}

public class Parser {
  Lexer lexer;
  public Parser(Lexer lexer) {
    this.lexer = lexer;
  }
}

//find an example of a Program
public Program program() {
  advance();  // get first token
  MainClass main_class = mainClass();
  ClassDeclList<ClassDecl> other_classes = new ClassDeclList<ClassDecl>();
  while (is(TokenType.KEY, "class")) {
    other_classes.add(ClassDecl());
  }
  if (token != null) {
    error("Expected EOF after Classes");
  } else {
    System.out.println("OK");
  }

  return new Program(main_class, other_classes);
}

public ClassDecl classDecl() {
  Identifier class_name - classDeclSpec();
  return classDeclDef(className);
}

public ClassDeclSpec classDeclSpec() {
  eat("class");
  Identifier class_name = new Identifier(value);
  eat(tokenType.ID);
  return className;
}

public ClassDeclDef(Identifier class_name) {
  MethodDeclList<MethodDecl methods = new MethodDeclList<MethodDecl>();
  VarDeclList<VarDecl> fields = new VarDeclList<VarDecl>();
  if (token == LBRACE) {
    eat(LBRACE);
    while () {
      fields.add(varDecl());
      return new ClassDecl(class_name, fields, methods);
    }
  } else {
    // do extends
  }
}

public Exp exp() {
  Exp left = And();
  Exp right = Elist(left);
  if (right == null) {
    return left;
  }
  return right;
}


text:
<?php
// vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
/**
 * Mediawiki: Parses for superscripted text.
 *
 * PHP versions 4 and 5
 *
 * @category   Text
 * @package    Text_Wiki
 * @author     Paul M. Jones <pmjones@php.net>
 * @author     Moritz Venn <ritzmo@php.net>
 * @license    http://www.gnu.org/copyleft/lesser.html  LGPL License 2.1
 * @version    CVS: $Id: Superscript.php 218426 2006-08-18 13:25:02Z ritzmo $
 * @link       http://pear.php.net/package/Text_Wiki
 */

/**
 * Parses for superscripted text.
 *
 * @category   Text
 * @package    Text_Wiki
 * @author     Paul M. Jones <pmjones@php.net>
 * @author     Moritz Venn <ritzmo@php.net>
 * @license    http://www.gnu.org/copyleft/lesser.html  LGPL License 2.1
 * @version    Release: @package_version@
 * @link       http://pear.php.net/package/Text_Wiki
 * @see        Text_Wiki_Parse::Text_Wiki_Parse()
 */
class Text_Wiki_Parse_Superscript extends Text_Wiki_Parse {

    /**
    * The regular expression used to parse the source text and find
    * matches conforming to this rule.  Used by the parse() method.
    *
    * @access public
    * @var string
    * @see parse()
    */
    var $regex =  "/<sup>(.*?)<\/sup>/s";

    /**
    * Generates a replacement for the matched text.  Token options are:
    * 'type' => ['start'|'end'] The starting or ending point of the
    * emphasized text.  The text itself is left in the source.
    *
    * @access public
    * @param array &$matches The array of matches from parse().
    * @return A pair of delimited tokens to be used as a placeholder in
    * the source text surrounding the text to be emphasized.
    */
    function process(&$matches)
    {
        $start = $this->wiki->addToken(
            $this->rule, array('type' => 'start')
        );

        $end = $this->wiki->addToken(
            $this->rule, array('type' => 'end')
        );

        return $start . $matches[1] . $end;
    }
}
?>


text:
from pygls.lsp.types.basic_structures import *
from pygls.lsp.types.client import *
from pygls.lsp.types.diagnostics import *
from pygls.lsp.types.file_operations import *
from pygls.lsp.types.general_messages import *
from pygls.lsp.types.language_features import *
from pygls.lsp.types.text_synchronization import *
from pygls.lsp.types.window import *
from pygls.lsp.types.workspace import *


text:
#ifndef SRC_DRIVERS_TTT_TTT_STREAM_H_
#define SRC_DRIVERS_TTT_TTT_STREAM_H_

#include <src/transports/stream.h>
#include <src/transports/connector.h>

NEW_STREAM_DECLARE(ttt);

camio_error_t ttt_stream_construct(camio_stream_t* this, camio_connector_t* connector /**, ... , **/);

#endif /* SRC_DRIVERS_TTT_TTT_STREAM_H_ */


text:
<?php
namespace Concrete\Package\WebliEvents\Block\WebliEventAccordion;
use BlockType;
use CollectionAttributeKey;
use Concrete\Core\Block\BlockController;
use Database;
use Loader;
use Page;
use Core;
use PageList;
use Concrete\Core\Attribute\Key\CollectionKey;
use \Concrete\Core\Tree\Node\Type\Topic;

class Controller extends BlockController
{

    protected $btTable = 'btWebliEventAccordion';
    protected $btInterfaceWidth = "400";
    protected $btInterfaceHeight = "420";
    protected $btExportPageColumns = array('cParentID');
    protected $btExportPageTypeColumns = array('ptID');
    protected $btCacheBlockRecord = true;
    protected $list;
	protected $btDefaultSet = 'events';

    /**
     * Used for localization. If we want to localize the name/description we have to include this
     */
    public function getBlockTypeDescription()
    {
        return t("Create Event Accordion.");
    }

    public function getBlockTypeName()
    {
        return t("Event Accordion");
    }

    public function getJavaScriptStrings()
    {
        return array(
            'feed-name' => t('Please give your RSS Feed a name.')
        );
    }

    public function on_start()
    {

        $this->list = new PageList();
        $this->list->disableAutomaticSorting();
        //$pl->setNameSpace('b' . $this->bID);

        $cArray = array();

        $c = Page::getCurrentPage();
        if (is_object($c)) {
            $this->cID = $c->getCollectionID();
        }

        if ($this->displayAliases) {
            $this->list->includeAliases();
        }
        $this->list->filter('cvName', '', '!=');

        if ($this->ptID) {
            $this->list->filterByPageTypeID($this->ptID);
        }

        if ($this->filterByRelated) {
            $ak = CollectionKey::getByHandle($this->relatedTopicAttributeKeyHandle);
            if (is_object($ak)) {
                $topics = $c->getAttribute($ak->getAttributeKeyHandle());
                if (count($topics) > 0 && is_array($topics)) {
                    $topic = $topics[array_rand($topics)];
                    $this->list->filter('p.cID', $c->getCollectionID(), '<>');
                    $this->list->filterByTopic($topic);
                }
            }
        }

        $db = Database::connection();
        $collectionAttributeKey = new CollectionAttributeKey();
        $columns = $db->MetaColumnNames($collectionAttributeKey->getIndexedSearchTable());
        if (in_array('ak_exclude_page_list', $columns)) {
            $this->list->filter(false, '(ak_exclude_page_list = 0 or ak_exclude_page_list is null)');
        }

        if (intval($this->cParentID) != 0) {
            $cParentID = ($this->cThis) ? $this->cID : $this->cParentID;
            $this->list->filterByPath(Page::getByID($cParentID)->getCollectionPath());
        }

		if($this->parent){
				$parentPage=Page::getByID($c->getCollectionParentID());
				$this->list->filterByParentID($parentPage->getCollectionID());
		}

        return $this->list;

    }

    public function view()
    {

        $list = $this->list;
        $nh = Core::Make('helper/navigation');
        $this->set('nh', $nh);

        if ($this->pfID) {
            $this->requireAsset('css', 'font-awesome');
            $feed = Feed::getByID($this->pfID);
            if (is_object($feed)) {
                $this->set('rssUrl', $feed->getFeedURL());
                $link = new \HtmlObject\Element('link');
                $link->href($feed->getFeedURL());
                $link->rel('alternate');
                $link->type('application/rss+xml');
                $link->title($feed->getTitle());
                $this->addHeaderItem($link);
            }
        }

        //Pagination...
        $showPagination = false;
        if ($this->num > 0) {
            $list->setItemsPerPage($this->num);
            $pagination = $list->getPagination();
            $pages = $pagination->getCurrentPageResults();
            if ($pagination->getTotalPages() > 1 && $this->paginate) {
                $showPagination = true;
                $pagination = $pagination->renderDefaultView();
                $this->set('pagination', $pagination);
            }
        } else {
            $pages = $list->getResults();
        }

        if ($showPagination) {
            $this->requireAsset('css', 'core/frontend/pagination');
        }

		foreach( $pages as $p){

			$eventDates = $p->getCollectionAttributeValue('event_dates');
			$lastRecurring = strtotime($eventDates['dates']['lastRecurring']);

			if($eventDates['dates']){
				foreach($eventDates['dates'] as $dates){
					unset($startDate);
					$startDate = strtotime($dates['start']);
					unset($endDate);
					$endDate = strtotime($dates['end']);

					$eventPages[] = array('cID' => $p->getCollectionID(), 'startDate' => $startDate, 'endDate' => $endDate);
				}
			}

		}

        $this->set('pages', $eventPages);
        $this->set('list', $list);
        $this->set('showPagination', $showPagination);
		$this->set('display', $this->get_display_options());

		// Thumbnail Attribute
		if($this->image_attribute == 0) {
		    $this->set('thumbnail_attribute', 'thumbnail');
		} else {
			$this->set('thumbnail_attribute', CollectionAttributeKey::getByID($this->image_attribute)->getAttributeKeyHandle());
		}
    }

		function get_display_options()
	{
		$page = Page::getCurrentPage();
		$parentPage = Page::getByID($page->getCollectionParentID());

		$db = Database::connection();
		if($page->getCollectionAttributeValue('event_category')){
			$display = $db->GetRow("select * from btWebliEvents where cID = ?", $page->getCollectionID());
		} elseif($parentPage->getCollectionAttributeValue('event_category')){
			$display = $db->GetRow("select * from btWebliEvents where cID = ?", $parentPage->getCollectionID());
		}

		if(!$display) $display = $db->GetRow("select * from btWebliEvents where cID = ?", 0);

		return $display;
	}

	function get_event_categories()
	{
		$pl = new PageList();
		$pl->sortByName();
		$pl->filterByAttribute('event_category', true);

		return $pl->get();
	}

    public function add()
    {

        $c = Page::getCurrentPage();
        $uh = Loader::helper('concrete/urls');
        $this->set('c', $c);
        $this->set('uh', $uh);
        $this->set('includeDescription', true);
        $this->set('includeName', true);
        $this->set('bt', BlockType::getByHandle('page_list'));
        $this->set('featuredAttribute', CollectionAttributeKey::getByHandle('is_featured'));
        $this->set('thumbnailAttribute', CollectionAttributeKey::getByHandle('thumbnail'));
        $this->loadKeys();
		$this->set(thumb_height, 75);
		$this->set(thumb_width, 120);
		$this->set(date_format, 'l F j, Y g:ia');
		$this->set(includeDate, true);
		$this->set(event_location, true);
		$this->set(orderBy, 'chrono_asc');
    }

    public function edit()
    {
        $b = $this->getBlockObject();
        $bCID = $b->getBlockCollectionID();
        $bID = $b->getBlockID();
        $this->set('bID', $bID);
        $c = Page::getCurrentPage();
        if ($c->getCollectionID() != $this->cParentID && (!$this->cThis) && ($this->cParentID != 0)) {
            $isOtherPage = true;
            $this->set('isOtherPage', true);
        }
        if ($this->pfID) {
            $feed = Feed::getByID($this->pfID);
            if (is_object($feed)) {
                $this->set('rssFeed', $feed);
            }
        }
        $uh = Loader::helper('concrete/urls');
        $this->set('uh', $uh);
        $this->set('bt', BlockType::getByHandle('page_list'));
        $this->set('featuredAttribute', CollectionAttributeKey::getByHandle('is_featured'));
        $this->set('thumbnailAttribute', CollectionAttributeKey::getByHandle('thumbnail'));
        $this->loadKeys();
    }

    protected function loadKeys()
    {
        $attributeKeys = array();
        $keys = CollectionKey::getList(array('atHandle' => 'topics'));
        foreach ($keys as $ak) {
            if ($ak->getAttributeTypeHandle() == 'topics') {
                $attributeKeys[] = $ak;
            }
        }
        $this->set('attributeKeys', $attributeKeys);
    }

    public function action_filter_by_topic($treeNodeID = false, $topic = false)
    {
        if ($treeNodeID) {
            $this->list->filterByTopic(intval($treeNodeID));
            $topicObj = Topic::getByID(intval($treeNodeID));
            if (is_object($topicObj)) {
                $seo = Core::make('helper/seo');
                $seo->addTitleSegment($topicObj->getTreeNodeDisplayName());
            }
        }
        $this->view();
    }

    public function action_filter_by_tag($tag = false)
    {
        $seo = Core::make('helper/seo');
        $seo->addTitleSegment($tag);
        $this->list->filterByTags(h($tag));
        $this->view();
    }

    public function action_filter_by_date($year = false, $month = false, $timezone = 'user')
    {
        if (is_numeric($year)) {
            $year = (($year < 0) ? '-' : '') . str_pad(abs($year), 4, '0', STR_PAD_LEFT);
            if ($month) {
                $month = str_pad($month, 2, '0', STR_PAD_LEFT);
                $lastDayInMonth = date('t', strtotime("$year-$month-01"));
                $start = "$year-$month-01 00:00:00";
                $end = "$year-$month-$lastDayInMonth 23:59:59";
            } else {
                $start = "$year-01-01 00:00:00";
                $end = "$year-12-31 23:59:59";
            }
            if ($timezone !== 'system') {
                $dh = Core::make('helper/date');
                /* @var $dh \Concrete\Core\Localization\Service\Date */
                $start = $dh->toDB($start, $timezone);
                $end = $dh->toDB($end, $timezone);
            }
            $this->list->filterByPublicDate($start, '>=');
            $this->list->filterByPublicDate($end, '<=');

            $seo = Core::make('helper/seo');
            $srv = Core::make('helper/date');
            $seo->addTitleSegment($srv->date('F Y',$start));
        }
        $this->view();
    }

    public function validate($args)
    {
        $e = Core::make('helper/validation/error');
        $vs = Core::make('helper/validation/strings');
        $pf = false;
        if ($this->pfID) {
            $pf = Feed::getByID($this->pfID);
        }
        if ($args['rss'] && !is_object($pf)) {
            if (!$vs->handle($args['rssHandle'])) {
                $e->add(t('Your RSS feed must have a valid URL, containing only letters, numbers or underscores'));
            }
            if (!$vs->notempty($args['rssTitle'])) {
                $e->add(t('Your RSS feed must have a valid title.'));
            }
            if (!$vs->notempty($args['rssDescription'])) {
                $e->add(t('Your RSS feed must have a valid description.'));
            }
        }

        return $e;
    }

    public function getPassThruActionAndParameters($parameters)
    {
        if ($parameters[0] == 'topic') {
            $method = 'action_filter_by_topic';
            $parameters = array_slice($parameters, 1);
        } elseif ($parameters[0] == 'tag') {
            $method = 'action_filter_by_tag';
            $parameters = array_slice($parameters, 1);
        } elseif (Loader::helper("validation/numbers")->integer($parameters[0])) {
            // then we're going to treat this as a year.
            $method = 'action_filter_by_date';
            $parameters[0] = intval($parameters[0]);
            if (isset($parameters[1])) {
                $parameters[1] = intval($parameters[1]);
            }
        }

        return array($method, $parameters);
    }

    public function isValidControllerTask($method, $parameters = array())
    {
        if (!$this->enableExternalFiltering) {
            return false;
        }

        return parent::isValidControllerTask($method, $parameters);
    }

    public function save($args)
    {
        // If we've gotten to the process() function for this class, we assume that we're in
        // the clear, as far as permissions are concerned (since we check permissions at several
        // points within the dispatcher)
        $db = Loader::db();

        $bID = $this->bID;
        $c = $this->getCollectionObject();
        if (is_object($c)) {
            $this->cID = $c->getCollectionID();
        }

        $args['cThis'] = ($args['cParentID'] == $this->cID) ? '1' : '0';
 		if($args['cParentID'] == 'PARENT'){
			$args['parent'] = 1;
			$args['cParentIDValue'] = 0;
		} else {
			$args['parent'] = 0;
		}
		$args['cParentID'] = ($args['cParentID'] == 'OTHER' || $args['cParentID'] == 'PARENT') ? $args['cParentIDValue'] : $args['cParentID'];
        if (!$args['cParentID']) {
            $args['cParentID'] = 0;
        }
        $args['enableExternalFiltering'] = ($args['enableExternalFiltering']) ? '1' : '0';
        $args['filterByRelated'] = ($args['filterByRelated']) ? '1' : '0';
        $args['ptID'] = intval($args['ptID']);

		if($data['event_categories']){
			$args['event_categories'] = serialize($data['event_categories']);
		}else {
			$args['event_categories'] = '';
		}

        parent::save($args);

    }

    public function isBlockEmpty()
    {
        $pages = $this->get('pages');
        if ($this->title) {
            return false;
        }
        if (count($pages) == 0) {
            if ($this->noResultsMessage) {
                return false;
            } else {
                return true;
            }
        } else {
            if ($this->includeName || $this->includeDate || $this->displayThumbnail
                || $this->includeDescription || $this->useButtonForLink
            ) {
                return false;
            } else {
                return true;
            }
        }
    }

}


text:
"""A library of basic cythonized CombineFn subclasses.

For internal use only; no backwards-compatibility guarantees.
"""

# pytype: skip-file

import operator

from apache_beam.transforms import core

try:
  from apache_beam.transforms.cy_dataflow_distribution_counter import DataflowDistributionCounter
except ImportError:
  from apache_beam.transforms.py_dataflow_distribution_counter import DataflowDistributionCounter

class AccumulatorCombineFn(core.CombineFn):
  # singleton?
  def create_accumulator(self):
    return self._accumulator_type()

  @staticmethod
  def add_input(accumulator, element):
    accumulator.add_input(element)
    return accumulator

  def merge_accumulators(self, accumulators):
    accumulator = self._accumulator_type()
    accumulator.merge(accumulators)
    return accumulator

  @staticmethod
  def extract_output(accumulator):
    return accumulator.extract_output()

  def __eq__(self, other):
    return (
        isinstance(other, AccumulatorCombineFn) and
        self._accumulator_type is other._accumulator_type)

  def __hash__(self):
    return hash(self._accumulator_type)

_63 = 63  # Avoid large literals in C source code.
globals()['INT64_MAX'] = 2**_63 - 1
globals()['INT64_MIN'] = -2**_63

class CountAccumulator(object):
  def __init__(self):
    self.value = 0

  def add_input(self, unused_element):
    self.value += 1

  def merge(self, accumulators):
    for accumulator in accumulators:
      self.value += accumulator.value

  def extract_output(self):
    return self.value

class SumInt64Accumulator(object):
  def __init__(self):
    self.value = 0

  def add_input(self, element):
    global INT64_MAX, INT64_MIN  # pylint: disable=global-variable-not-assigned
    element = int(element)
    if not INT64_MIN <= element <= INT64_MAX:
      raise OverflowError(element)
    self.value += element

  def merge(self, accumulators):
    for accumulator in accumulators:
      self.value += accumulator.value

  def extract_output(self):
    if not INT64_MIN <= self.value <= INT64_MAX:
      self.value %= 2**64
      if self.value >= INT64_MAX:
        self.value -= 2**64
    return self.value

class MinInt64Accumulator(object):
  def __init__(self):
    self.value = INT64_MAX

  def add_input(self, element):
    element = int(element)
    if not INT64_MIN <= element <= INT64_MAX:
      raise OverflowError(element)
    if element < self.value:
      self.value = element

  def merge(self, accumulators):
    for accumulator in accumulators:
      if accumulator.value < self.value:
        self.value = accumulator.value

  def extract_output(self):
    return self.value

class MaxInt64Accumulator(object):
  def __init__(self):
    self.value = INT64_MIN

  def add_input(self, element):
    element = int(element)
    if not INT64_MIN <= element <= INT64_MAX:
      raise OverflowError(element)
    if element > self.value:
      self.value = element

  def merge(self, accumulators):
    for accumulator in accumulators:
      if accumulator.value > self.value:
        self.value = accumulator.value

  def extract_output(self):
    return self.value

class MeanInt64Accumulator(object):
  def __init__(self):
    self.sum = 0
    self.count = 0

  def add_input(self, element):
    element = int(element)
    if not INT64_MIN <= element <= INT64_MAX:
      raise OverflowError(element)
    self.sum += element
    self.count += 1

  def merge(self, accumulators):
    for accumulator in accumulators:
      self.sum += accumulator.sum
      self.count += accumulator.count

  def extract_output(self):
    if not INT64_MIN <= self.sum <= INT64_MAX:
      self.sum %= 2**64
      if self.sum >= INT64_MAX:
        self.sum -= 2**64
    return self.sum // self.count if self.count else _NAN

class DistributionInt64Accumulator(object):
  def __init__(self):
    self.sum = 0
    self.count = 0
    self.min = INT64_MAX
    self.max = INT64_MIN

  def add_input(self, element):
    element = int(element)
    if not INT64_MIN <= element <= INT64_MAX:
      raise OverflowError(element)
    self.sum += element
    self.count += 1
    self.min = min(self.min, element)
    self.max = max(self.max, element)

  def merge(self, accumulators):
    for accumulator in accumulators:
      self.sum += accumulator.sum
      self.count += accumulator.count
      self.min = min(self.min, accumulator.min)
      self.max = max(self.max, accumulator.max)

  def extract_output(self):
    if not INT64_MIN <= self.sum <= INT64_MAX:
      self.sum %= 2**64
      if self.sum >= INT64_MAX:
        self.sum -= 2**64
    mean = self.sum // self.count if self.count else _NAN
    return mean, self.sum, self.count, self.min, self.max

class CountCombineFn(AccumulatorCombineFn):
  _accumulator_type = CountAccumulator

class SumInt64Fn(AccumulatorCombineFn):
  _accumulator_type = SumInt64Accumulator

class MinInt64Fn(AccumulatorCombineFn):
  _accumulator_type = MinInt64Accumulator

class MaxInt64Fn(AccumulatorCombineFn):
  _accumulator_type = MaxInt64Accumulator

class MeanInt64Fn(AccumulatorCombineFn):
  _accumulator_type = MeanInt64Accumulator

class DistributionInt64Fn(AccumulatorCombineFn):
  _accumulator_type = DistributionInt64Accumulator

_POS_INF = float('inf')
_NEG_INF = float('-inf')
_NAN = float('nan')

class SumDoubleAccumulator(object):
  def __init__(self):
    self.value = 0

  def add_input(self, element):
    element = float(element)
    self.value += element

  def merge(self, accumulators):
    for accumulator in accumulators:
      self.value += accumulator.value

  def extract_output(self):
    return self.value

class MinDoubleAccumulator(object):
  def __init__(self):
    self.value = _POS_INF

  def add_input(self, element):
    element = float(element)
    if element < self.value:
      self.value = element

  def merge(self, accumulators):
    for accumulator in accumulators:
      if accumulator.value < self.value:
        self.value = accumulator.value

  def extract_output(self):
    return self.value

class MaxDoubleAccumulator(object):
  def __init__(self):
    self.value = _NEG_INF

  def add_input(self, element):
    element = float(element)
    if element > self.value:
      self.value = element

  def merge(self, accumulators):
    for accumulator in accumulators:
      if accumulator.value > self.value:
        self.value = accumulator.value

  def extract_output(self):
    return self.value

class MeanDoubleAccumulator(object):
  def __init__(self):
    self.sum = 0
    self.count = 0

  def add_input(self, element):
    element = float(element)
    self.sum += element
    self.count += 1

  def merge(self, accumulators):
    for accumulator in accumulators:
      self.sum += accumulator.sum
      self.count += accumulator.count

  def extract_output(self):
    return self.sum // self.count if self.count else _NAN

class SumFloatFn(AccumulatorCombineFn):
  _accumulator_type = SumDoubleAccumulator

class MinFloatFn(AccumulatorCombineFn):
  _accumulator_type = MinDoubleAccumulator

class MaxFloatFn(AccumulatorCombineFn):
  _accumulator_type = MaxDoubleAccumulator

class MeanFloatFn(AccumulatorCombineFn):
  _accumulator_type = MeanDoubleAccumulator

class AllAccumulator(object):
  def __init__(self):
    self.value = True

  def add_input(self, element):
    self.value &= not not element

  def merge(self, accumulators):
    for accumulator in accumulators:
      self.value &= accumulator.value

  def extract_output(self):
    return self.value

class AnyAccumulator(object):
  def __init__(self):
    self.value = False

  def add_input(self, element):
    self.value |= not not element

  def merge(self, accumulators):
    for accumulator in accumulators:
      self.value |= accumulator.value

  def extract_output(self):
    return self.value

class AnyCombineFn(AccumulatorCombineFn):
  _accumulator_type = AnyAccumulator

class AllCombineFn(AccumulatorCombineFn):
  _accumulator_type = AllAccumulator

class DataflowDistributionCounterFn(AccumulatorCombineFn):
  """A subclass of cy_combiners.AccumulatorCombineFn.

  Make DataflowDistributionCounter able to report to Dataflow service via
  CounterFactory.

  When cythonized DataflowDistributinoCounter available, make
  CounterFn combine with cythonized module, otherwise, combine with python
  version.
  """
  _accumulator_type = DataflowDistributionCounter

class ComparableValue(object):
  """A way to allow comparing elements in a rich fashion."""

  __slots__ = (
      'value', '_less_than_fn', '_comparable_value', 'requires_hydration')

  def __init__(self, value, less_than_fn, key_fn, _requires_hydration=False):
    self.value = value
    self.hydrate(less_than_fn, key_fn)
    self.requires_hydration = _requires_hydration

  def hydrate(self, less_than_fn, key_fn):
    self._less_than_fn = less_than_fn if less_than_fn else operator.lt
    self._comparable_value = key_fn(self.value) if key_fn else self.value
    self.requires_hydration = False

  def __lt__(self, other):
    assert not self.requires_hydration
    assert self._less_than_fn is other._less_than_fn
    return self._less_than_fn(self._comparable_value, other._comparable_value)

  def __repr__(self):
    return 'ComparableValue[%s]' % str(self.value)

  def __reduce__(self):
    # Since we can't pickle the Compare and Key Fn we pass None and we signify
    # that this object _requires_hydration.
    return ComparableValue, (self.value, None, None, True)


text: export * from './breakdownChart.component';


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"
    >
    <include layout="@layout/toolbar"

        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40.0dip"
        android:background="@color/jianshutabBackground"
        android:orientation="horizontal" >

        <RelativeLayout
            android:id="@+id/rl_column"
            android:layout_width="match_parent"
            android:layout_height="40.0dip"
            android:layout_weight="1.0" >

            <com.dawnlightning.zhai.widget.ColumnHorizontalScrollView
                android:id="@+id/mColumnHorizontalScrollView"
                android:layout_width="match_parent"
                android:layout_height="40.0dip"
                android:scrollbars="none">

                <LinearLayout
                    android:id="@+id/mRadioGroup_content"
                    android:layout_width="fill_parent"
                    android:layout_height="40.0dip"
                    android:layout_centerVertical="true"
                    android:gravity="center_vertical"
                    android:orientation="horizontal"
                    android:paddingLeft="10.0dip"
                    android:paddingRight="10.0dip" />
         </com.dawnlightning.zhai.widget.ColumnHorizontalScrollView>

            <ImageView
                android:id="@+id/shade_left"
                android:layout_width="10.0dip"
                android:layout_height="40.0dip"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:background="@mipmap/channel_leftblock"
                android:visibility="gone" />

            <ImageView
                android:id="@+id/shade_right"
                android:layout_width="10.0dip"
                android:layout_height="40.0dip"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:background="@mipmap/channel_rightblock"
                android:visibility="visible" />
        </RelativeLayout>

        <LinearLayout
            android:id="@+id/ll_more_columns"
            android:layout_width="wrap_content"
            android:layout_height="40.0dip" >

            <ImageView
                android:id="@+id/button_more_columns"
                android:layout_width="40.0dip"
                android:layout_height="40.0dip"
                android:layout_gravity="center_vertical"
                android:src="@drawable/channel_glide_day_bg" />
        </LinearLayout>
    </LinearLayout>

    <View
        android:id="@+id/category_line"
        android:layout_width="fill_parent"
        android:layout_height="0.5dip"
        android:background="#ffdddddd" />
    <com.dawnlightning.zhai.widget.lvp.LazyViewPager
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/lvp_main_viewpager"
        />
</LinearLayout>


text:
package heliospectra

import (
	"context"
	"net"
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"strings"
	"testing"
	"time"
)

func TestNewDevice(t *testing.T) {
	client := &http.Client{}
	d := NewDevice(net.IPv4(1, 2, 3, 4), client)
	if !reflect.DeepEqual(d.addr, net.IPv4(1, 2, 3, 4)) {
		t.Errorf("expected IP 1.2.3.4, got %s", d.addr)
	}
	if !reflect.DeepEqual(d.client, client) {
		t.Errorf("expected passed-in client to be used")
	}
	d = NewDevice(net.IPv4(1, 2, 3, 4), nil)
	if !reflect.DeepEqual(d.client, http.DefaultClient) {
		t.Errorf("expected DefaultClient to be used")
	}
}

const diagResponse = `
<diagnostic>
	<model>L4</model>
	<cpuFW>R2.2.25</cpuFW>
	<driverFW>N/A</driverFW>
	<ethernetMAC>64:1a:00:00:00:00</ethernetMAC>
	<wlanMAC></wlanMAC>
	<wavelengths>0:450nm:10.2W,1:660nm:5.2W,2:735nm:10.0W,3:5700K:6.0W,</wavelengths>
	<clock>2017:03:17:02:48:41</clock>
	<onSchedule>Not running</onSchedule>
	<masterOrSlave>Independent</masterOrSlave>
	<systemStatus>OK</systemStatus>
	<runtime>0d 02h 10m 08s</runtime>
	<latestChange>2017-03-17	02:06:25</latestChange>
	<changedBy>Web</changedBy>
	<changeIP>192.168.1.3</changeIP>
	<changeType>Light setting</changeType>
	<temps>0:26.8C,</temps>
	<intensities>0:0,1:0,2:0,3:0,</intensities>
	<useNTP>1</useNTP>
	<networkType>dynamic</networkType>
	<networkIP>192.168.1.8</networkIP>
	<networkSubnet>255.255.255.0</networkSubnet>
	<networkGateway>192.168.1.1</networkGateway>
	<networkDNS1>192.168.1.1</networkDNS1>
	<networkDNS2>0.0.0.0</networkDNS2>
	<allowedTemp>15.0 60.0:59.0 140.0</allowedTemp>
	<hs>51</hs>
	<title>L4</title>
	<wlanIP></wlanIP>
	<ethernetIP>192.168.1.8</ethernetIP>
	<ntpOffset>00:00:00</ntpOffset>
	<masters> </masters>
	<dialog> </dialog>
	<poweredLink>http://www.heliospectra.com</poweredLink>
	<poweredText>Powered by Heliospectra</poweredText>
	<ntpPoolType>default</ntpPoolType>
	<ntpPoolCustom>pool.ntp.org</ntpPoolCustom>
	<favicon>/favi.ico</favicon>
	<tempUnit>C</tempUnit>
	<lockData>off:Enter your message here:heliospectra</lockData>
	<shortcuts> </shortcuts>
	<ntpData>on, pool.ntp.org, 00:00:00</ntpData>
	<multicastIP>239.153.155.131</multicastIP>
	<tags>0|^|name|^||~|</tags>
</diagnostic>`

func TestDevice_Diagnostic(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	statusToReturn := 200
	bodyToReturn := diagResponse

	diagHandler := func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "GET" {
			t.Errorf("expected GET, got %s", r.Method)
		}
		if r.URL.Path != "/diag.xml" {
			t.Errorf("expected URL /diag.xml, got %s", r.URL.Path)
		}
		w.WriteHeader(statusToReturn)
		if _, err := w.Write([]byte(bodyToReturn)); err != nil {
			t.Fatal(err)
		}
	}
	server := httptest.NewServer(http.HandlerFunc(diagHandler))
	defer server.Close()

	testIP := net.IPv4(192, 168, 1, 8)

	client := &http.Client{
		Transport: &http.Transport{
			DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
				expectedAddr := testIP.String() + ":80"
				if addr != expectedAddr {
					t.Errorf("expected request to be sent to %s, was sent to %s", expectedAddr, addr)
				}
				// override the DialContext func to only dial to our test server:
				return (&net.Dialer{
					Timeout:   1 * time.Second,
					KeepAlive: 1 * time.Second,
					DualStack: false,
				}).DialContext(ctx, network, strings.TrimPrefix(server.URL, "http://"))
			},
		},
	}

	device := NewDevice(testIP, client)
	diag, err := device.Diagnostic(ctx)
	if err != nil {
		t.Fatal(err)
	}

	if expModel := "L4"; expModel != diag.Model {
		t.Errorf("expected model=%q, got %q", expModel, diag.Model)
	}
	expWavelengths := WavelengthList{
		{Number: 0, Wavelength: "450nm", Power: "10.2W"},
		{Number: 1, Wavelength: "660nm", Power: "5.2W"},
		{Number: 2, Wavelength: "735nm", Power: "10.0W"},
		{Number: 3, Wavelength: "5700K", Power: "6.0W"},
	}
	if !reflect.DeepEqual(expWavelengths, diag.Wavelengths) {
		t.Errorf("expected wavelengths=%#v\n\tgot %#v", expWavelengths, diag.Wavelengths)
		t.Logf("DIAG: %+v\n", diag)
	}

	statusToReturn = 400
	_, err = device.Diagnostic(ctx)
	if err == nil {
		t.Errorf("expected an error on status 400, got none")
	}

	statusToReturn = 200
	bodyToReturn = `{"some":"json"}`
	if _, err = device.Diagnostic(ctx); err == nil {
		t.Errorf("expected an error on a non-XML body, got none")
	}
}

func TestDevice_SetIntensities(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	statusToReturn := 200
	expectedQuery := url.Values{"int": []string{"1:2:3:4"}}

	diagHandler := func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "GET" {
			t.Errorf("expected GET, got %s", r.Method)
		}
		if err := r.ParseForm(); err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(expectedQuery, r.Form) {
			t.Errorf("expected query %#v, got %#v", expectedQuery, r.Form)
		}
		if r.URL.Path != "/intensity.cgi" {
			t.Errorf("expected URL /intensity.cgi, got %s", r.URL.Path)
		}
		w.WriteHeader(statusToReturn)
	}
	server := httptest.NewServer(http.HandlerFunc(diagHandler))
	defer server.Close()

	testIP := net.IPv4(192, 168, 1, 8)

	client := &http.Client{
		Transport: &http.Transport{
			DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
				expectedAddr := testIP.String() + ":80"
				if addr != expectedAddr {
					t.Errorf("expected request to be sent to %s, was sent to %s", expectedAddr, addr)
				}
				// override the DialContext func to only dial to our test server:
				return (&net.Dialer{
					Timeout:   1 * time.Second,
					KeepAlive: 1 * time.Second,
					DualStack: false,
				}).DialContext(ctx, network, strings.TrimPrefix(server.URL, "http://"))
			},
		},
	}

	device := NewDevice(testIP, client)
	if err := device.SetIntensities(ctx, 1, 2, 3, 4); err != nil {
		t.Fatal(err)
	}

	statusToReturn = 400
	if err := device.SetIntensities(ctx, 1, 2, 3, 4); err == nil {
		t.Errorf("expected an error on status 400, got none")
	}
}

const statusResponse = `<r>
2017:03:17:19:07:56
Not running
<c>OK</c>
<d>0d 02h 39m 37s</d>
<e>2017-03-17	18:58:34</e>
<f>Web</f>
<g>192.168.1.3</g>
<h>Light setting</h>
0:26.0C,
<j>0:0,1:0,2:0,3:0,</j>
<k> </k>
<l> </l>
<m>Independent</m>
<n>C:on</n>
<o>off:Enter your message here:heliospectra</o>

<q>on, pool.ntp.org, 00:00:00</q>
<s>on</s>
<r></r>
<t>0.0A,0.0W</t>
</r>`

func TestDevice_Status(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	statusToReturn := 200
	bodyToReturn := statusResponse

	statusHandler := func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "GET" {
			t.Errorf("expected GET, got %s", r.Method)
		}
		if r.URL.Path != "/status.xml" {
			t.Errorf("expected URL /status.xml, got %s", r.URL.Path)
		}
		w.WriteHeader(statusToReturn)
		if _, err := w.Write([]byte(bodyToReturn)); err != nil {
			t.Fatal(err)
		}
	}
	server := httptest.NewServer(http.HandlerFunc(statusHandler))
	defer server.Close()

	testIP := net.IPv4(192, 168, 1, 8)

	client := &http.Client{
		Transport: &http.Transport{
			DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
				expectedAddr := testIP.String() + ":80"
				if addr != expectedAddr {
					t.Errorf("expected request to be sent to %s, was sent to %s", expectedAddr, addr)
				}
				// override the DialContext func to only dial to our test server:
				return (&net.Dialer{
					Timeout:   1 * time.Second,
					KeepAlive: 1 * time.Second,
					DualStack: false,
				}).DialContext(ctx, network, strings.TrimPrefix(server.URL, "http://"))
			},
		},
	}

	device := NewDevice(testIP, client)
	status, err := device.Status(ctx)
	if err != nil {
		t.Fatal(err)
	}

	expected := &Status{
		InternalTime: "2017:03:17:19:07:56",
		OnSchedule:   "Not running",
		Status:       "OK",
		Uptime:       "0d 02h 39m 37s",
		LastChangeAt: "2017-03-17	18:58:34",
		LastChangeInterface: "Web",
		LastChangeBy:        net.IPv4(192, 168, 1, 3),
		LastChangeType:      "Light setting",
		Temp:                "0:26.0C,",
		Intensities:         "0:0,1:0,2:0,3:0,",
		Masters:             " ",
		Reserved:            " ",
		ControlMode:         "Independent",
		NTPTimeSettings:     "on, pool.ntp.org, 00:00:00",
	}

	if !reflect.DeepEqual(expected, status) {
		t.Errorf("expected status=%#v\n\ngot status=%#v", expected, status)
	}

	statusToReturn = 400
	_, err = device.Status(ctx)
	if err == nil {
		t.Errorf("expected an error on status 400, got none")
	}

	statusToReturn = 200
	bodyToReturn = `{"some":"json"}`
	if _, err = device.Status(ctx); err == nil {
		t.Errorf("expected an error on a non-XML body, got none")
	}
}


text:
#include <stdint.h>

#include "error/s2n_errno.h"

#include "tls/s2n_connection.h"
#include "tls/s2n_record.h"
#include "tls/s2n_cipher_suites.h"
#include "tls/s2n_tls.h"

#include "stuffer/s2n_stuffer.h"

#include "utils/s2n_safety.h"
#include "utils/s2n_map.h"

int s2n_handshake_write_header(struct s2n_connection *conn, uint8_t message_type)
{
    S2N_ERROR_IF(s2n_stuffer_data_available(&conn->handshake.io), S2N_ERR_HANDSHAKE_STATE);

    /* Write the message header */
    GUARD(s2n_stuffer_write_uint8(&conn->handshake.io, message_type));

    /* Leave the length blank for now */
    uint16_t length = 0;
    GUARD(s2n_stuffer_write_uint24(&conn->handshake.io, length));

    return 0;
}

int s2n_handshake_finish_header(struct s2n_connection *conn)
{
    uint16_t length = s2n_stuffer_data_available(&conn->handshake.io);
    S2N_ERROR_IF(length < TLS_HANDSHAKE_HEADER_LENGTH, S2N_ERR_SIZE_MISMATCH);

    uint16_t payload = length - TLS_HANDSHAKE_HEADER_LENGTH;

    /* Write the message header */
    GUARD(s2n_stuffer_rewrite(&conn->handshake.io));
    GUARD(s2n_stuffer_skip_write(&conn->handshake.io, 1));
    GUARD(s2n_stuffer_write_uint24(&conn->handshake.io, payload));
    GUARD(s2n_stuffer_skip_write(&conn->handshake.io, payload));

    return 0;
}

int s2n_handshake_parse_header(struct s2n_connection *conn, uint8_t * message_type, uint32_t * length)
{
    S2N_ERROR_IF(s2n_stuffer_data_available(&conn->handshake.io) < TLS_HANDSHAKE_HEADER_LENGTH, S2N_ERR_SIZE_MISMATCH);

    /* read the message header */
    GUARD(s2n_stuffer_read_uint8(&conn->handshake.io, message_type));
    GUARD(s2n_stuffer_read_uint24(&conn->handshake.io, length));

    return 0;
}

int s2n_handshake_get_hash_state(struct s2n_connection *conn, s2n_hash_algorithm hash_alg, struct s2n_hash_state *hash_state)
{
    switch (hash_alg) {
    case S2N_HASH_MD5:
        *hash_state = conn->handshake.md5;
        break;
    case S2N_HASH_SHA1:
        *hash_state = conn->handshake.sha1;
        break;
    case S2N_HASH_SHA224:
        *hash_state = conn->handshake.sha224;
        break;
    case S2N_HASH_SHA256:
        *hash_state = conn->handshake.sha256;
        break;
    case S2N_HASH_SHA384:
        *hash_state = conn->handshake.sha384;
        break;
    case S2N_HASH_SHA512:
        *hash_state = conn->handshake.sha512;
        break;
    case S2N_HASH_MD5_SHA1:
        *hash_state = conn->handshake.md5_sha1;
        break;
    default:
        S2N_ERROR(S2N_ERR_HASH_INVALID_ALGORITHM);
    }
    return 0;
}

int s2n_handshake_require_all_hashes(struct s2n_handshake *handshake)
{
    memset(handshake->required_hash_algs, 1, sizeof(handshake->required_hash_algs));
    return 0;
}

static int s2n_handshake_require_hash(struct s2n_handshake *handshake, s2n_hash_algorithm hash_alg)
{
    handshake->required_hash_algs[hash_alg] = 1;
    return 0;
}

uint8_t s2n_handshake_is_hash_required(struct s2n_handshake *handshake, s2n_hash_algorithm hash_alg)
{
    return handshake->required_hash_algs[hash_alg];
}

/* Update the required handshake hash algs depending on current handshake session state.
 * This function must called at the end of a handshake message handler. Additionally it must be called after the
 * ClientHello or ServerHello is processed in client and server mode respectively. The relevant handshake parameters
 * are not available until those messages are processed.
 */
int s2n_conn_update_required_handshake_hashes(struct s2n_connection *conn)
{
    /* Clear all of the required hashes */
    memset(conn->handshake.required_hash_algs, 0, sizeof(conn->handshake.required_hash_algs));

    message_type_t handshake_message = s2n_conn_get_current_message_type(conn);
    const uint8_t client_cert_verify_done = (handshake_message >= CLIENT_CERT_VERIFY) ? 1 : 0;
    s2n_cert_auth_type client_cert_auth_type;
    GUARD(s2n_connection_get_client_auth_type(conn, &client_cert_auth_type));

    /* If client authentication is possible, all hashes are needed until we're past CLIENT_CERT_VERIFY. */
    if ((client_cert_auth_type != S2N_CERT_AUTH_NONE) && !client_cert_verify_done) {
        GUARD(s2n_handshake_require_all_hashes(&conn->handshake));
        return 0;
    }

    /* We don't need all of the hashes. Set the hash alg(s) required for the PRF */
    switch (conn->actual_protocol_version) {
    case S2N_SSLv3:
    case S2N_TLS10:
    case S2N_TLS11:
        GUARD(s2n_handshake_require_hash(&conn->handshake, S2N_HASH_MD5));
        GUARD(s2n_handshake_require_hash(&conn->handshake, S2N_HASH_SHA1));
        break;
    case S2N_TLS12:
        /* fall through */
    case S2N_TLS13:
    {
        /* For TLS 1.2 and TLS 1.3, the cipher suite defines the PRF hash alg */
        s2n_hmac_algorithm prf_alg = conn->secure.cipher_suite->prf_alg;
        s2n_hash_algorithm hash_alg;
        GUARD(s2n_hmac_hash_alg(prf_alg, &hash_alg));
        GUARD(s2n_handshake_require_hash(&conn->handshake, hash_alg));
        break;
    }
    }

    return 0;
}

/*
 * Take a hostname and return a single "simple" wildcard domain name that matches it.
 * The output wildcard representation is meant to be compared directly against a wildcard domain in a certificate.
 * We take a restrictive definition of wildcard here to achieve a single unique wildcard representation
 * given any input hostname.
 * No embedded or trailing wildcards are supported. Additionally, we only support one level of wildcard matching.
 * Thus the output should be a single wildcard character in the first(left-most) DNS label.
 *
 * Example:
 * - my.domain.name -> *.domain.name
 *
 * Not supported:
 * - my.domain.name -> m*.domain.name
 * - my.domain.name -> my.*.name
 * etc.
 *
 * The motivation for using a constrained definition of wildcard:
 * - Support for issuing non-simple wildcard certificates is insignificant.
 * - Certificate selection can be implemented with a constant number of lookups(two).
 */
int s2n_create_wildcard_hostname(struct s2n_stuffer *hostname_stuffer, struct s2n_stuffer *output)
{
    /* Find the end of the first label */
    GUARD(s2n_stuffer_skip_to_char(hostname_stuffer, '.'));

    /* No first label found */
    if (s2n_stuffer_data_available(hostname_stuffer) == 0) {
        return 0;
    }

    /* Slap a single wildcard character to be the first label in output */
    GUARD(s2n_stuffer_write_uint8(output, '*'));

    /* Simply copy the rest of the input to the output. */
    GUARD(s2n_stuffer_copy(hostname_stuffer, output, s2n_stuffer_data_available(hostname_stuffer)));

    return 0;
}

static int s2n_find_cert_matches(struct s2n_map *domain_name_to_cert_map,
        struct s2n_blob *dns_name,
        struct s2n_cert_chain_and_key *matches[S2N_AUTHENTICATION_METHOD_SENTINEL],
        uint8_t *match_exists)
{
    struct s2n_blob map_value;
    if (s2n_map_lookup(domain_name_to_cert_map, dns_name, &map_value) == 1) {
        struct auth_method_to_cert_value *value = (void *) map_value.data;
        for (int i = 0; i < S2N_AUTHENTICATION_METHOD_SENTINEL; i++) {
            matches[i] = value->certs[i];
        }
        *match_exists = 1;
    }

    return 0;
}

/* Find certificates that match the ServerName TLS extension sent by the client.
 * For a given ServerName there can be multiple matching certificates based on the
 * type of key in the certificate.
 *
 * A match is determined using s2n_map lookup by DNS name.
 * Wildcards that have a single * in the left most label are supported.
 */
int s2n_conn_find_name_matching_certs(struct s2n_connection *conn)
{
    if (!s2n_server_received_server_name(conn)) {
        return 0;
    }
    const char *name = conn->server_name;
    struct s2n_blob hostname_blob = { .data = (uint8_t *) (uintptr_t) name, .size = strlen(name) };
    lte_check(hostname_blob.size, S2N_MAX_SERVER_NAME);
    char normalized_hostname[S2N_MAX_SERVER_NAME + 1] = { 0 };
    memcpy_check(normalized_hostname, hostname_blob.data, hostname_blob.size);
    struct s2n_blob normalized_name = { .data = (uint8_t *) normalized_hostname, .size = hostname_blob.size };
    GUARD(s2n_blob_char_to_lower(&normalized_name));
    struct s2n_stuffer normalized_hostname_stuffer;
    GUARD(s2n_stuffer_init(&normalized_hostname_stuffer, &normalized_name));
    GUARD(s2n_stuffer_skip_write(&normalized_hostname_stuffer, normalized_name.size));

    /* Find the exact matches for the ServerName */
    GUARD(s2n_find_cert_matches(conn->config->domain_name_to_cert_map,
                &normalized_name,
                conn->handshake_params.exact_sni_matches,
                &(conn->handshake_params.exact_sni_match_exists)));

    if (!conn->handshake_params.exact_sni_match_exists) {
        /* We have not yet found an exact domain match. Try to find wildcard matches. */
        char wildcard_hostname[S2N_MAX_SERVER_NAME + 1] = { 0 };
        struct s2n_blob wildcard_blob = { .data = (uint8_t *) wildcard_hostname, .size = sizeof(wildcard_hostname) };
        struct s2n_stuffer wildcard_stuffer;
        GUARD(s2n_stuffer_init(&wildcard_stuffer, &wildcard_blob));
        GUARD(s2n_create_wildcard_hostname(&normalized_hostname_stuffer, &wildcard_stuffer));
        const uint32_t wildcard_len = s2n_stuffer_data_available(&wildcard_stuffer);

        /* Couldn't create a valid wildcard from the input */
        if (wildcard_len == 0) {
            return 0;
        }

        /* The client's SNI is wildcardified, do an exact match against the set of server certs. */
        wildcard_blob.size = wildcard_len;
        GUARD(s2n_find_cert_matches(conn->config->domain_name_to_cert_map,
                    &wildcard_blob,
                    conn->handshake_params.wc_sni_matches,
                    &(conn->handshake_params.wc_sni_match_exists)));
    }

    /* If we found a suitable cert, we should send back the ServerName extension.
     * Note that this may have already been set by the client hello callback, so we won't override its value
     */
    conn->server_name_used = conn->server_name_used
        || conn->handshake_params.exact_sni_match_exists
        || conn->handshake_params.wc_sni_match_exists;

    return 0;
}


text:
[![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)

Supporting app for [this workshop module](http://ccoenraets.github.io/salesforce-developer-advanced/Using-the-Salesforce1-Platform-APIs.html).

1. Access the following GitHub repository:

    [https://github.com/ccoenraets/salesforce-conference-demo](https://github.com/ccoenraets/salesforce-conference-demo)

1. Click the **Deploy to Heroku** button
    - For **App Name**, specify a name for your application. For example, if you specify my-conference, your application will be available at http://my-conference.herokuapp.com. Your app name has to be unique on the herokuapp.com domain.
    - For **APP_ID** in the deployment wizard, paste the consumer key of the connected app you created in step 1.
    - Click the **Deploy For Free** button

1. In Salesforce, go back to your Connected App and adjust the URLs based on your Heroku app name:
     - For **Callback URL**, specify: https://my-conference.herokuapp.com/oauthcallback.html

     > Replace **my-conference** with your own app name.

     xcode-select --install
  117  brew uninstall pkg-config cairo libpng jpeg giflib
  118  brew install pkg-config cairo libpng jpeg giflib
  119  npm install canvas
  120  brew install pkg-config cairo libpng jpeg giflib
  121  brew link libpng fontconfig
  122  sudo chmod 777 /usr/local/share/man/man5
  123  brew link libpng fontconfig
  124  brew install pkg-config cairo libpng jpeg giflib
  125  npm install canvas


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

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp" />
</RelativeLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="grey900">#212121</color>
    <color name="solarizedOrange">#cb4b16</color>
    <color name="solarizedBase1">#93a1a1</color>
    <color name="solarizedBase2">#eee8d5</color>
    <color name="solarizedBase02">#073642</color>
    <color name="solarizedBase03">#002b36</color>
    <color name="solarizedBlue">#268bd2</color>
    <color name="solarizedYellow">#b58900</color>

    <color name="afterglowHighlight">#333435</color>
    <color name="afterglowAccent">#cc7832</color>
    <color name="afterglowBackground">#2e2e2e</color>
    <color name="afterglowForeground">#d6d6d6</color>
    <color name="afterglowComment">#797979</color>
    <color name="afterglowConstant">#6D9CBE</color>
    <color name="afterglowDefinition">#FFC66D</color>
    <color name="afterglowString">#b4c973</color>

    <color name="tomorrowBackground">#1d1f21</color>
    <color name="tomorrowHighlight">#373b41</color>
    <color name="tomorrowForeground">#c5c8c6</color>
    <color name="tomorrowConstant">#81a2be</color>
    <color name="tomorrowDefinition">#de935f</color>
    <color name="tomorrowString">#b5bd68</color>
    <color name="tomorrowComment">#969896</color>
    <color name="tomorrowAccent">#cc6666</color>
</resources>


text:
/*
 * $Id: _psutil_osx.h 347 2009-04-24 17:02:36Z jloden $
 *
 * OS X platform-specific module methods for _psutil_osx
 */

#include <Python.h>

static PyObject* get_pid_list(PyObject* self, PyObject* args);
static PyObject* get_process_info(PyObject* self, PyObject* args);
static int pid_exists(long pid);
static PyObject* get_process_cpu_times(PyObject* self, PyObject* args);
static PyObject* get_process_create_time(PyObject* self, PyObject* args);
static PyObject* get_num_cpus(PyObject* self, PyObject* args);
static PyObject* get_memory_info(PyObject* self, PyObject* args);
static PyObject* get_total_phymem(PyObject* self, PyObject* args);
static PyObject* get_avail_phymem(PyObject* self, PyObject* args);
static PyObject* get_total_virtmem(PyObject* self, PyObject* args);
static PyObject* get_avail_virtmem(PyObject* self, PyObject* args);
static PyObject* get_system_cpu_times(PyObject* self, PyObject* args);


text:
(function ($, app) {

    'use strict';

    window.app = app || {};

    $(function () {

        window.app.datepickers = {
            startRangeBegin: $('#start-range-begin'),
            startRangeEnd: $('#start-range-end'),
            endRangeBegin: $('#end-range-begin'),
            endRangeEnd: $('#end-range-end')
        };

        window.app.modals = {
            randomData: $('#random-data-modal'),
            error: $('#error-modal')
        };

        window.app.controls = {
            map: $('#map-container'),
            mapProgress: $('#map-progress'),
            chart: $("#chart-container")
        };

        window.app.containers = {
            conversions: $('#conversions-container'),
            conversionsHighlight: $('#conversions-highlight'),
            status: $('#status-container'),
            question: $('#question-container'),
            errorMessage: app.modals.error.find('.modal-body')
        };

        window.app.buttons = {
            navigation: $('#navigation-container button'),
            chart: $('#chart-view-buttons button'),
            oneWeek: $('#one-week-button'),
            oneMonth: $('#one-month-button'),
            threeMonths: $('#three-months-button'),
            oneYear: $('#one-year-button'),
            allConversions: $('#all-button'),
            medium: $('#medium-button'),
            ppc: $('#ppc-button'),
            email: $('#email-button'),
            banners: $('#banners-button'),
            thirdParty: $('#thirdParty-button'),
            compare: $('#compare-button'),
            hideRandomDataModal: $('#hide-random-data-modal'),
            map: $("#map-play")
        };
    });

}(jQuery, window.app));


text:
using System;
using OpenTK.Graphics.OpenGL4;

namespace CGSharp.Buffers
{
    public class FBO : Buffer
    {
        public FBO(string bufferName, int bufferSize = 4, BufferTarget bufferTarget = BufferTarget.ShaderStorageBuffer) : base(bufferName, bufferSize, bufferTarget)
        {
            throw new NotImplementedException();
        }
    }
}


text:
package jp.co.flect.soap;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.BeforeClass;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.IOException;
import org.xml.sax.SAXException;
import org.w3c.dom.Node;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import jp.co.flect.util.ExtendedMap;
import jp.co.flect.io.FileUtils;
import jp.co.flect.xml.XMLUtils;
import jp.co.flect.xmlschema.template.TemplateBuilder;
import jp.co.flect.xmlschema.template.GroovyTemplateBuilder;
import jp.co.flect.xmlschema.template.VelocityTemplateBuilder;
import jp.co.flect.xmlschema.template.EmptyTemplateBuilder;
import jp.co.flect.xmlschema.template.TemplateHint;
import jp.co.flect.xmlschema.template.IgnoreHint;
import jp.co.flect.xmlschema.template.DerivedHint;
import jp.co.flect.xmlschema.XMLSchemaException;

public class SoapTest
{

	private static final String SF_ENTERPRISE_URI = "urn:enterprise.soap.sforce.com";
	private static final String SF_SOBJECT_URI    = "urn:sobject.enterprise.soap.sforce.com";

	private static WSDLWrapper wsdl;
	private static SoapClient soapClient;

	@BeforeClass
	public static void setup() {
		try {
			wsdl = new WSDLWrapper(new File("testdata/enterprise.wsdl"));
//			TemplateBuilder builder = new GroovyTemplateBuilder();
//			TemplateBuilder builder = new EmptyTemplateBuilder();
			TemplateBuilder builder = new VelocityTemplateBuilder();
			builder.setIndent(4);
			soapClient = new SoapClient(wsdl.getDocument(), builder);

			new File("target/test-output").mkdirs();
		} catch (XMLSchemaException e) {
			e.printStackTrace();
		} catch (InvalidWSDLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void endpoint() throws InvalidWSDLException {
		assertEquals(wsdl.getEndpoint(), "https://login.salesforce.com/services/Soap/c/24.0");
	}

	@Test
	public void operations() throws InvalidWSDLException {
		List<String> list = wsdl.getOperationNames();
		for (String s : list) {
			System.out.println("OperationName: " + s);
		}
		assertNotNull(list);
		assertTrue(list.size() > 0);
		assertTrue(list.contains("login") && list.contains("describeSObject"));
		List<OperationDef> list2 = wsdl.getOperations();
		assertEquals(list.size(), list2.size());
		OperationDef op = getOperation(list2, "query");
		assertNotNull(op);
		assertEquals("Create a Query Cursor", op.getDocumentation());
		assertEquals(6, op.getFaultCount());

		MessageDef msg = op.getRequestMessage();
		assertEquals(4, msg.getHeaderCount());
		assertEquals(1, msg.getBodyCount());
	}

	private OperationDef getOperation(List<OperationDef> list, String name) {
		for (OperationDef op : list) {
			if (op.getName().equals(name)) {
				return op;
			}
		}
		return null;
	}

	@Test
	public void templateTest() throws Exception {
		templateTest("login", null);
		templateTest("describeSObject", null);
		List<TemplateHint> hints = new ArrayList<TemplateHint>();
		hints.add(new IgnoreHint(new QName(SF_SOBJECT_URI, "DebuggingHeader")));
		hints.add(new DerivedHint(new QName(SF_SOBJECT_URI, "sObject"), new QName(SF_SOBJECT_URI, "Account")));
		soapClient.setDebug(true);
		templateTest("update", hints);
		soapClient.setDebug(false);
		templateTest("create", hints);
	}

	private void templateTest(String name, List<TemplateHint> hints) throws IOException {
		SoapTemplate template = soapClient.generateTemplate(name, hints);
		File f1 = new File("target/test-output/" + name + ".xml");
		File f2 = new File("testdata/" + name + "-base.xml");
		FileUtils.writeFile(f1, template.getTemplateString().getBytes("utf-8"));
		if (f2.exists()) {
			assertTrue(name, FileUtils.contentEquals(f1, f2));
		} else {
			f1.renameTo(f2);
		}
	}

	@Test
	public void messageTest() throws Exception {
		List<TemplateHint> hints = new ArrayList<TemplateHint>();
		hints.add(new IgnoreHint(new QName(SF_SOBJECT_URI, "DebuggingHeader")));
		hints.add(new DerivedHint(new QName(SF_SOBJECT_URI, "sObject"), new QName(SF_SOBJECT_URI, "Account")));

		MessageDef msg = soapClient.getOperation("create").getRequestMessage();
		MessageHelper helper = new MessageHelper(soapClient.getWSDL(), msg, hints);
		assertEquals(helper.getElementByPath("create.sObjects.AccountContactRoles.done").getName(), "done");
	}

	@Test
	public void saveTemplate() throws Exception {
		try {
			List<TemplateHint> hints = new ArrayList<TemplateHint>();
			hints.add(new IgnoreHint(new QName(SF_ENTERPRISE_URI, "DebuggingHeader")));
			hints.add(new IgnoreHint(new QName(SF_ENTERPRISE_URI, "EmailHeader")));
			hints.add(new DerivedHint(new QName(SF_SOBJECT_URI, "sObject"), new QName(SF_SOBJECT_URI, "Campaign")));

			File f1 = new File("target/test-output/upsert-base.txt");
			File f2 = new File("target/test-output/upsert.txt");
			SoapTemplate op1 = soapClient.generateTemplate("upsert", hints);
			op1.saveToFile(f1);

			SoapTemplate op2 = new SoapTemplate(f1);
			op2.saveToFile(f2);
			assertTrue("Compare soapTemplate", FileUtils.contentEquals(f1, f2));
		} catch (Throwable e) {
			e.printStackTrace();
			fail(e.toString());
		}
	}

}


text:
package fleet

import (
	"fmt"
	"io"
	"sync"
	"time"

	"github.com/coreos/fleet/schema"
	"github.com/deis/deis/pkg/prettyprint"
)

// Start units and wait for their desiredState
func (c *FleetClient) Start(targets []string, wg *sync.WaitGroup, out, ew io.Writer) {
	// expand @* targets
	expandedTargets, err := c.expandTargets(targets)
	if err != nil {
		io.WriteString(ew, err.Error())
		return
	}

	for _, target := range expandedTargets {
		wg.Add(1)
		go doStart(c, target, wg, out, ew)
	}
	return
}

func doStart(c *FleetClient, target string, wg *sync.WaitGroup, out, ew io.Writer) {
	defer wg.Done()

	// prepare string representation
	component, num, err := splitTarget(target)
	if err != nil {
		io.WriteString(ew, err.Error())
		return
	}
	name, err := formatUnitName(component, num)
	if err != nil {
		io.WriteString(ew, err.Error())
		return
	}

	requestState := "launched"
	desiredState := "running"

	if err := c.Fleet.SetUnitTargetState(name, requestState); err != nil {
		io.WriteString(ew, err.Error())
		return
	}

	// start with the likely subState to avoid sending it across the channel
	lastSubState := "dead"

	for {
		// poll for unit states
		states, err := c.Fleet.UnitStates()
		if err != nil {
			io.WriteString(ew, err.Error())
			return
		}

		// FIXME: fleet UnitStates API forces us to iterate for now
		var currentState *schema.UnitState
		for _, s := range states {
			if name == s.Name {
				currentState = s
				break
			}
		}
		if currentState == nil {
			fmt.Fprintf(ew, "Could not find unit: %v\n", name)
			return
		}

		// if subState changed, send it across the output channel
		if lastSubState != currentState.SystemdSubState {
			l := prettyprint.Overwritef(stateFmt, name, currentState.SystemdActiveState, currentState.SystemdSubState)
			fmt.Fprintf(out, l)
		}

		// break when desired state is reached
		if currentState.SystemdSubState == desiredState {
			fmt.Fprintln(out)
			return
		}

		lastSubState = currentState.SystemdSubState

		if lastSubState == "failed" {
			o := prettyprint.Colorize("{{.Red}}The service '%s' failed while starting.{{.Default}}\n")
			fmt.Fprintf(ew, o, target)
			return
		}
		time.Sleep(250 * time.Millisecond)
	}
}


text:
#ifndef REALM_BINARY_DATA_HPP
#define REALM_BINARY_DATA_HPP

#include <cstddef>
#include <algorithm>
#include <string>
#include <ostream>

#include <realm/util/features.h>
#include <realm/utilities.hpp>
#include <realm/owned_data.hpp>

namespace realm {

/// A reference to a chunk of binary data.
///
/// This class does not own the referenced memory, nor does it in any other way
/// attempt to manage the lifetime of it.
///
/// \sa StringData
class BinaryData {
public:
    BinaryData() noexcept : m_data(nullptr), m_size(0) {}
    BinaryData(const char* data, size_t size) noexcept: m_data(data), m_size(size) {}
    template<size_t N>
    explicit BinaryData(const char (&data)[N]): m_data(data), m_size(N) {}
    template<class T, class A>
    explicit BinaryData(const std::basic_string<char, T, A>&);

    template<class T, class A>
    explicit operator std::basic_string<char, T, A>() const;

    char operator[](size_t i) const noexcept { return m_data[i]; }

    const char* data() const noexcept { return m_data; }
    size_t size() const noexcept { return m_size; }

    /// Is this a null reference?
    ///
    /// An instance of BinaryData is a null reference when, and only when the
    /// stored size is zero (size()) and the stored pointer is the null pointer
    /// (data()).
    ///
    /// In the case of the empty byte sequence, the stored size is still zero,
    /// but the stored pointer is **not** the null pointer. Note that the actual
    /// value of the pointer is immaterial in this case (as long as it is not
    /// zero), because when the size is zero, it is an error to dereference the
    /// pointer.
    ///
    /// Conversion of a BinaryData object to `bool` yields the logical negation
    /// of the result of calling this function. In other words, a BinaryData
    /// object is converted to true if it is not the null reference, otherwise
    /// it is converted to false.
    ///
    /// It is important to understand that all of the functions and operators in
    /// this class, and most of the functions in the Realm API in general
    /// makes no distinction between a null reference and a reference to the
    /// empty byte sequence. These functions and operators never look at the
    /// stored pointer if the stored size is zero.
    bool is_null() const noexcept;

    friend bool operator==(const BinaryData&, const BinaryData&) noexcept;
    friend bool operator!=(const BinaryData&, const BinaryData&) noexcept;

    //@{
    /// Trivial bytewise lexicographical comparison.
    friend bool operator<(const BinaryData&, const BinaryData&) noexcept;
    friend bool operator>(const BinaryData&, const BinaryData&) noexcept;
    friend bool operator<=(const BinaryData&, const BinaryData&) noexcept;
    friend bool operator>=(const BinaryData&, const BinaryData&) noexcept;
    //@}

    bool begins_with(BinaryData) const noexcept;
    bool ends_with(BinaryData) const noexcept;
    bool contains(BinaryData) const noexcept;

    template<class C, class T>
    friend std::basic_ostream<C,T>& operator<<(std::basic_ostream<C,T>&, const BinaryData&);

    explicit operator bool() const noexcept;

private:
    const char* m_data;
    size_t m_size;
};

/// A read-only chunk of binary data.
class OwnedBinaryData : public OwnedData {
public:
    using OwnedData::OwnedData;

    OwnedBinaryData() = default;
    OwnedBinaryData(const BinaryData& data) : OwnedData(data.data(), data.size()) { }

    BinaryData get() const
    {
        return { data(), size() };
    }
};

// Implementation:

template<class T, class A>
inline BinaryData::BinaryData(const std::basic_string<char, T, A>& s):
    m_data(s.data()),
    m_size(s.size())
{
}

template<class T, class A>
inline BinaryData::operator std::basic_string<char, T, A>() const
{
    return std::basic_string<char, T, A>(m_data, m_size);
}

inline bool BinaryData::is_null() const noexcept
{
    return !m_data;
}

inline bool operator==(const BinaryData& a, const BinaryData& b) noexcept
{
    return a.m_size == b.m_size && a.is_null() == b.is_null() && safe_equal(a.m_data, a.m_data + a.m_size, b.m_data);
}

inline bool operator!=(const BinaryData& a, const BinaryData& b) noexcept
{
    return !(a == b);
}

inline bool operator<(const BinaryData& a, const BinaryData& b) noexcept
{
    if (a.is_null() || b.is_null())
        return !a.is_null() < !b.is_null();

    return std::lexicographical_compare(a.m_data, a.m_data + a.m_size,
                                        b.m_data, b.m_data + b.m_size);
}

inline bool operator>(const BinaryData& a, const BinaryData& b) noexcept
{
    return b < a;
}

inline bool operator<=(const BinaryData& a, const BinaryData& b) noexcept
{
    return !(b < a);
}

inline bool operator>=(const BinaryData& a, const BinaryData& b) noexcept
{
    return !(a < b);
}

inline bool BinaryData::begins_with(BinaryData d) const noexcept
{
    if (is_null() && !d.is_null())
        return false;

    return d.m_size <= m_size && safe_equal(m_data, m_data + d.m_size, d.m_data);
}

inline bool BinaryData::ends_with(BinaryData d) const noexcept
{
    if (is_null() && !d.is_null())
        return false;

    return d.m_size <= m_size && safe_equal(m_data + m_size - d.m_size, m_data + m_size, d.m_data);
}

inline bool BinaryData::contains(BinaryData d) const noexcept
{
    if (is_null() && !d.is_null())
        return false;

    return d.m_size == 0 ||
        std::search(m_data, m_data + m_size, d.m_data, d.m_data + d.m_size) != m_data + m_size;
}

template<class C, class T>
inline std::basic_ostream<C,T>& operator<<(std::basic_ostream<C,T>& out, const BinaryData& d)
{
    out << "BinaryData("<<static_cast<const void*>(d.m_data)<<", "<<d.m_size<<")";
    return out;
}

inline BinaryData::operator bool() const noexcept
{
    return !is_null();
}

} // namespace realm

#endif // REALM_BINARY_DATA_HPP


text:
"use strict";

import controller from "./controller";
import authorization from "../../middleware/authorization";

import { Router } from "express";

const router = Router();

router.use(authorization);

router.get("/get/unreviewed", controller.getUnReviewedAppeals);
router.get("/get/:id", controller.getAppeal);
router.get("/get_multiple/:query", controller.getAppeals);
router.post("/post", controller.postAppeal);
router.post("/review/post", controller.postReview);

module.exports = router;


text:
namespace nsCore
{

  class IMessageManager;
  class ISerializerOut;
  class ISerializerIn;

  class IComponent
  {
  protected:
    virtual ~IComponent(void) {}
  public:
    virtual unsigned GetComponentType(void) = 0;
    virtual void OnRegister(IMessageManager* owner) = 0;
    virtual void SerializeOut(ISerializerOut* out) = 0;
    virtual void SerializeIn(ISerializerIn* in) = 0;
  };

} // namespace nsCore


text:
/**
 *
 */
package org.devel.jsynfx.app;

import javafx.scene.Parent;
import javafx.scene.layout.HBox;

import org.devel.jsynfx.control.Knob;

import com.jsyn.JSyn;
import com.jsyn.Synthesizer;
import com.jsyn.unitgen.LineOut;
import com.jsyn.unitgen.LinearRamp;
import com.jsyn.unitgen.SawtoothOscillatorBL;
import com.jsyn.unitgen.UnitOscillator;

/**
 * @author stefan.illgen
 */
public class SynthesizerFX {

    private static final double MINIMUM_FREQUENCY = 50;
    private static final double MAXIMUM_FREQUENCY = 1000.0;

    private Synthesizer synth;
    private UnitOscillator osc;
    private LinearRamp lag;
    private LineOut lineOut;

    /**
     *
     */
    public SynthesizerFX() {
        createModel();
    }

    private void createModel() {
        synth = JSyn.createSynthesizer();
        synth.setRealTime(true);

        // Add a tone generator. (band limited sawtooth)
        synth.add(osc = new SawtoothOscillatorBL());
        // Add a lag to smooth out amplitude changes and avoid pops.
        synth.add(lag = new LinearRamp());
        // Add an output mixer.
        synth.add(lineOut = new LineOut());
        // Connect the oscillator to both left and right output.
        osc.output.connect(0, lineOut.input, 0);
        osc.output.connect(0, lineOut.input, 1);

        // Set the minimum, current and maximum values for the port.
        lag.output.connect(osc.amplitude);
        lag.input.setup(0.0, 0.5, 1.0);
        lag.time.set(0.2);

        osc.frequency.setup(MINIMUM_FREQUENCY, MINIMUM_FREQUENCY, MAXIMUM_FREQUENCY);
        // osc.amplitude.setup(1.0, 1.0, 10.0);

        // Start synthesizer using default stereo output at 44100 Hz.
        synth.start();

        // We only need to start the LineOut. It will pull data from the
        // oscillator.
        lineOut.start();
    }

    public void stop() {
        synth.stop();
    }

    public Parent createView() {
        // knobs
        HBox root = new HBox();
        Knob knobOscFreq =
            new Knob("Frequency", osc.frequency.get(), osc.frequency.getMinimum(), osc.frequency.getMaximum());
        knobOscFreq.valueProperty()
                   .addListener((observable, oldValue, newValue) -> osc.frequency.set(newValue.doubleValue()));
        // Knob knobOscAmp =
        // new Knob("Amplitude", osc.amplitude.get(),
        // osc.amplitude.getMinimum(), osc.amplitude.getMaximum());
        // knobOscAmp.valueProperty()
        // .addListener((observable, oldValue, newValue) ->
        // osc.amplitude.set(newValue.doubleValue()));
        Knob knobOscPhase = new Knob("Phase", osc.phase.get(), 0.0, 1.0);
        knobOscPhase.valueProperty()
                    .addListener((observable, oldValue, newValue) ->
                                 osc.phase.set(newValue.doubleValue()));
        root.getChildren().addAll(knobOscFreq
            // , knobOscAmp
            // , knobOscPhase
            );

        return root;
    }
}


text:
import itertools
import json
from collections import defaultdict

import networkx
import six
import sys

class AssemblyPoint(object):
    def __init__(self, seq1, seq2, seq1_or, seq2_or, sources, cw=None, parent_id=None, children_ids=None, self_id=None,
                 gap_size=None):
        self.seq1 = seq1
        self.seq2 = seq2
        self.seq1_or = seq1_or
        self.seq2_or = seq2_or
        self.sources = sorted(sources)
        self.cw = cw
        self.gap_size = gap_size
        self.self_id = self_id
        self.parent_id = parent_id
        self.children_ids = children_ids if children_ids is not None else []
        #### comparative metrics
        self.participates_in_merged = False
        self.in_conflicted = defaultdict(set)
        self.in_semi_conflicted = defaultdict(set)
        self.out_conflicted = defaultdict(set)
        self.out_semi_conflicted = defaultdict(set)
        self.seq1_par_or = None
        self.seq2_par_or = None
        #### ref metrics
        self.ref_metrics = RefMetrics()
        self.extra_data = {}

    @property
    def orientation_as_word(self):
        if self.is_unoriented:
            return "U"
        if self.is_semi_oriented:
            return "SO"
        return "O"

    @property
    def is_unoriented(self):
        return [self.seq1_or, self.seq2_or].count("?") == 2

    @property
    def is_semi_oriented(self):
        return [self.seq1_or, self.seq2_or].count("?") == 1

    @property
    def is_oriented(self):
        return [self.seq1_or, self.seq2_or].count("?") == 0

    def is_in_semi_conflicted_for(self, source_name):
        return source_name in self.in_semi_conflicted

    def is_in_conflicted_for(self, source_name):
        return source_name in self.in_conflicted

    def is_out_semi_conflicted_for(self, source_name):
        return len(self.out_semi_conflicted) > 0

    def is_out_conflicted_for(self, source_name):
        return len(self.out_conflicted) > 0

    @property
    def is_out_conflicted(self):
        return len(self.out_conflicted) > 0

    @property
    def is_out_semi_conflicted(self):
        return len(self.out_semi_conflicted) > 0

    @property
    def is_non_conflicted(self):
        return len(self.in_conflicted) == 0 and len(self.out_conflicted) == 0 and len(self.in_semi_conflicted) == 0 and len(
            self.out_semi_conflicted) == 0

    def get_edges(self, weight=False, sort=True):
        result = []
        for ap in self.get_all_all_possible_realizations():
            head = ap.seq1 + ("h" if ap.seq1_or == "+" else "t")
            tail = ap.seq2 + ("t" if ap.seq2_or == "+" else "h")
            hv = head
            tv = tail
            if sort:
                hv, tv = (hv, tv) if hv < tv else (tv, hv)
            if weight:
                result.append((hv, tv, self.cw))
            else:
                result.append((hv, tv))
        return result

    def get_all_all_possible_realizations(self):
        result = []
        if self.seq1_or == "?":
            seq1_choices = ["+", "-"]
        else:
            seq1_choices = [self.seq1_or]
        if self.seq2_or == "?":
            seq2_choices = ["+", "-"]
        else:
            seq2_choices = [self.seq2_or]
        for ctg1_or, ctg2_or in itertools.product(seq1_choices, seq2_choices):
            result.append(AssemblyPoint(seq1=self.seq1, seq2=self.seq2, seq1_or=ctg1_or, seq2_or=ctg2_or,
                                        sources=self.sources))
        return result

    @property
    def is_ambiguous(self):
        return self.seq1_or == "?" or self.seq2_or == "?"

class APFieldOutExtractorConverter(object):
    def __init__(self, field_name, converter_name):
        self.field_name = field_name
        self.converter = AP_FIELD_CONVERTERS[converter_name]

    def extract_field_value_str(self, ap):
        return self.converter.convert(getattr(ap, self.field_name))

class APFieldConverter(object):
    @staticmethod
    def convert(field_value, **kwargs):
        raise NotImplemented("Converter must be field/area specific")

class APFieldConverterStr(APFieldConverter):
    @staticmethod
    def convert(field_value, **kwargs):
        return str(field_value)

class APFieldConverterQuestionIfNone(APFieldConverterStr):
    @staticmethod
    def convert(field_value, **kwargs):
        if field_value is None:
            field_value = "?"
        return super(APFieldConverterQuestionIfNone, APFieldConverterQuestionIfNone).convert(field_value=field_value, **kwargs)

class APFieldConverterBooleanToInt(APFieldConverterQuestionIfNone):
    @staticmethod
    def convert(field_value, **kwargs):
        if field_value in [True, False]:
            field_value = int(field_value)
        return super(APFieldConverterBooleanToInt, APFieldConverterBooleanToInt).convert(field_value=field_value, **kwargs)

IdFieldConverter = APFieldConverterQuestionIfNone

class IterableFieldConverter(APFieldConverterQuestionIfNone):
    @staticmethod
    def convert(field_value, **kwargs):
        result = []
        treat_as_set = kwargs.get("as_set", True)
        for value in field_value:
            result.append(super(IterableFieldConverter, IterableFieldConverter).convert(field_value=value, **kwargs))
        if treat_as_set:
            result = set(result)
        result = sorted(result)
        treat_empty_as_zero = kwargs.get("empty_as_zero", True)
        if treat_empty_as_zero and len(result) == 0:
            return "0"
        separator = kwargs.get("intra_separator", ",")
        return separator.join(result)

class ConflictFieldConverter(APFieldConverter):
    @staticmethod
    def convert(field_value):
        conflicted_ids = [ap_id for conflict_assembly in field_value.values() for ap_id in conflict_assembly]
        return IterableFieldConverter.convert(field_value=conflicted_ids)

class RefMetrics(object):
    def __init__(self):
        #### correct
        self.present = False
        self.present_ref_ids = []
        #### incorrect
        # the worst error
        self.interchromosomal = False
        # the best error
        self.tranlocation = False
        self.translocation_path = []
        # can be combined with translocation, or can be on its own
        self.reversal = False
        # a subtype of reversal, better than reversal. possible for semi/un-oriented assembly points only
        self.semi_reversal = False
        # a best available reading of the reference genome for this particular assembly point
        self.best_ref_reading_id = None

class OrderGraph(object):
    def __init__(self, graph=None):
        self.graph = graph if graph is not None else networkx.Graph()

    def add_ap(self, ap):
        seq1, seq2 = ap.seq1, ap.seq2
        if self.graph.has_edge(u=seq1, v=seq2):
            self.graph[seq1][seq2]["ids"].append(ap.self_id)
            self.graph[seq1][seq2]["sources"].extend(ap.sources)
        else:
            self.graph.add_edge(seq1, seq2, ids=[ap.self_id], sources=[source for source in ap.sources])

    @classmethod
    def from_aps(cls, aps):
        result = cls()
        for ap in aps:
            result.add_ap(ap=ap)
        return result

class MergedScaffoldAssemblyGraph(object):
    def __init__(self):
        self.graph = networkx.Graph()

    def add_edge(self, u, v, weight):
        if self.graph.has_edge(u=u, v=v):
            self.graph[u][v]['weight'] += weight
        else:
            self.graph.add_edge(u, v, weight=weight)

    def get_maximal_non_conflicting_assembly_graph(self):
        max_matching = networkx.max_weight_matching(G=self.graph)
        seen = set()
        edges = []
        for key, value in max_matching.items():
            if key not in seen and value not in seen:
                edges.append((key, value))
                seen.add(key)
                seen.add(value)
        result = networkx.Graph()
        result.add_edges_from(edges)
        return result

    def edges(self, weight=True):
        if weight:
            return [(u, v, w) if u < v else (v, u, w) for (u, v, w) in self.graph.edges(data='weight')]
        else:
            return [(u, v) if u < v else (v, u) for (u, v) in self.graph.edges()]

    def remove_edges_with_low_cw(self, cw_threshold=0.0):
        low_weight_edges = [(u, v) for (u, v, d) in self.graph.edges(data=True) if d['weight'] < cw_threshold]
        self.graph.remove_edges_from(low_weight_edges)

class ScaffoldAssemblyGraph(object):
    def __init__(self):
        self.graph = networkx.MultiGraph()

    def add_edge(self, u, v, **kwargs):
        self.graph.add_edge(u, v, **kwargs)

    @classmethod
    def from_assembly_points(cls, assembly_points, reference=False, add_scaffold_edges=True):
        result = cls()
        scaffold_edges = get_scaffold_edges(assembly_points=assembly_points)
        if add_scaffold_edges:
            for u, v in scaffold_edges:
                result.add_edge(u=u, v=v, edge_type="scaffold")
        for ap in assembly_points:
            for (u, v, weight) in ap.get_edges(sort=True, weight=True):
                edge_type = "ref_assembly" if reference else "assembly"
                result.add_edge(u=u, v=v, weight=weight, edge_type=edge_type, ap_id=ap.self_id, ap_type=ap.orientation_as_word)
        return result

class Assembly(object):
    def __init__(self, name, aps):
        self.name = name
        self.aps = aps
        self.total_cnt = 0
        self.max_non_conflicting_aps = []

    @property
    def entries_names(self):
        return self.get_all_entries_names()

    def get_all_entries_names(self):
        return sorted(set(name for ap in self.aps for name in ap.sources))

    def sort_aps(self):
        self.aps = sorted(self.aps,
                          key=lambda ap: (ap.contig_1, ap.contig_1_orientation, ap.contig_2, ap.contig_2_orientation))

    @property
    def unoriented_ap_cnt(self):
        return sum(ap.is_unoriented for ap in self.aps)

    @property
    def semi_oriented_aps_cnt(self):
        return sum(ap.is_semi_oriented for ap in self.aps)

    @property
    def oriented_aps_cnt(self):
        return sum(ap.is_oriented for ap in self.aps)

    @property
    def in_conflicted_cnt(self):
        cnt = 0
        for ap in self.aps:
            if isinstance(self.name, tuple):
                to_check = self.name
            else:
                to_check = [self.name]
            for name in to_check:
                if ap.is_in_conflicted_for(name):
                    cnt += 1
                    break
        return cnt

    @property
    def in_semi_conflicted_cnt(self):
        cnt = 0
        for ap in self.aps:
            if isinstance(self.name, tuple):
                to_check = self.name
            else:
                to_check = [self.name]
            for name in to_check:
                if ap.is_in_semi_conflicted_for(name):
                    cnt += 1
                    break
        return cnt

    @property
    def out_conflicted_cnt(self):
        return sum(ap.is_out_conflicted for ap in self.aps)

    @property
    def out_semi_conflicted_cnt(self):
        return sum(ap.is_out_semi_conflicted for ap in self.aps)

    @property
    def non_conflicted_cnt(self):
        return len([ap for ap in self.aps if ap.is_non_conflicted])

def assign_ids_to_assembly_points(assembly_points, id_prefix="", id_generator=None, skip_existing=True, sort=False):
    assembly_points_by_ids = {}
    if id_generator is None:
        id_generator = itertools.count()
    existing_ids = set()
    if not skip_existing:
        for ap in assembly_points:
            if ap.self_id is not None and ap.self_id != "?":
                existing_ids.add(ap.self_id)
    if sort:
        s_assembly_points = sorted(assembly_points, key=lambda entry: (entry.seq1, entry.seq2, entry.seq1_or, entry.seq2_or, entry.sources))
    else:
        s_assembly_points = assembly_points
    for assembly_point in s_assembly_points:
        if skip_existing:
            new_id = id_prefix + str(six.next(id_generator))
            assembly_point.self_id = new_id
        elif assembly_point.self_id is None or assembly_point.self_id == "?":
            new_id = id_prefix + str(six.next(id_generator))
            while new_id in existing_ids:
                new_id = id_prefix + str(six.next(id_generator))
            assembly_point.self_id = new_id
        assembly_points_by_ids[assembly_point.self_id] = assembly_point
    return assembly_points_by_ids

def merge_assembly_points(assembly_points_by_source):
    unique_assembly_points = defaultdict(list)

    for assembly_points in assembly_points_by_source.values():
        for assembly_point in assembly_points:
            seq1, seq2 = assembly_point.seq1, assembly_point.seq2
            seq1_or, seq2_or = assembly_point.seq1_or, assembly_point.seq2_or
            if seq1 < seq2:
                entry = (seq1, seq1_or, seq2, seq2_or)
            else:
                entry = (seq2, inverse_orientation(seq2_or), seq1, inverse_orientation(seq1_or))
            unique_assembly_points[entry].append(assembly_point)
    result = []
    for (seq1, seq1_or, seq2, seq2_or), children in unique_assembly_points.items():
        sources = sorted(set(source for ap in children for source in ap.sources))
        weight = sum(ap.cw for ap in children)
        children_ids = [ap.self_id for ap in children]
        merged_assembly_point = AssemblyPoint(seq1=seq1, seq2=seq2, seq1_or=seq1_or, seq2_or=seq2_or,
                                              sources=sources, cw=weight, children_ids=children_ids)
        result.append(merged_assembly_point)
    return result

def assign_parents_to_children(children_assembly_points_by_ids, parent_assembly_points_by_ids):
    for p_assembly_point in parent_assembly_points_by_ids.values():
        for child_id in p_assembly_point.children_ids:
            children_assembly_points_by_ids[child_id].parent_id = p_assembly_point.self_id

def inverse_orientation(orientation):
    if orientation in ("+", "-"):
        return "+" if orientation == "-" else "-"
    return orientation

AP_FIELD_CONVERTERS = {
    "str_raw": APFieldConverterStr,
    "str": APFieldConverterQuestionIfNone,
    "bool": APFieldConverterBooleanToInt,
    "conflict": ConflictFieldConverter,
    "id": IdFieldConverter,
    "iter": IterableFieldConverter,
}

def get_scaffold_edges(assembly_points):
    unique_scaffolds = set()
    for ap in assembly_points:
        unique_scaffolds.add(ap.seq1)
        unique_scaffolds.add(ap.seq2)
    return [(name + "t", name + "h") for name in unique_scaffolds]

def to_json(value):
    if isinstance(value, Sequence):
        return json.dumps({"seq_id": value.name, "length": value.length})
    result = {}
    for key, values in value.items():
        if isinstance(values, str):
            result[key] = values
        else:
            result[key] = sorted(values)
    return json.dumps(result)

class Sequence(object):
    def __init__(self, name, length=None, parent_seq_id=None, start=None, end=None, strand="+", annotation=None, seq_group_id="Default"):
        self.name = name
        self._length = length
        self._parent_seq_id = parent_seq_id
        self._start = start
        self._end = end
        self._seq_group_id = seq_group_id
        self.strand = strand
        self._annotation = annotation

    @property
    def length(self):
        if self._length is not None:
            return self._length
        if self.start is not None and self.end is not None:
            return self.end - self.start
        return None

    @property
    def parent_seq_id(self):
        if self._parent_seq_id is None:
            return self.name
        return self._parent_seq_id

    @property
    def start(self):
        if self._start is None:
            return 0
        return int(self._start)

    @property
    def end(self):
        if self._end is None:
            return sys.maxsize
        return int(self._end)

    @property
    def seq_group_id(self):
        return str(self._seq_group_id)

    @property
    def annotation(self):
        return str(self._annotation)