text:
EXTRA_SCRIPT_FOLDER=$(dirname "${BASH_SOURCE[0]}")

source ${EXTRA_SCRIPT_FOLDER}/prompt.sh
source ${EXTRA_SCRIPT_FOLDER}/aliases.sh
source ${EXTRA_SCRIPT_FOLDER}/ssh.sh

source ${EXTRA_SCRIPT_FOLDER}/applications.sh
source ${EXTRA_SCRIPT_FOLDER}/osx.sh
source ${EXTRA_SCRIPT_FOLDER}/vagrant.sh
source ${EXTRA_SCRIPT_FOLDER}/docker.sh

redpajama_set_name: RedPajamaGithub


text:
<?php
use kartik\helpers\Html;
use kartik\widgets\Spinner;
use yii\helpers\Url;
use yii\helpers\Json;
use yii\web\Response;
use yii\helpers\ArrayHelper;
use yii\web\Request;
use yii\bootstrap\Modal;
use ptrnov\fusionchart\Chart;

	//DISTRIBUTOR SALES PO
	$distSalesPo= Chart::Widget([
		'urlSource'=> url::base().'/dashboard/rpt-esm-chart-salesmd/dist-sales-po',
		'userid'=>'piter@lukison.com',
		'dataArray'=>'[]',//$actionChartGrantPilotproject,				//array scource model or manual array or sqlquery
		'dataField'=>'[]',//['label','value'],							//field['label','value'], normaly value is numeric
		'type'=>'msline',//msline//'bar3d',//'gantt',				//Chart Type
		'renderid'=>'msline-distributor-sales-po',					//unix name render
		'autoRender'=>true,
		'width'=>'100%',
		'height'=>'300px',
	]);
	//$loadingSpinner1=Spinner::widget(['id'=>'spn1-load-road','preset' => 'large', 'align' => 'center', 'color' => 'blue']);

?>

<?php //$loadingSpinner1?>
<?=$distSalesPo?>


text:
package com.osc4j;

import com.squareup.okhttp.MediaType;

/**
 * Constrains.
 *
 * @author Xinyue Zhao
 */
public final class Consts {
	/**
	 * A configuration-file must be located under asset.
	 */
	static final String CONFIG_FILE = "osc4j.properties";
	/**
	 * Body type when http.
	 */
	static final MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded");

	/**
	 * Broadcast Action: The authentication is done.
	 */
	public static final String ACTION_AUTH_DONE = "com.osctweet4j.action.AUTH_DONE";
	/**
	 * Host of osc.
	 */
	static final String OSC_HOST = "http://osc-server-848.appspot.com/";
	/**
	 * Key for storage user-id
	 */
	static final String KEY_UID = "uid";
	/**
	 * Your name.
	 */
	static final String KEY_NAME = "name";
	/**
	 * Key for storage session
	 */
	public static final String KEY_SESSION = "oscid";
	/**
	 * Key for storage access-token
	 */
	public static final String KEY_ACCESS_TOKEN = "access_token";
	/**
	 * Key for storage for expires.
	 */
	public static final String KEY_EXPIRES = "expires";

	/**
	 * Login data format.
	 */
	static final String LOGIN_PARAMS = "u=%s&pw=%s&appid=%s&appsec=%s&redurl=%s&scope=%s";
	/**
	 * Login
	 */
	static final String LOGIN_URL = OSC_HOST + "login";
	/**
	 * Publish tweet.
	 */
	static final String TWEET_PUB_URL = OSC_HOST + "tweetPub";
	/**
	 * Reply someone on tweet.
	 */
	static final String TWEET_REPLY_URL = OSC_HOST + "tweetReply";
	/**
	 * Publish comment on tweet.
	 */
	static final String TWEET_COMMENT_PUB_URL = OSC_HOST + "tweetCommentPub?id=%d";
	/**
	 * Get tweet-lists.
	 */
	static final String TWEET_LIST_URL = OSC_HOST + "tweetList?page=%d";
	/**
	 * Get my tweet-lists.
	 */
	static final String TWEET_MY_LIST_URL = OSC_HOST + "myTweetList?uid=%d&page=%d";
	/**
	 * Get my tweet-lists.
	 */
	static final String TWEET_HOTSPOT_LIST_URL = OSC_HOST + "hotspotTweetList?page=%d";
	/**
	 * Friends-list.
	 */
	static final String FRIENDS_URL = OSC_HOST + "friendsList?uid=%d";
	/**
	 * User-information.
	 */
	static final String USER_INFORMATION_URL = OSC_HOST + "userInformation?uid=%d&fri=%d&msg=%d";
	/**
	 * Update relation between me and user.
	 */
	static final String UPDATE_RELATION_URL = OSC_HOST + "updateRelation?fri=%d&rel=%d";
	/**
	 * My personal information.
	 */
	static final String MY_INFORMATION_URL = OSC_HOST + "myInformation?uid=%d&me=%d";
	/**
	 * All comments of a tweet item.
	 */
	static final String TWEET_COMMENT_LIST_URL = OSC_HOST + "tweetCommentList?id=%d&page=%d";
	/**
	 * Tweet detail.
	 */
	static final String TWEET_DETAIL_URL = OSC_HOST + "tweetDetail?id=%d";
	/**
	 * Clear "@me" notice.
	 */
	static final String CLEAR_AT_NOTICE_URL = OSC_HOST + "clearAtNotice";
	/**
	 * Clear comment notice.
	 */
	static final String CLEAR_COMMENTS_NOTICE_URL = OSC_HOST + "clearCommentsNotice";
	/**
	 * Get list of all favorite-tweets.
	 */
	static final String FAVORITE_TWEETS_URL = OSC_HOST + "tweetFavorites?uid=%d";
	/**
	 * Add tweet to favorite.
	 */
	static final String ADD_TWEET_FAVORITE_URL = OSC_HOST + "addTweetFavorite?uid=%d&id=%d";
	/**
	 * Delete tweet to favorite.
	 */
	static final String DEL_TWEET_FAVORITE_URL = OSC_HOST + "delTweetFavorite?uid=%d&id=%d";
	/**
	 * Unknown people.
	 */
	static final String NO_RELATION_PEOPLE = OSC_HOST + "noRelationPeople?uid=%d&mp=%d&fp=%d";
}


text:
#pragma once

#include "Base/BaseTypes.h"
#include "FileSystem/XMLParserStatus.h"

namespace DAVA
{
class FilePath;
class XMLParserDelegate;
class XMLParser
{
public:
    /** Parse xml data from specified file and delegate and return error information. */
    static XMLParserStatus ParseFileEx(const FilePath& fileName, XMLParserDelegate* delegate);
    /** Parse xml data from specified buffer and delegate and return error information. */
    static XMLParserStatus ParseBytesEx(const char8* bytes, int32 length, XMLParserDelegate* delegate);
    /** Parse xml data from specified string and delegate and return error information. */
    static XMLParserStatus ParseStringEx(const String& str, XMLParserDelegate* delegate);

    DAVA_DEPRECATED(static bool ParseFile(const FilePath& fileName, XMLParserDelegate* delegate));
    DAVA_DEPRECATED(static bool ParseBytes(const unsigned char* bytes, int length, XMLParserDelegate* delegate));
};
};


text:
package com.sylvanaar.idea.Lua.lang.psi.impl.symbols;

import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.PsiReference;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaExpression;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaIdentifier;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaSymbol;

/**
 * Created by IntelliJ IDEA.
 * User: Jon S Akhtar
 * Date: 2/4/11
 * Time: 10:36 PM
 */
public class LuaWrapperReferenceElementImpl extends LuaReferenceElementImpl implements LuaExpression {
    @Override
    public boolean isSameKind(LuaSymbol symbol) {
//        assert false;
        if (getElement() instanceof LuaSymbol)
             return ((LuaSymbol) getElement()).isSameKind(symbol);
        return false;
    }

    public LuaWrapperReferenceElementImpl(ASTNode node) {
        super(node);
    }

    public PsiElement getElement() {
        return findChildByClass(LuaIdentifier.class);
    }

    public PsiReference getReference() {
        return this;
    }

    @Override
    public String getName() {
        return ((PsiNamedElement)getElement()).getName();
    }

    @Override
    public String toString() {
        return "Reference: " + getName();
    }

}


text:
function jsonp(obj) {
  T(jsonp_flag == 0);
  T(obj.results.length == 1 && obj.last_seq == 1, "jsonp");
  jsonp_flag = 1;
}

couchTests.changes = function(debug) {
  var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"true"});
  db.deleteDb();
  db.createDb();
  if (debug) debugger;

  var req = CouchDB.request("GET", "/test_suite_db/_changes");
  var resp = JSON.parse(req.responseText);

  T(resp.results.length == 0 && resp.last_seq == 0, "empty db");
  var docFoo = {_id:"foo", bar:1};
  T(db.save(docFoo).ok);
  T(db.ensureFullCommit().ok);
  T(db.open(docFoo._id)._id == docFoo._id);

  req = CouchDB.request("GET", "/test_suite_db/_changes");
  var resp = JSON.parse(req.responseText);

  T(resp.last_seq == 1);
  T(resp.results.length == 1, "one doc db");
  T(resp.results[0].changes[0].rev == docFoo._rev);

  // test with callback

  run_on_modified_server(
    [{section: "httpd",
      key: "allow_jsonp",
      value: "true"}],
  function() {
    var xhr = CouchDB.request("GET", "/test_suite_db/_changes?callback=jsonp");
    T(xhr.status == 200);
    jsonp_flag = 0;
    eval(xhr.responseText);
    T(jsonp_flag == 1);
  });

  req = CouchDB.request("GET", "/test_suite_db/_changes?feed=continuous&timeout=10");
  var lines = req.responseText.split("\n");
  T(JSON.parse(lines[0]).changes[0].rev == docFoo._rev);
  T(JSON.parse(lines[1]).last_seq == 1);

  var xhr;

  try {
    xhr = CouchDB.newXhr();
  } catch (err) {
  }

  // poor man's browser detection
  var is_safari = false;
  if(typeof(navigator) == "undefined") {
    is_safari = true; // For CouchHTTP based runners
  } else if(navigator.userAgent.match(/AppleWebKit/)) {
    is_safari = true;
  };
  if (!is_safari && xhr) {
    // Only test the continuous stuff if we have a real XHR object
    // with real async support.

    // WebKit (last checked on nightly #47686) does fail on processing
    // the async-request properly while javascript is executed.

    xhr.open("GET", CouchDB.proxyUrl("/test_suite_db/_changes?feed=continuous&timeout=500"), true);
    xhr.send("");

    var docBar = {_id:"bar", bar:1};
    db.save(docBar);

    var lines, change1, change2;
    waitForSuccess(function() {
      lines = xhr.responseText.split("\n");
      change1 = JSON.parse(lines[0]);
      change2 = JSON.parse(lines[1]);
      if (change2.seq != 2) {
          throw "bad seq, try again";
      }
      return true;
    }, "bar-only");

    T(change1.seq == 1);
    T(change1.id == "foo");

    T(change2.seq == 2);
    T(change2.id == "bar");
    T(change2.changes[0].rev == docBar._rev);

    var docBaz = {_id:"baz", baz:1};
    db.save(docBaz);

    var change3;
    waitForSuccess(function() {
      lines = xhr.responseText.split("\n");
      change3 = JSON.parse(lines[2]);
      if (change3.seq != 3) {
        throw "bad seq, try again";
      }
      return true;
    });

    T(change3.seq == 3);
    T(change3.id == "baz");
    T(change3.changes[0].rev == docBaz._rev);

    xhr = CouchDB.newXhr();

    //verify the hearbeat newlines are sent
    xhr.open("GET", CouchDB.proxyUrl("/test_suite_db/_changes?feed=continuous&heartbeat=10&timeout=500"), true);
    xhr.send("");

    var str;
    waitForSuccess(function() {
      str = xhr.responseText;
      if (str.charAt(str.length - 1) != "\n" || str.charAt(str.length - 2) != "\n") {
        throw("keep waiting");
      }
      return true;
    }, "heartbeat");

    T(str.charAt(str.length - 1) == "\n");
    T(str.charAt(str.length - 2) == "\n");

    // otherwise we'll continue to receive heartbeats forever
    xhr.abort();

    // test Server Sent Event (eventsource)
    if (!!window.EventSource) {
      var source = new EventSource(
              "/test_suite_db/_changes?feed=eventsource");
      var results = [];
      var sourceListener = function(e) {
        var data = JSON.parse(e.data);
        results.push(data);
      };

      source.addEventListener('message', sourceListener , false);

      waitForSuccess(function() {
        if (results.length != 3) {
          throw "bad seq, try again";
        }
        return true;
      });

      source.removeEventListener('message', sourceListener, false);

      T(results[0].seq == 1);
      T(results[0].id == "foo");

      T(results[1].seq == 2);
      T(results[1].id == "bar");
      T(results[1].changes[0].rev == docBar._rev);
    }

    // test longpolling
    xhr = CouchDB.newXhr();

    xhr.open("GET", CouchDB.proxyUrl("/test_suite_db/_changes?feed=longpoll"), true);
    xhr.send("");

    waitForSuccess(function() {
      lines = xhr.responseText.split("\n");
      if (lines[5] != '"last_seq":3}') {
        throw("still waiting");
      }
      return true;
    }, "last_seq");

    xhr = CouchDB.newXhr();

    xhr.open("GET", CouchDB.proxyUrl("/test_suite_db/_changes?feed=longpoll&since=3"), true);
    xhr.send("");

    var docBarz = {_id:"barz", bar:1};
    db.save(docBarz);

    var parse_changes_line = function(line) {
      if (line.charAt(line.length-1) == ",") {
        var linetrimmed = line.substring(0, line.length-1);
      } else {
        var linetrimmed = line;
      }
      return JSON.parse(linetrimmed);
    };

    waitForSuccess(function() {
      lines = xhr.responseText.split("\n");
      if (lines[3] != '"last_seq":4}') {
        throw("still waiting");
      }
      return true;
    }, "change_lines");

    var change = parse_changes_line(lines[1]);
    T(change.seq == 4);
    T(change.id == "barz");
    T(change.changes[0].rev == docBarz._rev);
    T(lines[3]=='"last_seq":4}');

    // test since=now
    xhr = CouchDB.newXhr();

    xhr.open("GET", "/test_suite_db/_changes?feed=longpoll&since=now", true);
    xhr.send("");

    var docBarz = {_id:"barzzzz", bar:1};
    db.save(docBarz);

    var parse_changes_line = function(line) {
      if (line.charAt(line.length-1) == ",") {
        var linetrimmed = line.substring(0, line.length-1);
      } else {
        var linetrimmed = line;
      }
      return JSON.parse(linetrimmed);
    };

    waitForSuccess(function() {
      lines = xhr.responseText.split("\n");
      if (lines[3] != '"last_seq":5}') {
        throw("still waiting");
      }
      return true;
    }, "change_lines");

    var change = parse_changes_line(lines[1]);
    T(change.seq == 5);
    T(change.id == "barzzzz");
    T(change.changes[0].rev == docBarz._rev);
    T(lines[3]=='"last_seq":5}');

  }

  // test the filtered changes
  var ddoc = {
    _id : "_design/changes_filter",
    "filters" : {
      "bop" : "function(doc, req) { return (doc.bop);}",
      "dynamic" : stringFun(function(doc, req) {
        var field = req.query.field;
        return doc[field];
      }),
      "userCtx" : stringFun(function(doc, req) {
        return doc.user && (doc.user == req.userCtx.name);
      }),
      "conflicted" : "function(doc, req) { return (doc._conflicts);}"
    },
    options : {
      local_seq : true
    },
    views : {
      local_seq : {
        map : "function(doc) {emit(doc._local_seq, null)}"
      },
      blah: {
        map : 'function(doc) {' +
              '  if (doc._id == "blah") {' +
              '    emit(null, null);' +
              '  }' +
              '}'
      }
    }
  };

  db.save(ddoc);

  var req = CouchDB.request("GET", "/test_suite_db/_changes?filter=changes_filter/bop");
  var resp = JSON.parse(req.responseText);
  T(resp.results.length == 0);

  db.save({"bop" : "foom"});
  db.save({"bop" : false});

  var req = CouchDB.request("GET", "/test_suite_db/_changes?filter=changes_filter/bop");
  var resp = JSON.parse(req.responseText);
  T(resp.results.length == 1, "filtered/bop");

  req = CouchDB.request("GET", "/test_suite_db/_changes?filter=changes_filter/dynamic&field=woox");
  resp = JSON.parse(req.responseText);
  T(resp.results.length == 0);

  req = CouchDB.request("GET", "/test_suite_db/_changes?filter=changes_filter/dynamic&field=bop");
  resp = JSON.parse(req.responseText);
  T(resp.results.length == 1, "changes_filter/dynamic&field=bop");

  if (!is_safari && xhr) { // full test requires parallel connections
    // filter with longpoll
    // longpoll filters full history when run without a since seq
    xhr = CouchDB.newXhr();
    xhr.open("GET", CouchDB.proxyUrl("/test_suite_db/_changes?feed=longpoll&filter=changes_filter/bop"), false);
    xhr.send("");
    var resp = JSON.parse(xhr.responseText);
    T(resp.last_seq == 8);
    // longpoll waits until a matching change before returning
    xhr = CouchDB.newXhr();
    xhr.open("GET", CouchDB.proxyUrl("/test_suite_db/_changes?feed=longpoll&since=7&filter=changes_filter/bop"), true);
    xhr.send("");
    db.save({"_id":"falsy", "bop" : ""}); // empty string is falsy
    db.save({"_id":"bingo","bop" : "bingo"});

    waitForSuccess(function() {
      resp = JSON.parse(xhr.responseText);
      return true;
    }, "longpoll-since");

    T(resp.last_seq == 10);
    T(resp.results && resp.results.length > 0 && resp.results[0]["id"] == "bingo", "filter the correct update");
    xhr.abort();

    var timeout = 500;
    var last_seq = 11;
    while (true) {

      // filter with continuous
      xhr = CouchDB.newXhr();
      xhr.open("GET", CouchDB.proxyUrl("/test_suite_db/_changes?feed=continuous&filter=changes_filter/bop&timeout="+timeout), true);
      xhr.send("");

      db.save({"_id":"rusty", "bop" : "plankton"});
      T(xhr.readyState != 4, "test client too slow");
      var rusty = db.open("rusty", {cache_bust : new Date()});
      T(rusty._id == "rusty");

      waitForSuccess(function() { // throws an error after 5 seconds
        if (xhr.readyState != 4) {
          throw("still waiting");
        }
        return true;
      }, "continuous-rusty");
      lines = xhr.responseText.split("\n");
      var good = false;
      try {
        JSON.parse(lines[3]);
        good = true;
      } catch(e) {
      }
      if (good) {
        T(JSON.parse(lines[1]).id == "bingo", lines[1]);
        T(JSON.parse(lines[2]).id == "rusty", lines[2]);
        T(JSON.parse(lines[3]).last_seq == last_seq, lines[3]);
        break;
      } else {
        xhr.abort();
        db.deleteDoc(rusty);
        timeout = timeout * 2;
        last_seq = last_seq + 2;
      }
    }
  }
  // error conditions

  // non-existing design doc
  var req = CouchDB.request("GET",
    "/test_suite_db/_changes?filter=nothingtosee/bop");
  TEquals(404, req.status, "should return 404 for non existant design doc");

  // non-existing filter
  var req = CouchDB.request("GET",
    "/test_suite_db/_changes?filter=changes_filter/movealong");
  TEquals(404, req.status, "should return 404 for non existant filter fun");

  // both
  var req = CouchDB.request("GET",
    "/test_suite_db/_changes?filter=nothingtosee/movealong");
  TEquals(404, req.status,
    "should return 404 for non existant design doc and filter fun");

  // changes get all_docs style with deleted docs
  var doc = {a:1};
  db.save(doc);
  db.deleteDoc(doc);
  var req = CouchDB.request("GET",
    "/test_suite_db/_changes?filter=changes_filter/bop&style=all_docs");
  var resp = JSON.parse(req.responseText);
  var expect = (!is_safari && xhr) ? 3: 1;
  TEquals(expect, resp.results.length, "should return matching rows");

  // test filter on view function (map)
  //
  T(db.save({"_id":"blah", "bop" : "plankton"}).ok);
  var req = CouchDB.request("GET", "/test_suite_db/_changes?filter=_view&view=changes_filter/blah");
  var resp = JSON.parse(req.responseText);
  T(resp.results.length === 1);
  T(resp.results[0].id === "blah");

  // test for userCtx
  run_on_modified_server(
    [{section: "httpd",
      key: "authentication_handlers",
      value: "{couch_httpd_auth, special_test_authentication_handler}"},
     {section:"httpd",
      key: "WWW-Authenticate",
      value:  "X-Couch-Test-Auth"}],

    function() {
      var authOpts = {"headers":{"WWW-Authenticate": "X-Couch-Test-Auth Chris Anderson:mp3"}};

      var req = CouchDB.request("GET", "/_session", authOpts);
      var resp = JSON.parse(req.responseText);

      T(db.save({"user" : "Noah Slater"}).ok);
      var req = CouchDB.request("GET", "/test_suite_db/_changes?filter=changes_filter/userCtx", authOpts);
      var resp = JSON.parse(req.responseText);
      T(resp.results.length == 0);

      var docResp = db.save({"user" : "Chris Anderson"});
      T(docResp.ok);
      T(db.ensureFullCommit().ok);
      req = CouchDB.request("GET", "/test_suite_db/_changes?filter=changes_filter/userCtx", authOpts);
      resp = JSON.parse(req.responseText);
      T(resp.results.length == 1, "userCtx");
      T(resp.results[0].id == docResp.id);
    }
  );

  req = CouchDB.request("GET", "/test_suite_db/_changes?limit=1");
  resp = JSON.parse(req.responseText);
  TEquals(1, resp.results.length);

  //filter includes _conflicts
  var id = db.save({'food' : 'pizza'}).id;
  db.bulkSave([{_id: id, 'food' : 'pasta'}], {all_or_nothing:true});

  req = CouchDB.request("GET", "/test_suite_db/_changes?filter=changes_filter/conflicted");
  resp = JSON.parse(req.responseText);
  T(resp.results.length == 1, "filter=changes_filter/conflicted");

  // test with erlang filter function
  run_on_modified_server([{
    section: "native_query_servers",
    key: "erlang",
    value: "{couch_native_process, start_link, []}"
  }], function() {
    var erl_ddoc = {
      _id: "_design/erlang",
      language: "erlang",
      filters: {
        foo:
          'fun({Doc}, Req) -> ' +
          '  case couch_util:get_value(<<"value">>, Doc) of' +
          '  undefined -> false;' +
          '  Value -> (Value rem 2) =:= 0;' +
          '  _ -> false' +
          '  end ' +
          'end.'
      }
    };

    db.deleteDb();
    db.createDb();
    T(db.save(erl_ddoc).ok);

    var req = CouchDB.request("GET", "/test_suite_db/_changes?filter=erlang/foo");
    var resp = JSON.parse(req.responseText);
    T(resp.results.length === 0);

    T(db.save({_id: "doc1", value : 1}).ok);
    T(db.save({_id: "doc2", value : 2}).ok);
    T(db.save({_id: "doc3", value : 3}).ok);
    T(db.save({_id: "doc4", value : 4}).ok);

    var req = CouchDB.request("GET", "/test_suite_db/_changes?filter=erlang/foo");
    var resp = JSON.parse(req.responseText);
    T(resp.results.length === 2);
    T(resp.results[0].id === "doc2");
    T(resp.results[1].id === "doc4");

    // test filtering on docids
    //

    var options = {
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({"doc_ids": ["something", "anotherthing", "andmore"]})
    };

    var req = CouchDB.request("POST", "/test_suite_db/_changes?filter=_doc_ids", options);
    var resp = JSON.parse(req.responseText);
    T(resp.results.length === 0);

    T(db.save({"_id":"something", "bop" : "plankton"}).ok);
    var req = CouchDB.request("POST", "/test_suite_db/_changes?filter=_doc_ids", options);
    var resp = JSON.parse(req.responseText);
    T(resp.results.length === 1);
    T(resp.results[0].id === "something");

    T(db.save({"_id":"anotherthing", "bop" : "plankton"}).ok);
    var req = CouchDB.request("POST", "/test_suite_db/_changes?filter=_doc_ids", options);
    var resp = JSON.parse(req.responseText);
    T(resp.results.length === 2);
    T(resp.results[0].id === "something");
    T(resp.results[1].id === "anotherthing");

    var docids = JSON.stringify(["something", "anotherthing", "andmore"]),
        req = CouchDB.request("GET", "/test_suite_db/_changes?filter=_doc_ids&doc_ids="+docids, options);
    var resp = JSON.parse(req.responseText);
    T(resp.results.length === 2);
    T(resp.results[0].id === "something");
    T(resp.results[1].id === "anotherthing");

    var req = CouchDB.request("GET", "/test_suite_db/_changes?filter=_design");
    var resp = JSON.parse(req.responseText);
    T(resp.results.length === 1);
    T(resp.results[0].id === "_design/erlang");

    if (!is_safari && xhr) {
        // filter docids with continuous
        xhr = CouchDB.newXhr();
        xhr.open("POST", CouchDB.proxyUrl("/test_suite_db/_changes?feed=continuous&timeout=500&since=7&filter=_doc_ids"), true);
        xhr.setRequestHeader("Content-Type", "application/json");

        xhr.send(options.body);

        T(db.save({"_id":"andmore", "bop" : "plankton"}).ok);

        waitForSuccess(function() {
            if (xhr.readyState != 4) {
              throw("still waiting");
            }
            return true;
        }, "andmore-only");

        var line = JSON.parse(xhr.responseText.split("\n")[0]);
        T(line.seq == 8);
        T(line.id == "andmore");
    }
  });

  // COUCHDB-1037 - empty result for ?limit=1&filter=foo/bar in some cases
  T(db.deleteDb());
  T(db.createDb());

  ddoc = {
    _id: "_design/testdocs",
    filters: {
      testdocsonly: (function(doc, req) {
        return (typeof doc.integer === "number");
      }).toString()
    }
  };
  T(db.save(ddoc));

  ddoc = {
    _id: "_design/foobar",
    foo: "bar"
  };
  T(db.save(ddoc));

  db.bulkSave(makeDocs(0, 5));

  req = CouchDB.request("GET", "/" + db.name + "/_changes");
  resp = JSON.parse(req.responseText);
  TEquals(7, resp.last_seq);
  TEquals(7, resp.results.length);

  req = CouchDB.request(
    "GET", "/"+ db.name + "/_changes?limit=1&filter=testdocs/testdocsonly");
  resp = JSON.parse(req.responseText);
  TEquals(3, resp.last_seq);
  TEquals(1, resp.results.length);
  TEquals("0", resp.results[0].id);

  req = CouchDB.request(
    "GET", "/" + db.name + "/_changes?limit=2&filter=testdocs/testdocsonly");
  resp = JSON.parse(req.responseText);
  TEquals(4, resp.last_seq);
  TEquals(2, resp.results.length);
  TEquals("0", resp.results[0].id);
  TEquals("1", resp.results[1].id);

  TEquals(0, CouchDB.requestStats('httpd', 'clients_requesting_changes').current);
  CouchDB.request("GET", "/" + db.name + "/_changes");
  TEquals(0, CouchDB.requestStats('httpd', 'clients_requesting_changes').current);

  // COUCHDB-1256
  T(db.deleteDb());
  T(db.createDb());

  T(db.save({"_id":"foo", "a" : 123}).ok);
  T(db.save({"_id":"bar", "a" : 456}).ok);

  options = {
      headers: {"Content-Type": "application/json"},
      body: JSON.stringify({"_rev":"1-cc609831f0ca66e8cd3d4c1e0d98108a", "a":456})
  };
  req = CouchDB.request("PUT", "/" + db.name + "/foo?new_edits=false", options);

  req = CouchDB.request("GET", "/" + db.name + "/_changes?style=all_docs");
  resp = JSON.parse(req.responseText);

  TEquals(3, resp.last_seq);
  TEquals(2, resp.results.length);

  req = CouchDB.request("GET", "/" + db.name + "/_changes?style=all_docs&since=2");
  resp = JSON.parse(req.responseText);

  TEquals(3, resp.last_seq);
  TEquals(1, resp.results.length);
  TEquals(2, resp.results[0].changes.length);

  // COUCHDB-1852
  T(db.deleteDb());
  T(db.createDb());

  // create 4 documents... this assumes the update sequnce will start from 0 and get to 4
  db.save({"bop" : "foom"});
  db.save({"bop" : "foom"});
  db.save({"bop" : "foom"});
  db.save({"bop" : "foom"});

  // simulate an EventSource request with a Last-Event-ID header
  req = CouchDB.request("GET", "/test_suite_db/_changes?feed=eventsource&timeout=0&since=0",
        {"headers": {"Accept": "text/event-stream", "Last-Event-ID": "2"}});

  // "parse" the eventsource response and collect only the "id: ..." lines
  var changes = req.responseText.split('\n')
     .map(function (el) {
        return el.split(":").map(function (el) { return el.trim()});
     })
     .filter(function (el) { return (el[0] === "id"); })

  // make sure we only got 2 changes, and they are update_seq=3 and update_seq=4
  T(changes.length === 2);
  T(changes[0][1] === "3");
  T(changes[1][1] === "4");

  // COUCHDB-1923
  T(db.deleteDb());
  T(db.createDb());

  var attachmentData = "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ=";

  db.bulkSave(makeDocs(20, 30, {
    _attachments:{
      "foo.txt": {
        content_type:"text/plain",
        data: attachmentData
      },
      "bar.txt": {
        content_type:"text/plain",
        data: attachmentData
      }
    }
  }));

  var mapFunction = function(doc) {
    var count = 0;

    for(var idx in doc._attachments) {
      count = count + 1;
    }

    emit(parseInt(doc._id), count);
  };

  var req = CouchDB.request("GET", "/test_suite_db/_changes?include_docs=true");
  var resp = JSON.parse(req.responseText);

  T(resp.results.length == 10);
  T(resp.results[0].doc._attachments['foo.txt'].stub === true);
  T(resp.results[0].doc._attachments['foo.txt'].data === undefined);
  T(resp.results[0].doc._attachments['foo.txt'].encoding === undefined);
  T(resp.results[0].doc._attachments['foo.txt'].encoded_length === undefined);
  T(resp.results[0].doc._attachments['bar.txt'].stub === true);
  T(resp.results[0].doc._attachments['bar.txt'].data === undefined);
  T(resp.results[0].doc._attachments['bar.txt'].encoding === undefined);
  T(resp.results[0].doc._attachments['bar.txt'].encoded_length === undefined);

  var req = CouchDB.request("GET", "/test_suite_db/_changes?include_docs=true&attachments=true");
  var resp = JSON.parse(req.responseText);

  T(resp.results.length == 10);
  T(resp.results[0].doc._attachments['foo.txt'].stub === undefined);
  T(resp.results[0].doc._attachments['foo.txt'].data === attachmentData);
  T(resp.results[0].doc._attachments['foo.txt'].encoding === undefined);
  T(resp.results[0].doc._attachments['foo.txt'].encoded_length === undefined);
  T(resp.results[0].doc._attachments['bar.txt'].stub === undefined);
  T(resp.results[0].doc._attachments['bar.txt'].data == attachmentData);
  T(resp.results[0].doc._attachments['bar.txt'].encoding === undefined);
  T(resp.results[0].doc._attachments['bar.txt'].encoded_length === undefined);

  var req = CouchDB.request("GET", "/test_suite_db/_changes?include_docs=true&att_encoding_info=true");
  var resp = JSON.parse(req.responseText);

  T(resp.results.length == 10);
  T(resp.results[0].doc._attachments['foo.txt'].stub === true);
  T(resp.results[0].doc._attachments['foo.txt'].data === undefined);
  T(resp.results[0].doc._attachments['foo.txt'].encoding === "gzip");
  T(resp.results[0].doc._attachments['foo.txt'].encoded_length === 47);
  T(resp.results[0].doc._attachments['bar.txt'].stub === true);
  T(resp.results[0].doc._attachments['bar.txt'].data === undefined);
  T(resp.results[0].doc._attachments['bar.txt'].encoding === "gzip");
  T(resp.results[0].doc._attachments['bar.txt'].encoded_length === 47);

  // cleanup
  db.deleteDb();
};


text:
namespace  {

using namespace bart;

using ::testing::DoDefault, ::testing::NiceMock, ::testing::ReturnRef;

class K_EffectiveCalculatorViaRayleighQuotientTest : public ::testing::Test {
 public:
  using SphericalHarmonicMock = NiceMock<system::moments::SphericalHarmonicMock>;
  using Vector = dealii::Vector<double>;

  static constexpr int total_groups_{ 2 };
  static constexpr int vector_size_{ 3 };
  const double initial_k_effective_{ 1.0235 };
  const double expected_k_effective_{ 0.4094 };
  std::array<Vector, total_groups_> current_moments_, previous_moments_;

  system::System test_system_ { .k_effective = initial_k_effective_, .total_groups = total_groups_ };

  SphericalHarmonicMock* current_moments_obs_ptr_;
  SphericalHarmonicMock* previous_moments_obs_ptr_;

  auto SetUp() -> void override;
};

auto K_EffectiveCalculatorViaRayleighQuotientTest::SetUp() -> void {
  for (int group = 0; group < total_groups_; ++group) {
    Vector current_group_moment(vector_size_), previous_group_moment(vector_size_);
    for (int i = 0; i < vector_size_; ++i) {
      if (group == 0) {
        current_group_moment[i] = (i + 1);
        previous_group_moment[i] = (i + 1 + vector_size_);
      } else {
        current_group_moment[i] = vector_size_ - i;
        previous_group_moment[i] = 2 * vector_size_ - i;
      }
    }
    current_moments_.at(group) = current_group_moment;
    previous_moments_.at(group) = previous_group_moment;
  }

  test_system_.current_moments = std::make_unique<SphericalHarmonicMock>();
  test_system_.previous_moments = std::make_unique<SphericalHarmonicMock>();
  current_moments_obs_ptr_ = dynamic_cast<SphericalHarmonicMock*>(test_system_.current_moments.get());
  previous_moments_obs_ptr_ = dynamic_cast<SphericalHarmonicMock*>(test_system_.previous_moments.get());

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    ON_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillByDefault(ReturnRef(current_moments_.at(group)));
    ON_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillByDefault(ReturnRef(previous_moments_.at(group)));
  }
}

TEST_F(K_EffectiveCalculatorViaRayleighQuotientTest, Calculate) {
  eigenvalue::k_eigenvalue::CalculatorViaRayleighQuotient test_updater;
  EXPECT_FALSE(test_updater.k_eigenvalue().has_value());

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
    EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
  }

  auto calculated_k_effective = test_updater.CalculateK_Eigenvalue(test_system_);
  EXPECT_NEAR(calculated_k_effective, expected_k_effective_, 1e-8);
  ASSERT_TRUE(test_updater.k_eigenvalue().has_value());
  EXPECT_EQ(calculated_k_effective, test_updater.k_eigenvalue().value());
}

TEST_F(K_EffectiveCalculatorViaRayleighQuotientTest, ZeroCurrentFlux) {
  eigenvalue::k_eigenvalue::CalculatorViaRayleighQuotient test_updater;
  EXPECT_FALSE(test_updater.k_eigenvalue().has_value());

  Vector zero_flux(vector_size_);

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(ReturnRef(zero_flux));
    EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
  }

  auto calculated_k_effective = test_updater.CalculateK_Eigenvalue(test_system_);
  EXPECT_NEAR(calculated_k_effective, 0, 1e-8);
  ASSERT_TRUE(test_updater.k_eigenvalue().has_value());
  EXPECT_EQ(calculated_k_effective, test_updater.k_eigenvalue().value());
}

TEST_F(K_EffectiveCalculatorViaRayleighQuotientTest, ZeroPreviousFlux) {
  eigenvalue::k_eigenvalue::CalculatorViaRayleighQuotient test_updater;
  EXPECT_FALSE(test_updater.k_eigenvalue().has_value());

  Vector zero_flux(vector_size_);

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
    EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(ReturnRef(zero_flux));
  }

  auto calculated_k_effective = test_updater.CalculateK_Eigenvalue(test_system_);
  EXPECT_NEAR(calculated_k_effective, initial_k_effective_, 1e-8);
  ASSERT_TRUE(test_updater.k_eigenvalue().has_value());
  EXPECT_EQ(calculated_k_effective, test_updater.k_eigenvalue().value());
}

} // namespace


text:
/**
 * ---------------------------------------------------------------------
 * @file Sets up the application functionality.
 * @author Shahzeb Ihsan
 */

/**
 * Called on the "onload" event, sets event handlers for various elements.
 */
onload = function() {
   chrome.runtime.getBackgroundPage(
      function (bg_page) {
         // Populate the IP address field from the stored value
         window.stored_ip_port = bg_page.stored_ip_port;

         if (window.stored_ip_port !== undefined) {
            document.getElementById('ip_port').value = window.stored_ip_port;
         }

         // Populate the pre-defined sequences field from the stored value
         window.stored_predefined_sequences = bg_page.stored_predefined_sequences;

         if (window.stored_predefined_sequences !== undefined) {
            for (var i = 0; i < window.stored_predefined_sequences.length; i++) {
               option = document.createElement('option');
               option.text = window.stored_predefined_sequences[i];
               document.getElementById('predefined_sequences').add(option);
            }
         }
      });

   // Attach event listeners to UI elements
   document.getElementById('del_sequence').onclick = del_sequence;
   document.getElementById('add_sequence').onclick = popup;
   document.getElementById('close_popup').onclick = popup;
   document.getElementById('connect').onclick = connect;
   document.getElementById('send_data').onclick = send_data;
   document.getElementById('save_sequence').onclick = save_sequence;
};


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_MATH_SHIMS_NEXTMULTIPLE_H_
#define _BLAZE_MATH_SHIMS_NEXTMULTIPLE_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/system/Inline.h>

namespace blaze {

//=================================================================================================
//
//  NEXTMULTIPLE SHIM
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Rounds up an integral value to the next multiple of a given factor.
// \ingroup math
//
// \param value The integral value to be rounded up \f$[1..\infty)\f$.
// \param factor The factor of the multiple \f$[1..\infty)\f$.
// \return The next multiple of the given factor.
//
// This function rounds up the given integral value to the next multiple of the given integral
// factor. In case the integral value is already a multiple of the given factor, the value itself
// is returned. Note that the attempt to use the function with non-integral types results in a
// compilation error!
*/
template< typename T1, typename T2 >
BLAZE_ALWAYS_INLINE constexpr auto nextMultiple( T1 value, T2 factor ) noexcept
{
   return ( value + ( factor - ( value % factor ) ) % factor );
}
//*************************************************************************************************

} // namespace blaze

#endif


text:
using System;
using System.Diagnostics.Contracts;
using LanguageExt.Attributes;
using System.Threading.Tasks;

namespace LanguageExt.TypeClasses
{
    [Typeclass]
    public interface ChoiceUnsafeAsync<CH, L, R> : Typeclass
    {
        /// <summary>
        /// Is the choice in the first state
        /// </summary>
        [Pure]
        Task<bool> IsLeft(CH choice);

        /// <summary>
        /// Is the choice in the second state
        /// </summary>
        [Pure]
        Task<bool> IsRight(CH choice);

        /// <summary>
        /// Is the choice in the bottom
        /// </summary>
        [Pure]
        Task<bool> IsBottom(CH choice);

        /// <summary>
        /// Match the two states of the Choice and return a non-null C.
        /// </summary>
        /// <typeparam name="C">Return type</typeparam>
        [Pure]
        Task<C> MatchUnsafe<C>(CH choice, Func<L, C> Left, Func<R, C> Right, Func<C> Bottom = null);

        /// <summary>
        /// Match the two states of the Choice and return a non-null C.
        /// </summary>
        /// <typeparam name="C">Return type</typeparam>
        [Pure]
        Task<C> MatchUnsafeAsync<C>(CH choice, Func<L, Task<C>> LeftAsync, Func<R, C> Right, Func<C> Bottom = null);

        /// <summary>
        /// Match the two states of the Choice and return a non-null C.
        /// </summary>
        /// <typeparam name="C">Return type</typeparam>
        [Pure]
        Task<C> MatchUnsafeAsync<C>(CH choice, Func<L, C> Left, Func<R, Task<C>> RightAsync, Func<C> Bottom = null);

        /// <summary>
        /// Match the two states of the Choice and return a non-null C.
        /// </summary>
        /// <typeparam name="C">Return type</typeparam>
        [Pure]
        Task<C> MatchUnsafeAsync<C>(CH choice, Func<L, Task<C>> LeftAsync, Func<R, Task<C>> RightAsync, Func<C> Bottom = null);

        /// <summary>
        /// Match the two states of the Choice and return a non-null C.
        /// </summary>
        /// <typeparam name="C">Return type</typeparam>
        Task<Unit> MatchUnsafe(CH choice, Action<L> Left, Action<R> Right, Action Bottom = null);

        /// <summary>
        /// Match the two states of the Choice and return a non-null C.
        /// </summary>
        /// <typeparam name="C">Return type</typeparam>
        Task<Unit> MatchUnsafeAsync(CH choice, Func<L, Task> LeftAsync, Action<R> Right, Action Bottom = null);

        /// <summary>
        /// Match the two states of the Choice and return a non-null C.
        /// </summary>
        /// <typeparam name="C">Return type</typeparam>
        Task<Unit> MatchUnsafeAsync(CH choice, Action<L> Left, Func<R, Task> RightAsync, Action Bottom = null);

        /// <summary>
        /// Match the two states of the Choice and return a non-null C.
        /// </summary>
        /// <typeparam name="C">Return type</typeparam>
        Task<Unit> MatchUnsafeAsync(CH choice, Func<L, Task> LeftAsync, Func<R, Task> RightAsync, Action Bottom = null);
    }
}


text:
/**
 * Created by Administrator on 3/1/2016.
 */
import {mockHelpdeskLogin} from "./mock.js"
import {getMockToken} from "./mock.js"

export function mock() {
  if (Meteor.settings.debug) {
    mockHelpdeskLogin();
  }
}
let apiRoot = Meteor.settings.helpdesk.protocal + Meteor.settings.helpdesk.host + (Meteor.settings.helpdesk.port ? ":" + Meteor.settings.helpdesk.port : "");
let userToken = "";

function setUserToken(token) {
  userToken = token;
}
function getUserToken() {
  if (!Meteor.settings.debug) {
    //userToken = getMockToken();
    userToken = UnicallOauth.getAccessTokenFromDb(Meteor.userId());
  } else {
    userToken = getMockToken();
  }
  return userToken;
}
function composeHeader(agentInfo) {
  let header = {
    "Authorization": agentInfo ? "Bearer " + agentInfo.token : getUserToken(),
    "Content-Type": "application/json;charset=UTF-8",
    "Accept": "application/json, text/javascript, */*; q=0.01"
  }
  return header;
}
Meteor.methods(
  {
    'getSimulatedToken'(){
      if (Meteor.settings.public.debug) {
        return getMockToken();
      }
    }
  }
);
Meteor.startup(()=> {
    if (Meteor.settings.public.debug) {
      console.log("simulate oauth login");
      mockHelpdeskLogin();
      console.log("simulation token:" + getMockToken());
    }
  }
);
function gotAPIError(name, e) {
  let errStr = e.message.substring(e.message.indexOf("{"));
  let errObj = {};
  if (errStr && errStr.length > 0) {
    console.log(name + " error:" + errStr);
    try {
      error = JSON.parse(errStr);
      throw new Meteor.Error(name + " error:", errStr);
    } catch (e) {
      errObj.internalServerError = true;
      errObj.error = e;
    }
  }
  throw new Meteor.Error(name + " error:", JSON.stringify(error));
}
export function suggestContacts(key, page) {
  let url = apiRoot + Meteor.settings.helpdesk.api.suggestContacts;
  let term = key;
  let error = null;
  let res = null;
  try {
    res = HTTP.get(
      url,
      {
        "headers": composeHeader(),
        "query": "term=" + encodeURIComponent(term)
      }
    );
  } catch (e) {
    gotAPIError("suggestContact", e);
  }
  //console.log("suggest contacts result" + JSON.stringify(res));
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.data;
  } else {
    return null;
  }
}
export function getContactDetail(id) {
  let url = apiRoot + Meteor.settings.helpdesk.api.getContactDetail + "/" + id;
  let error = null;
  let res = null;
  try {
    res = HTTP.get(
      url,
      {
        "headers": composeHeader()
      }
    );
  } catch (e) {
    gotAPIError("getContactDetail", e);
  }
  //console.log("getContactDetail result" + JSON.stringify(res));
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.data;
  } else {
    return null;
  }
}
export function getTicketDomain() {
  let url = apiRoot + Meteor.settings.helpdesk.api.getTicketConfig;
  let error = null;
  let res = null;
  try {
    res = HTTP.get(
      url,
      {
        "headers": composeHeader()
      }
    );
  } catch (e) {
    gotAPIError("getTicketDomain", e);
  }

  //console.log("getTicketDomain result" + JSON.stringify(res));
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.data;
  } else {
    return null;
  }
}
export function getTicketConfig(agentInfo) {
  let url = apiRoot + Meteor.settings.helpdesk.api.getTicketConfig;
  if (agentInfo) {
    url = Meteor.settings.helpdesk.protocal + agentInfo.group + Meteor.settings.helpdesk.api.getTicketConfig;
  }
  let error = null;
  let res = null;
  try {
    res = HTTP.get(
      url,
      {
        "headers": composeHeader(agentInfo)
      }
    );
  } catch (e) {
    gotAPIError("getTicketConfig", e);
  }

  //console.log("getTicketConfig result" + JSON.stringify(res));
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.data;
  } else {
    return null;
  }
}
export function getAllAgentGroups(agentInfo) {
  let url = apiRoot + Meteor.settings.helpdesk.api.getAllAgentGroups;
  if (agentInfo) {
    url = Meteor.settings.helpdesk.protocal + agentInfo.group + Meteor.settings.helpdesk.api.getAllAgentGroups;
  }
  let error = null;
  let res = null;
  try {
    res = HTTP.get(
      url,
      {
        "headers": composeHeader(agentInfo)
      }
    );
  } catch (e) {
    gotAPIError("getAllAgentGroups", e);
  }

  //console.log("getAllAgentGroups result" + JSON.stringify(res));
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.data;
  } else {
    return null;
  }
}
export function getAllAgent(agentInfo) {
  let url = apiRoot + Meteor.settings.helpdesk.api.getAllAgent;
  if (agentInfo) {
    url = Meteor.settings.helpdesk.protocal + agentInfo.group + Meteor.settings.helpdesk.api.getAllAgent;
  }
  let error = null;
  let res = null;
  try {
    res = HTTP.get(
      url,
      {
        "headers": composeHeader(agentInfo)
      }
    );
  } catch (e) {
    gotAPIError("getAllAgent", e);
  }

  //console.log("getAllAgent result" + JSON.stringify(res));
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.data;
  } else {
    return null;
  }
}
export function getAllAgentInGroup(groupId) {
  let url = apiRoot + Meteor.settings.helpdesk.api.getAllAgentInGroup + "/" + groupId + "/members";
  let error = null;
  let res = null;
  try {
    res = HTTP.get(
      url,
      {
        "headers": composeHeader()
      }
    );
  } catch (e) {
    gotAPIError("getAllAgentInGroup", e);
  }

  //console.log("getAllAgentInGroup result" + JSON.stringify(res));
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.data;
  } else {
    return null;
  }
}

export function createContact(data, agentInfo) {
  let url = apiRoot + Meteor.settings.helpdesk.api.createContact;
  if (agentInfo) {
    url = Meteor.settings.helpdesk.protocal + agentInfo.group + Meteor.settings.helpdesk.api.createContact;
  }
  let error = null;
  let res = null;
  try {
    res = HTTP.post(
      url,
      {
        "headers": composeHeader(agentInfo),
        "data": data
      }
    );
  } catch (e) {
    gotAPIError("createContact", e);
  }
  //console.log("createContact result" + JSON.stringify(res));
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.data;
  } else {
    return null;
  }
}
export function updateContact(data, agentInfo) {
  let url = apiRoot + Meteor.settings.helpdesk.api.updateContact + "/" + data.id;
  if (agentInfo) {
    url = Meteor.settings.helpdesk.protocal + agentInfo.group + Meteor.settings.helpdesk.api.updateContact + "/" + data.id;
  }
  let error = null;
  let res = null;

  //console.log("server customer update", url, composeHeader(agentInfo), data);
  try {
    res = HTTP.put(
      url,
      {
        "headers": composeHeader(agentInfo),
        "data": data
      }
    );
  } catch (e) {
    gotAPIError("updateContact", e);
  }
  //console.log("updateContact result" + JSON.stringify(res));
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.data;
  } else {
    return null;
  }
}
export function createTicket(data, agentInfo) {
  let url = apiRoot + Meteor.settings.helpdesk.api.createTicket;
  if (agentInfo) {
    url = Meteor.settings.helpdesk.protocal + agentInfo.group + Meteor.settings.helpdesk.api.createTicket;
  }
  let error = null;
  let res = null;
  try {
    res = HTTP.post(
      url,
      {
        "headers": composeHeader(agentInfo),
        "data": data
      }
    );
  } catch (e) {
    gotAPIError("createTicket", e);
  }
  //console.log("createTicket result" + JSON.stringify(res));
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res;
  } else {
    return null;
  }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>About this Documentation</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../index.html" title="Chapter 1. Geometry">
<link rel="up" href="../index.html" title="Chapter 1. Geometry">
<link rel="prev" href="release_notes.html" title="Release Notes">
<link rel="next" href="acknowledgments.html" title="Acknowledgments">

Home
Libraries
People
FAQ
More

About this Documentation

      Within the Boost community there are several styles of documenting. Most libraries
      nowadays are using QuickBook, the WikiWiki style documentation.

      Boost.Geometry started with Doxygen, and during review it was decided to go
      to QuickBook. However, it was convenient to keep Doxygen also there: it does
      a good job of connecting descriptions to function and class declarations.

      Doxygen is able to generate XML (besides the normal HTML output), containing
      all documentation.

      So the challenge was to translate the XML generated by doxygen to QuickBook.
      At least, translate parts of it. Boost contains currently two tools using XSLT
      to go from Doxygen-XML to BoostBook, or to QuickBook. These tools are used
      within Boost.Random and Boost.Asio (and maybe more). However, this XSLT process
      was quite hard, did not deliver (yet) the wished results, and we are all C++
      programmers. So another tool was born, this time in C++ using RapidXML, going
      from Doxygen-XML to QuickBook with the ability to mix both.

      The
      chain

      The process is as following:

          call doxygen to go from C++ to XML

          call doxygen_xml2qbk to go from XML to QuickBook

          call bjam to from QuickBook to HTML

                bjam translates QuickBook to BoostBook

                bjam then translates from BoostBook to DocBook

                bjam then translates from DocBook to HTML

      This chain is currently called by "make_qbk.py", a Python script
      which calls the chain above in the right order. Python ensures that the chain
      can be handled in both Windows and Linux environments (it is probably possible
      to call all parts with bjam too).

      The
      reference matrix

      There reference matrix is the only thing written in BoostBook. It is an XML
      file with an overview of all Boost.Geometry functionality. Presenting it like
      this is not possible within QuickBook, therefore BoostBook XML is used here.
      It is included by the QuickBook code. The Boost.Asio documentation contains
      a similar reference matrix.

      Mixing
      QuickBook into C++ code

      With Doxygen it is possible to define aliases. Specificly for doxygen_xml2qbk,
      the alias \qbk{...} was defined. This alias
      \qbk{...} add some XML-tags around the text
      inside the alias, such that that included part is recognizable by the converter.

      So the C++ code might look like this:

/*!
\brief Some explanation
\ingroup some_group
\details Some details
\tparam Geometry Description of the template parameter
\param geometry Description of the variable

\qbk{ [include reference/more_documentation.qbk] }
 */

      First you see normal Doxygen comments. The last line uses the alias \qbk{...}
      to include a QuickBook file. So most of the documentation can be written in
      that QuickBook file: behaviour, complexity, examples, related pages, etc.

      In the example above a QuickBook include statement is used. But any QuickBook
      code can be used, the QuickBook code does not have to be stored in a separate
      file. Two more samples:

/*!
...
\qbk{
[heading Example]
[area_with_strategy]
[area_with_strategy_output]

[heading Available Strategies]
[link geometry.reference.strategies.strategy_area_cartesian Cartesian]
}
 */

      In this example pieces of QuickBook are included, two headers, two examples
      (this is the QuickBook way - the examples are defined elsewhere), and a link.

      QuickBook
      within C++ issues

      There are two issues: the comma and the asterisk. If within the \qbk
      alias a comma is used, it is recognized by Doxygen as another parameter, and
      therefore will not deliver the correct results, or result into errors. This
      is easily solvable by escaping comma's (by putting a backslash directly before
      the comma, \, ). It within the \qbk alias
      an asterisk is used on the first line, it is interpreted by Doxygen as well.
      This asterisk can be escaped as well, and this time it is doxygen_qbk2xml
      which handles this escape and translates it back into an asterisk.

      Overloads

      Boost.Geometry contains a lot of overloads, two functions with the same name
      and, for example, a different number of parameters. Or, as another example,
      a const and a non-const version. They can be marked specificly to the doxygen_xml2qbk
      tool with the \qbk alias, by adding a specific description for the overload.
      So, for example, \qbk{distinguish,with strategy}
      will result in another page where the text "with strategy" is added,
      and it is processed as "_with_strategy" within the QuickBook section
      name.

      Overloads
      and sharing documentation

      With overloads, part of the documentation must be shared, and other part must
      not. The descriptions are often the same. But the examples are usually not.
      So it is a balance between sharing documentation, including shared documentation,
      avoiding too much separate QuickBook files containing pieces of documentation
      and avoiding including too much QuickBook code within the C++ code...

      Doxygen
      aliases

      While documenting a large library, it is unavoidable that you have to document
      the same parameters in different places. For example, the template parameter
      Geometry, and the variable geometry,
      occur at least 100 times in our library.

      To avoid repeating the same text again and again, Doxygen aliases are used.
      So \tparam_geometry means that the generic description for a template parameter
      geometry is inserted. \param_geometry does the same for a parameter. This is
      all handled by Doxygen itself. The aliases can also be parameterized, for example:
      \return_calc{area} is expanded to: The
      calculated area

      This is for Doxygen alone and is not related to doxygen_xml2qbk
      or QuickBook.

      QuickBook
      macros

      QuickBook has the same functionality for the same purpose: macro's or templates
      can be defined. Within Boost.Geometry this is used in the QuickBook parts of
      the documentation. So the general rule would be: where it is possible to use
      a Doxygen alias, we use a Doxygen alias. If we are outside the scope of Doxygen
      and we want to define a macro, we use a QuickBook macro.

      Stated otherwise, we don't use the generated Doxygen documentation, but if
      we would, it would look correct and would not be unreadable by unexpanded QuickBook
      macro's.

      Code
      examples

      We favour the use of code examples within the generated documentation. Example
      code must be correct, so examples must compile, run, and produce the correct
      results. QuickBook has a nice solution to include and present C++ source code,
      including syntax highlighting. So we generally present the example (a complete
      example including necessary headerfiles) and the output. Asserts are not used
      here, these are examples and no tests.

      So this is why we did enclose in the \qbk alias above:

[heading Example]
[area_with_strategy]
[area_with_strategy_output]

      We define a heading, we include the example (here denoted by the name "area_with_strategy")
      and we include the output of the sample "area_with_strategy_output".
      Note that we simulate that the output is C++ code, a trick giving the appropriate
      formatting (there might be other ways to get the same effect).

      All these QuickBook examples are included in the doc/src/examples/* folders,
      where also a Jamfile is present. Running bjam there ensures that nothing is
      broken in the examples.

      Some examples, if relevant, are accompagnied by images. The images are generated
      by the example themselves (though marked as commented out for QuickBook), deliver
      an SVG file which can be manually converted to a PNG (I'm using InkScape for
      that which is quite convenient).

Copyright © 2009-2021 Barend Gehrels,
      Bruno Lalande, Mateusz Loskot, Adam Wulkiewicz, Oracle and/or its affiliates

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
from __future__ import division

import collections
import importlib

import networkx as nx
import numpy as np
PI = np.pi

from neurokernel.pattern import Pattern

from .geometry.opticaxis import opticaxisFactory, RuleHexArrayMap, OpticAxisRule

def divceil(x, y):
    return (x+y-1)//y

class Ommatidium(object):
    def __init__(self, element):
        '''
            element: ArrayElement object
        '''
        elev, azim = element.dima, element.dimb
        self._elev = elev
        self._azim = azim
        self.element = element

        # maybe simple dic is sufficient
        self.neurons = collections.OrderedDict()

    def add_neuron(self, neuron):
        if neuron.name not in self.neurons:
            self.neurons[neuron.name] = neuron

    def get_neighborid(self, neighbor_dr):
        return self.element.get_neighborid(neighbor_dr)

    @property
    def is_dummy(self):
        return self.element.is_dummy

    @property
    def sphere_pos(self):
        return self._elev, self._azim

    @property
    def gid(self):
        return self.element.gid

    @property
    def photoreceptor_num(self):
        return sum(n.is_photoreceptor
                   for n in self.neurons.values())

    @property
    def neuron_num(self):
        return len(self.neurons)

class RetinaArray(object):
    def __init__(self, hex_array, config, gen_graph = True):
        self.hex_array = hex_array

        modelname = config['Retina']['model']
        #try:
        #    self.model = importlib.import_module('vision_models.{}'
        #                                         .format(modelname))
        #except ImportError:
        self.model = importlib.import_module('retina.vision_models.{}'
                                                 .format(modelname))

        self.opticaxis = opticaxisFactory('SuperpositionLT')()
        self.rulemap = RuleHexArrayMap(self.opticaxis, hex_array)

        self._set_elements()
        self._update_neurons()

        # in degrees
        self.interommatidial_angle = self._get_interommatidial_angle()

        # in degrees
        acc_factor = config['Retina']['acceptance_factor']
        self.acceptance_angle = self.interommatidial_angle * acc_factor

        if gen_graph:
            self._generate_graph()

    def _set_elements(self):
        self._ommatidia = [Ommatidium(el)
                           for el in self.hex_array.elements]

    def _update_neurons(self):
        for omm in self._ommatidia:
            for neuron_params in self.model.OMMATIDIA_NEURON_LIST:
                self._add_photoreceptor(omm, neuron_params)

    def _add_photoreceptor(self, ommatidium, neuron_params):
        nid = self.opticaxis.name_to_ind(neuron_params['name'])
        neighbordr = self.opticaxis.neighbor_for_photor(nid)
        neighborid = ommatidium.get_neighborid(neighbordr)

        # position on sphere coincides with the
        # surface normal and the desired direction
        direction = self._ommatidia[neighborid].sphere_pos
        photor = OmmatidiumNeuron(ommatidium, direction, neuron_params)
        ommatidium.add_neuron(photor)

    def _add_fb_neuron(self, ommatidium, neuron_params):
        neuron = OmmatidiumNeuron(ommatidium, None, neuron_params,
                                  is_photoreceptor=False)
        ommatidium.add_neuron(neuron)

    def _get_interommatidial_angle(self):
        ''' Returns angle in degrees '''
        elev1, azim1 = self._ommatidia[0].sphere_pos
        try:
            elev2, azim2 = self._ommatidia[1].sphere_pos
        except IndexError:
            # when there is only one element
            # assume interommatidial angle is 90
            return 90

        x1 = np.sin(elev1)*np.cos(azim1)
        y1 = np.sin(elev1)*np.sin(azim1)
        z1 = np.cos(elev1)
        x2 = np.sin(elev2)*np.cos(azim2)
        y2 = np.sin(elev2)*np.sin(azim2)
        z2 = np.cos(elev2)
        angle = np.arccos(x1*x2 + y1*y2 + z1*z2)
        return float(angle*180/np.pi)

    def get_all_photoreceptors(self):
        return [photor for ommatidium in self._ommatidia
                for photor in ommatidium.neurons.values()
                if photor.name in ['R1', 'R2', 'R3', 'R4', 'R5', 'R6']]

    def get_angle(self):
        return self.acceptance_angle

    def get_all_photoreceptors_dir(self):
        allphotors = self.get_all_photoreceptors()
        elevazim = np.array([photor.sphere_pos for photor in allphotors])
        dirs = np.array([photor.direction for photor in allphotors])

        return elevazim[:, 0], elevazim[:, 1], dirs[:, 0], dirs[:, 1]

    def get_ommatidia_pos(self):
        positions = np.array([omm.sphere_pos for omm in self._ommatidia])
        return positions[:, 0], positions[:, 1]

    def generate_neuroarch_gexf(self, G_lamina = None):
        G_neuroarch = nx.MultiDiGraph()
        hex_loc = self.hex_array.hex_loc

        for i, omm in enumerate(self._ommatidia):
            sphere_pos = omm.sphere_pos
            hx_loc = hex_loc[i]
            circuit_name = 'ommatidium_{}'.format(i)

            G_neuroarch.add_node('circuit_'+ circuit_name,
                                 **{'name': 'Ommatidium',
                                  'elev_3d': float(sphere_pos[0]),
                                  'azim_3d': float(sphere_pos[1]),
                                  'x_2d': float(hx_loc[0]),
                                  'y_2d': float(hx_loc[1])})

            for name, neuron in omm.neurons.items():
                direction = neuron.direction
                neuron.id = 'neuron_{}_{}'.format(name, i)
                G_neuroarch.add_node(neuron.id, **neuron.params.copy())
                G_neuroarch.node[neuron.id].update(
                    {'name': name,
                     'elev_3d': float(sphere_pos[0]),
                     'azim_3d': float(sphere_pos[1]),
                     'x_2d': float(hx_loc[0]),
                     'y_2d': float(hx_loc[1]),
                     'genetic.neurotransmitter': 'histamine',
                     'optic_axis_elev': float(direction[0]),
                     'optic_axis_azim': float(direction[1]),
                     'circuit': circuit_name,
                     'acceptance_angle': self.get_angle()})
                G_neuroarch.add_node(
                    neuron.id+'_port',
                    **{'class': 'Port', 'name': name,
                     'port_type': 'gpot', 'port_io': 'out',
                     'circuit': circuit_name,
                     'selector': '/ret/{}/{}'.format(i, name)})
                G_neuroarch.add_edge(neuron.id, neuron.id+'_port')
                G_neuroarch.add_node(
                    neuron.id+'_aggregator_port',
                    **{'class': 'Port', 'name': name,
                     'port_type': 'gpot', 'port_io': 'in',
                     'circuit': circuit_name,
                     'selector': '/ret/{}/{}_agg'.format(i,name)})
                G_neuroarch.add_edge(neuron.id+'_aggregator_port', neuron.id,
                                     variable = 'I')

        return G_neuroarch

    def _generate_graph(self):
        G_master = nx.DiGraph()
        G_workers = nx.DiGraph()
        G_workers_nomaster = nx.DiGraph()

        self.worker_comp_list = []

        num_photoreceptors = self.num_photoreceptors

        num_w1 = 0  # workers no master counter
        num_w2 = 0  # workers counter
        num_m = 0

        for i, omm in enumerate(self._ommatidia):
            for name, neuron in omm.neurons.items():
                neuron.id = 'neuron_{}_{}'.format(name, i)
                G_workers_nomaster.add_node(neuron.id, **neuron.params.copy())
                G_workers_nomaster.add_node(
                    neuron.id+'_port',
                    **{'class': 'Port', 'name': name,
                     'port_type': 'gpot', 'port_io': 'out',
                    'selector': '/ret/{}/{}'.format(i, name)})
                G_workers_nomaster.add_node(
                        neuron.id+'_photon',
                        **{'class': 'BufferPhoton',
                        'name': '{}_buf'.format(name)
                    })
                G_workers_nomaster.add_edge(neuron.id, neuron.id+'_port')
                G_workers_nomaster.add_edge(neuron.id+'_photon', neuron.id)
                G_workers_nomaster.add_node(
                    neuron.id+'_aggregator_port',
                    **{'class': 'Port',
                     'name': name,
                     'port_type': 'gpot',
                     'port_io': 'in',
                     'selector': '/ret/{}/{}_agg'.format(i,name)})
                G_workers_nomaster.add_edge(neuron.id+'_aggregator_port',
                                            neuron.id, variable = 'I')
                num_w1 += 1

                if OpticAxisRule.is_photor(name):
                    ind = OpticAxisRule.name_to_ind(name)
                    G_workers.add_node(neuron.id, **neuron.params.copy())

                    self.worker_comp_list.append(neuron.id)
                    G_workers.add_node(neuron.id+'_in', **{
                        'class': 'Port',
                        'name': name,
                        'port_type': 'gpot',
                        'port_io': 'in',
                        'selector': '/retina_worker/{}/in_R{}'.format(i, ind)
                    })
                    G_workers.add_node(neuron.id+'_out', **{
                        'class': 'Port',
                        'name': name,
                        'port_type': 'gpot',
                        'port_io': 'out',
                        'selector': '/retina_worker/{}/out_R{}'.format(i, ind)
                    })
                    G_workers.add_edge(neuron.id+'_in',
                                       neuron.id)
                    G_workers.add_edge(neuron.id,
                                       neuron.id+'_out')
                    G_workers.add_node(neuron.id+'_aggregator_port', **{
                        'class': 'Port',
                        'name': name,
                        'port_type': 'gpot',
                        'port_io': 'in',
                        'selector': '/retina_worker/{}/agg_R{}'.format(i, ind)
                    })
                    G_workers.add_edge(neuron.id+'_aggregator_port',
                                       neuron.id, variable = 'I')

                    num_w2 += 1

                    G_master.add_node(neuron.id+'_photon', **{
                        'class': 'BufferPhoton',
                        'name': 'buf{}'.format(ind)
                    })
                    G_master.add_node(neuron.id+'_buff_in',**{
                        'class': 'Port',
                        'port_type': 'gpot',
                        'port_io': 'in',
                        'name': 'collect_{}'.format(name),
                        'selector': '/retina_master/{}/in_R{}'.format(i, ind)
                    })
                    G_master.add_node(neuron.id+'_photon_out', **{
                        'class': 'Port',
                        'port_type': 'gpot',
                        'port_io': 'out',
                        'name': 'port_buf_{}'.format(name),
                        'selector': '/retina_master/{}/buf_R{}'.format(i, ind)
                    })
                    G_master.add_node(neuron.id, **{
                        'class': 'BufferVoltage',
                        'name': 'buf_voltage_{}'.format(name)
                    })
                    G_master.add_node(neuron.id+'_out', **{
                        'class': 'Port',
                        'port_type': 'gpot',
                        'port_io': 'out',
                        'name': name,
                        'selector': '/ret/{}/R{}'.format(i, ind)
                    })
                    G_master.add_edge(neuron.id+'_photon', neuron.id+'_photon_out')
                    G_master.add_edge(neuron.id+'_buff_in', neuron.id)
                    G_master.add_edge(neuron.id, neuron.id+'_out')

                    G_master.add_node(neuron.id+'_aggregator_out', **{
                        'class': 'Port',
                        'port_type': 'gpot',
                        'port_io': 'out',
                        'name': name,
                        'selector': '/retina_master/{}/agg_R{}'.format(i, ind)
                    })
                    G_master.add_node(neuron.id+'_aggregator_in', **{
                        'class': 'Port',
                        'port_type': 'gpot',
                        'port_io': 'in',
                        'name': name,
                        'selector': '/ret/{}/R{}_agg'.format(i, ind)
                    })
                    G_master.add_node(neuron.id+'_buff_current', **{
                        'class': 'BufferCurrent',
                        'name': 'buff_current_'+name,
                    })
                    G_master.add_edge(neuron.id+'_aggregator_in',
                                      neuron.id+'buff_current',
                                      variable = 'I')
                    G_master.add_edge(neuron.id+'_buff_current',
                                      neuron.id+'aggregator_out',
                                      variable = 'I')

                    num_m += 1

        self.G_master = G_master
        self.G_workers = G_workers
        self.G_workers_nomaster = G_workers_nomaster

    def get_worker_nomaster_graph(self, *args):
        try:
            return self.G_workers_nomaster.subgraph(self.get_nodes(*args))
        except TypeError:
            return self.G_workers_nomaster

    def get_worker_graph(self, *args):
        try:
            nodes = self.get_worker_nodes_id(*args)
            nodes += [i + '_in' for i in nodes]
            nodes += [i + '_aggregator_port' for i in nodes]
            return self.G_workers.subgraph(nodes)
        except TypeError:
            return self.G_workers

    def get_master_graph(self):
        return self.G_master

    def update_pattern_master_worker(self, j, worker_num):
        indexes = self.get_worker_nodes(j, worker_num)

        master_selectors = self.get_master_selectors()
        worker_selectors = self.get_worker_selectors(j, worker_num)

        from_list = []
        to_list = []

        for i, ind in enumerate(indexes):
            col_m = ind // 6
            ind_m = 1 + (ind % 6)
            src = '/retina_master/{}/buf_R{}'.format(col_m, ind_m)
            dest = '/retina_worker/{}/in_R{}'.format(col_m, ind_m)
            from_list.append(src)
            to_list.append(dest)

            src = '/retina_worker/{}/out_R{}'.format(col_m, ind_m)
            dest = '/retina_master/{}/in_R{}'.format(col_m, ind_m)
            from_list.append(src)
            to_list.append(dest)

            src = '/retina_master/{}/agg_R{}'.format(col_m, ind_m)
            dest = '/retina_worker/{}/agg_R{}'.format(col_m, ind_m)
            from_list.append(src)
            to_list.append(dest)

        pattern = Pattern.from_concat(','.join(master_selectors),
                                      ','.join(worker_selectors),
                                      from_sel = ','.join(from_list),
                                      to_sel = ','.join(to_list),
                                      gpot_sel = ','.join(from_list+to_list))
        return pattern

    # Neuron representation
    def get_neurons(self, j, sublpu_num):
        # numbering starts from 1
        ommatidia = self._ommatidia
        ommatidia_num = len(ommatidia)
        start = divceil((j-1)*ommatidia_num, sublpu_num)
        end = divceil(j*ommatidia_num, sublpu_num)
        neurons = []
        # implicit assumption i is the same as
        # the global id of
        for i in range(start, end):
            ommatidium = ommatidia[i]
            for omm_neuron in ommatidium.neurons.values():
                neurons.append((ommatidium.gid,
                                omm_neuron.name,
                                ommatidium.sphere_pos))
        return neurons

    # Numeric order representation
    def get_interval(self, j, sublpu_num):
        '''
            Returns jth interval out of `sublpu_num`.
            Numbering starts from 1.
            Outputs are multiple of neuron_types.
            End index of last interval might be greater
            but not less than the number of photoreceptors.
            Indexes match positions returned by
            `get_all_photoreceptors`
        '''
        ommatidia_num = self.num_elements
        start = self.neuron_types*divceil((j-1)*ommatidia_num, sublpu_num)
        end = self.neuron_types*divceil(j*ommatidia_num, sublpu_num)
        return start, end

    def get_worker_interval(self, j, sublpu_num):
        '''
            Returns jth interval out of `sublpu_num`.
            Numbering starts from 1.
            Outputs are multiple of photoreceptor_types.
            End index of last interval might be greater
            but not less than the number of photoreceptors.
            Indexes match positions returned by
            `get_all_photoreceptors`
        '''
        ommatidia_num = self.num_elements
        start = self.photoreceptor_types*divceil((j-1)*ommatidia_num,
                                                 sublpu_num)
        end = self.photoreceptor_types*divceil(j*ommatidia_num, sublpu_num)
        return start, end

    # Node key representation
    def get_nodes(self, j, sublpu_num):
        # numbering starts from 1
        return list(range(*self.get_interval(j, sublpu_num)))

    def get_worker_nodes(self, j, sublpu_num):
        # numbering starts from 1
        return list(range(*self.get_worker_interval(j, sublpu_num)))

    def get_worker_nodes_id(self, j, sublpu_num):
        # numbering starts from 1
        return self.worker_comp_list(range(*self.get_worker_interval(j, sublpu_num)))

    # Selector representation
    def get_selectors(self, j, sublpu_num):
        # numbering starts from 1
        selectors = []
        for n in self.get_neurons(j, sublpu_num):
            n_id, n_name, _ = n
            selectors.append('/ret/{}/{}'.format(n_id, n_name))
            selectors.append('/ret/{}/{}_agg'.format(n_id, n_name))
        return selectors

    # Selector representation (all)
    def get_all_selectors(self):
        # Get interval as if there is 1 LPU
        # so get all nodes
        return self.get_selectors(1, 1)

    def get_master_selectors(self):
        selectors = []
        for i in self.get_worker_nodes(1, 1):
            col = i // 6
            ind = 1 + (i % 6)
            selectors.append('/retina_master/{}/buf{}'.format(col, ind))
            selectors.append('/retina_master/{}/in{}'.format(col, ind))
            selectors.append('/ret/{}/R{}'.format(col, ind))

        return selectors

    def get_worker_selectors(self, j, workernum):
        selectors = []
        for i in self.get_worker_nodes(j, workernum):
            col = i // 6
            ind = 1 + (i % 6)
            selectors.append('/retina_worker/{}/in{}'.format(col, ind))
            selectors.append('/retina_worker/{}/out{}'.format(col, ind))

        return selectors

    # A convenient representation of all neuron information
    def get_neuron_objects(self):
        return self._ommatidia

    def get_neighborid(self, oid, neighbor_dr):
        ''' Get id of neighbor of `oid` ommatidium in a
            specific direction
        '''
        return self._ommatidia[oid].get_neighborid(neighbor_dr)

    def index(self, ommid, name):
        return self._ommatidia[ommid].neurons.keys().index(name)

    @property
    def num_neurons(self):
        return self.neuron_types*self.num_elements

    @property
    def num_photoreceptors(self):
        return self.photoreceptor_types*self.num_elements

    @property
    def num_elements(self):
        return self.hex_array.num_elements

    @property
    def neuron_types(self):
        return self._ommatidia[0].neuron_num

    @property
    def photoreceptor_types(self):
        return self._ommatidia[0].photoreceptor_num

    @property
    def radius(self):
        return self.hex_array.radius

class Neuron(object):
    def __init__(self, params):
        self.name = params.get('name')

        self.params = params.copy()
        self.num = None

        self.outgoing_synapses = []
        self.incoming_synapses = []

    def add_outgoing_synapse(self, synapse):
        self.outgoing_synapses.append(synapse)

    def add_incoming_synapse(self, synapse):
        self.incoming_synapses.append(synapse)

    def remove_outgoing_synapse(self, synapse):
        self.outgoing_synapses.remove(synapse)

    def remove_incoming_synapse(self, synapse):
        self.incoming_synapses.remove(synapse)

    def __repr__(self):
        return 'neuron {}: {}'.format(self.params['name'], self.params)

    def __str__(self):
        return 'neuron {}'.format(self.params['name'])

class OmmatidiumNeuron(Neuron):
    def __init__(self, ommatidium, direction, params, is_photoreceptor=True):
        '''
            ommatidium: ommatidium object
            direction: tuple of 2 coordinates (elevation, azimuth) or None
                       direction of photoreceptor optical axis
        '''
        self.parent = ommatidium
        self.direction = direction
        self._is_photoreceptor = is_photoreceptor

        super(OmmatidiumNeuron, self).__init__(params)

    @property
    def sphere_pos(self):
        return self.parent.sphere_pos
    @property
    def is_photoreceptor(self):
        return self._is_photoreceptor

class Synapse(object):
    def __init__(self, params):
        """ params: a dictionary of neuron parameters.
                    It can be passed as an attribute dictionary parameter
                    for a node in networkx library.
        """
        self._params = params.copy()

    def link(self, pre_neuron, post_neuron):
        self.pre_neuron = pre_neuron
        self.post_neuron = post_neuron
        self.pre_neuron.add_outgoing_synapse(self)
        self.post_neuron.add_incoming_synapse(self)

    def __repr__(self):
        return 'synapse from {} to {}: {}'.format(self.params['prename'],
                                                  self.params['postname'],
                                                  self.params)

    def __str__(self):
        return 'synapse from {} to {}'.format(self.params['prename'],
                                              self.params['postname'])

    @property
    def prenum(self):
        return self._prenum

    @prenum.setter
    def prenum(self, value):
        self._prenum = value

    @property
    def postnum(self):
        return self._postnum

    @postnum.setter
    def postnum(self, value):
        self._postnum = value

    @property
    def params(self):
        return self._params

    def process_before_export(self):
        # assumes all conductances are gpot to gpot
        self._params.update({'class': 3})
        self._params.update({'conductance': True})
        if 'cart' in self._params.keys():
            del self._params['cart']
        if 'scale' in self.params.keys():
            self._params['slope'] *= self._params['scale']
            self._params['saturation'] *= self._params['scale']
            del self._params['scale']

def main():

    from retina.screen.map.mapimpl import AlbersProjectionMap
    import retina.geometry.hexagon as hex
    from retina.configreader import ConfigReader
    import retina.retina as ret
    import networkx as nx
    config=ConfigReader('retlam_default.cfg','../template_spec.cfg').conf
    transform = AlbersProjectionMap(config['Retina']['radius'],config['Retina']['eulerangles']).invmap
    hexarray = hex.HexagonArray(num_rings = 14, radius = config['Retina']['radius'], transform = transform)
    a = ret.RetinaArray(hexarray, config)
    G = a.generate_neuroarch_gexf()
    nx.write_gexf(G, 'retina_neuroarch.gexf.gz')

if __name__ == "__main__":
    main()


text:
On Debian it is quite easy to add a user to the **sudoers** group.

```bash
$ su -
$ adduser <existing userid> sudo
```

## References

- [Debian Wiki](https://wiki.debian.org/sudo)


text:
#ifndef __TIMER_H__
#define __TIMER_H__

#ifdef __cplusplus
extern "C" {
#endif

#include <rbtree_augmented.h>
#include <clockevent/clockevent.h>
#include <xboot/ktime.h>

struct timer_base_t;
struct timer_t;

enum timer_state_t {
	TIMER_STATE_INACTIVE = 0,
	TIMER_STATE_ENQUEUED = 1,
	TIMER_STATE_CALLBACK = 2,
};

struct timer_base_t {
	struct rb_root head;
	struct timer_t * next;
	struct clockevent_t * ce;
	spinlock_t lock;
};

struct timer_t {
	struct rb_node node;
	struct timer_base_t * base;
	enum timer_state_t state;
	ktime_t expires;
	void * data;
	int (*function)(struct timer_t *, void *);
};

void timer_init(struct timer_t * timer, int (*function)(struct timer_t *, void *), void * data);
void timer_start(struct timer_t * timer, ktime_t interval);
void timer_forward(struct timer_t * timer, ktime_t interval);
void timer_cancel(struct timer_t * timer);

void timer_bind_clockevent(struct clockevent_t * ce);

#ifdef __cplusplus
}
#endif

#endif /* __TIMER_H__ */


text:
@implementation Account

@synthesize sessionId = _sessionId;
@synthesize password = _password;
@synthesize preference = _preference;
@synthesize profileImageUrl = _profileImageUrl;

- (id)init {
    self = [super init];
    if (self) {
        return self;
    }
    return self;
}

- (id)initWithData:(NSDictionary*)dict {
    self = [super initWithData:dict];

    self.sessionId = [dict valueForKey:ACCT_SESSION_ID];

    return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        // Decode properties
        self.sessionId = [decoder decodeObjectForKey:@"sessionId"];
        self.userId = [[decoder decodeObjectForKey:@"userId"] intValue];
        self.email = [decoder decodeObjectForKey:@"email"];
        self.userName = [decoder decodeObjectForKey:@"userName"];
        self.firstName = [decoder decodeObjectForKey:@"firstName"];
        self.lastName = [decoder decodeObjectForKey:@"lastName"];
        self.padHost = [decoder decodeObjectForKey:@"padHost"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    // Encode properties
    [encoder encodeObject:self.sessionId forKey:@"sessionId"];
    [encoder encodeObject:[NSNumber numberWithInt:self.userId] forKey:@"userId"];
    [encoder encodeObject:self.email forKey:@"email"];
    [encoder encodeObject:self.userName forKey:@"userName"];
    [encoder encodeObject:self.firstName forKey:@"firstName"];
    [encoder encodeObject:self.lastName forKey:@"lastName"];
    [encoder encodeObject:self.padHost forKey:@"padHost"];
}

- (id)copyWithZone:(NSZone*)zone {
    Account *acct = [[Account alloc] init];

    if (self.sessionId != nil) {
        acct.sessionId = [self.sessionId copy];
    }

    acct.userId = self.userId;

    if (self.email.length > 0) {
        acct.email = [self.email copy];
    }

    if (self.userName.length > 0) {
        acct.userName = [self.userName copy];
    }

    if (self.firstName.length > 0) {
        acct.firstName = [self.firstName copy];
    }

    if (self.lastName.length > 0) {
        acct.lastName = [self.lastName copy];
    }

    if (self.padHost != nil) {
        acct.padHost = [self.padHost copy];
    }

    return acct;
}

- (BOOL)isLoggedIn
{
    if (self.sessionId != nil)
        return YES;
    return NO;
}

- (NSString*)profileImageUrlForEditing {
    if (_profileImageUrl.length > 0) {
        return _profileImageUrl;
    }
    return nil;
}

- (void)setTimezoneStr:(NSString *)timezoneStr {
    if (_preference == nil) {
        _preference = [[UserPreference alloc] init];
    }
    _preference.timezoneStr = timezoneStr;
}

- (void)setLocaleStr:(NSString*)localeStr {
    if (_preference == nil) {
        _preference = [[UserPreference alloc] init];
    }
    _preference.localeStr = localeStr;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"userId:%i userName:%@ email:%@ sessionId:%@ padhost:%@",
                                        self.userId,
                                        self.userName,
                                        self.email==nil?@"":self.email,
                                        self.sessionId==nil?@"":self.sessionId,
                                        self.padHost==nil?@"":self.padHost];
}
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/MDB.iml" filepath="$PROJECT_DIR$/MDB.iml" />
      <module fileurl="file://$PROJECT_DIR$/MDBancomer.iml" filepath="$PROJECT_DIR$/MDBancomer.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
    </modules>
  </component>
</project>


text:
package com.comcast.tvx.haproxy;

/*
 * Encapsulates this:
 * server server1 127.0.0.1:81 check
 */
public class HABackendServer extends HARenderer {

    private Integer port;
    private Boolean healthCheck;
    private String ipAddress;
    private String protocol;

    public HABackendServer(String ipAddress, Integer port, Boolean healthCheck, String protocol) {
        super();
        this.ipAddress = ipAddress;
        this.port = port;
        this.healthCheck = healthCheck;
        this.protocol = protocol;
    }

    public String toString() {
        // acl is_80 path_beg -i /healthCheck/80
        StringBuilder result = new StringBuilder().append(" server ").append(makeName(ipAddress)).append(" ")
                .append(ipAddress + ":" + port.toString());
        // hack... if xre server, DON'T specify check interval, it won't work
        if (!getProtocol().equalsIgnoreCase("xre"))
            result.append(" check inter 5000");
        return result.toString();
    }

    private String getProtocol() {

        return (protocol == null) ? "tcp" : protocol;
    }

    private String makeName(String networkName) {
        return networkName.replace('.', '_');
    }

    @Override
    public int compareTo(HAConfigurationSection o) {
        if (!(o instanceof HABackendServer))
            return 1;
        HABackendServer other = (HABackendServer) o;

        if (other.healthCheck != this.healthCheck)
            return -1;
        if (other.port != this.port)
            return -1;
        if (!other.ipAddress.equalsIgnoreCase(this.ipAddress))
            return -1;

        return 0;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PronoFoot.Data.Model;

namespace PronoFoot.Business.Models
{
    public class CompetitionModel
    {
        public int CompetitionId { get; set; }
        public string Name { get; set; }
        public bool HasTeamClassification { get; set; }

        public CompetitionModel()
        {
        }

        public CompetitionModel(Competition competition)
        {
            this.CompetitionId = competition.CompetitionId;
            this.Name = competition.Name;
            this.HasTeamClassification = competition.HasTeamClassification;
        }
    }
}


text:
import { Users, Followings } from '../../models';
import { ILocalUser, IRemoteUser } from '../../models/entities/user';
import { deliver } from '../../queue';

//#region types
interface IRecipe {
	type: string;
}

interface IFollowersRecipe extends IRecipe {
	type: 'Followers';
}

interface IDirectRecipe extends IRecipe {
	type: 'Direct';
	to: IRemoteUser;
}

const isFollowers = (recipe: any): recipe is IFollowersRecipe =>
	recipe.type === 'Followers';

const isDirect = (recipe: any): recipe is IDirectRecipe =>
	recipe.type === 'Direct';
//#endregion

export default class DeliverManager {
	private actor: ILocalUser;
	private activity: any;
	private recipes: IRecipe[] = [];

	/**
	 * Constructor
	 * @param actor Actor
	 * @param activity Activity to deliver
	 */
	constructor(actor: ILocalUser, activity: any) {
		this.actor = actor;
		this.activity = activity;
	}

	/**
	 * Add recipe for followers deliver
	 */
	public addFollowersRecipe() {
		const deliver = {
			type: 'Followers'
		} as IFollowersRecipe;

		this.addRecipe(deliver);
	}

	/**
	 * Add recipe for direct deliver
	 * @param to To
	 */
	public addDirectRecipe(to: IRemoteUser) {
		const recipe = {
			type: 'Direct',
			to
		} as IDirectRecipe;

		this.addRecipe(recipe);
	}

	/**
	 * Add recipe
	 * @param recipe Recipe
	 */
	public addRecipe(recipe: IRecipe) {
		this.recipes.push(recipe);
	}

	/**
	 * Execute delivers
	 */
	public async execute() {
		if (!Users.isLocalUser(this.actor)) return;

		const inboxes: string[] = [];

		// build inbox list
		for (const recipe of this.recipes) {
			if (isFollowers(recipe)) {
				// followers deliver
				const followers = await Followings.find({
					followeeId: this.actor.id
				});

				for (const following of followers) {
					if (Followings.isRemoteFollower(following)) {
						const inbox = following.followerSharedInbox || following.followerInbox;
						if (!inboxes.includes(inbox)) inboxes.push(inbox);
					}
				}
			} else if (isDirect(recipe)) {
				// direct deliver
				const inbox = recipe.to.inbox;
				if (inbox && !inboxes.includes(inbox)) inboxes.push(inbox);
			}
		}

		// deliver
		for (const inbox of inboxes) {
			deliver(this.actor, this.activity, inbox);
		}
	}
}

//#region Utilities
/**
 * Deliver activity to followers
 * @param activity Activity
 * @param from Followee
 */
export async function deliverToFollowers(actor: ILocalUser, activity: any) {
	const manager = new DeliverManager(actor, activity);
	manager.addFollowersRecipe();
	await manager.execute();
}

/**
 * Deliver activity to user
 * @param activity Activity
 * @param to Target user
 */
export async function deliverToUser(actor: ILocalUser, activity: any, to: IRemoteUser) {
	const manager = new DeliverManager(actor, activity);
	manager.addDirectRecipe(to);
	await manager.execute();
}
//#endregion


text:
import assert from 'assert';
import { Recurly } from '../../lib/recurly';
import { apiTest, initRecurly } from './support/helpers';

apiTest((requestMethod) => {
  describe(`Recurly.item (${requestMethod})`, () => {
    beforeEach(function () {
      this.sandbox = sinon.createSandbox();
      this.recurly = initRecurly({ cors: requestMethod === 'cors' });
      this.valid = { itemCode: 'basic-item' };
      this.invalid = { itemCode: 'invalid' };
    });

    it('requires an itemCode', function () {
      const { recurly } = this;
      assert.throws(() => recurly.item(), 'Option itemCode must be a String');
    });

    it('requires Recurly.configure', function (done) {
      const { sandbox, valid } = this;
      const recurly = new Recurly();
      const stub = sandbox.stub();
      recurly.item(valid)
        .then(stub)
        .catch(err => {
          assert(stub.notCalled);
          assert.strictEqual(err.code, 'not-configured');
          done();
        });
    });

    describe('when given an invalid itemCode', function () {
      it('rejects with an error', function (done) {
        const { invalid, recurly, sandbox } = this;
        const stub = sandbox.stub();
        recurly.item(invalid)
          .then(stub)
          .catch(err => {
            assert(stub.notCalled);
            assert.strictEqual(err.code, 'not-found');
            assert.strictEqual(err.message, "Couldn't find Item with item_code=invalid");
            done();
          });
      });
    });

    describe('when given a valid itemCode', function () {
      it('resolves with an item', function (done) {
        const { recurly, sandbox, valid } = this;
        const stub = sandbox.stub();
        recurly.item(valid)
          .catch(stub)
          .then(item => {
            assert(stub.notCalled);
            assert.strictEqual(item.code, 'basic-item');
            assert.strictEqual(item.name, 'Basic Item');
            assert.strictEqual(item.tax_code, null);
            assert.strictEqual(item.tax_exempt, true);
            assert(Array.isArray(item.currencies));
            assert.strictEqual(item.currencies.length, 2);
            assert.strictEqual(item.currencies[0].currency_code, 'CAD');
            assert.strictEqual(item.currencies[0].currency_symbol, '$');
            assert.strictEqual(item.currencies[0].unit_amount, 60.0);
            assert.strictEqual(item.currencies[1].currency_code, 'USD');
            assert.strictEqual(item.currencies[1].currency_symbol, '$');
            assert.strictEqual(item.currencies[1].unit_amount, 40.0);
            done();
          });
      });
    });
  });
});