text:
from __future__ import unicode_literals
import os
import re
from django.conf import settings
from django.db import transaction

from docutil.progress_monitor import CLIProgressMonitor
from docutil.commands_util import mkdir_safe, dump_model, load_model,\
    import_clazz
from project.models import ProjectRelease
from project.actions import DOC_PATH
from codebase.models import CodeBase, CodeBaseDiff
from recommender.models import CodePattern, CodePatternCoverage
from recommender.parser.pattern_coverage import compute_coverage
from doc.models import DocumentStatus, Document, Page, Section, DocDiff
from doc.parser.generic_parser import parse
from doc.parser.doc_diff import DocDiffer, DocLinkerDiffer

def get_doc_path(pname, dname=None, release=None, root=False):
    if root:
        doc_key = ''
    else:
        doc_key = dname + release
    basepath = settings.PROJECT_FS_ROOT
    doc_path = os.path.join(basepath, pname, DOC_PATH, doc_key)
    return doc_path

def create_doc_local(pname, dname, release, syncer, input_url=None):
    doc_key = dname + release
    doc_path = get_doc_path(pname, dname, release)
    mkdir_safe(doc_path)

    model = DocumentStatus(syncer=syncer, input_url=input_url)
    dump_model(model, pname, DOC_PATH, doc_key)

def create_doc_db(pname, dname, release, url, syncer, parser):
    prelease = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release)[0]
    document = Document(title=dname, project_release=prelease, url=url,
            parser=parser, syncer=syncer)
    document.save()
    return document

def list_doc_db(pname):
    docs = []
    for doc in Document.objects.filter(
            project_release__project__dir_name=pname):
        docs.append('{0}: {1} ({2})'.format(doc.pk, doc.title, doc.url))
    return docs

def list_doc_local(pname):
    doc_path = get_doc_path(pname, root=True)
    local_docs = []
    for member in os.listdir(doc_path):
        if os.path.isdir(os.path.join(doc_path, member)):
            local_docs.append(member)
    return local_docs

def sync_doc(pname, dname, release):
    doc_key = dname + release
    doc_path = get_doc_path(pname, dname, release)
    model = load_model(pname, DOC_PATH, doc_key)
    syncer = import_clazz(model.syncer)(model.input_url, doc_path)
    pages = syncer.sync()
    model.pages = pages
    dump_model(model, pname, DOC_PATH, doc_key)

def clear_doc_elements(pname, dname, release):
    prelease = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release)[0]
    document = Document.objects.filter(project_release=prelease).\
            filter(title=dname)[0]
    query = Section.objects.filter(page__document=document)
    print('Deleting %i sections' % query.count())
    for section in query.all():
        section.code_references.all().delete()
        section.code_snippets.all().delete()
        section.delete()
    Page.objects.filter(document=document).delete()

@transaction.autocommit
def parse_doc(pname, dname, release, parse_refs=True):
    prelease = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release)[0]
    document = Document.objects.filter(project_release=prelease).\
            filter(title=dname)[0]
    doc_key = dname + release
    model = load_model(pname, DOC_PATH, doc_key)
    progress_monitor = CLIProgressMonitor()
    parse(document, model.pages, parse_refs, progress_monitor)

    return document

@transaction.autocommit
def diff_doc(pname, dname, release1, release2):
    prelease1 = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release1)[0]
    document_from = Document.objects.filter(project_release=prelease1).\
            filter(title=dname)[0]
    prelease2 = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release2)[0]
    document_to = Document.objects.filter(project_release=prelease2).\
            filter(title=dname)[0]

    differ = DocDiffer()
    return differ.diff_docs(document_from, document_to)

@transaction.autocommit
def diff_links(pname, dname, release1, release2):
    prelease1 = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release1)[0]
    document_from = Document.objects.filter(project_release=prelease1).\
            filter(title=dname)[0]
    prelease2 = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release2)[0]
    document_to = Document.objects.filter(project_release=prelease2).\
            filter(title=dname)[0]
    doc_diff = DocDiff.objects.filter(document_from=document_from).\
            get(document_to=document_to)
    doc_linker_differ = DocLinkerDiffer(doc_diff)
    (added_links, removed_links) = doc_linker_differ.diff_links()
    print('Added links: {0}'.format(len(added_links)))
    print('Removed links: {0}'.format(len(removed_links)))

def compute_family_coverage(pname, bname, release, dname, srelease):
    prelease = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release)[0]
    codebase = CodeBase.objects.filter(project_release=prelease).\
            filter(name=bname)[0]
    psrelease = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=srelease)[0]
    document = Document.objects.filter(project_release=psrelease).\
            filter(title=dname)[0]
    patterns = CodePattern.objects.filter(codebase=codebase).all()
    progress_monitor = CLIProgressMonitor(min_step=1.0)

    compute_coverage(patterns, 'd', document, progress_monitor)

def clear_pattern_coverage(pname, bname, release, dname, srelease):
    prelease = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release)[0]
    codebase = CodeBase.objects.filter(project_release=prelease).\
            filter(name=bname)[0]
    psrelease = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=srelease)[0]
    document = Document.objects.filter(project_release=psrelease).\
            filter(title=dname)[0]

    query = CodePatternCoverage.objects.\
            filter(resource_object_id=document.pk).\
            filter(pattern__codebase=codebase)

    print('Deleting {0} pattern coverages'.format(query.count()))

    query.delete()

def remove_page(pname, dname, release, url_regex):
    prelease = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release)[0]
    document = Document.objects.filter(project_release=prelease).\
            filter(title=dname)[0]
    pattern = re.compile(url_regex)
    to_delete = []
    for page in document.pages.all():
        if pattern.search(page.url):
            to_delete.append(page)
    for page in to_delete:
        print('Page {0} deleted'.format(page.url))
        page.delete()

    print('{0} pages deleted'.format(len(to_delete)))

def show_new_new_links(pname, bname, dname, release1, release2):
    prelease1 = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release1)[0]
    document_from = Document.objects.filter(project_release=prelease1).\
            filter(title=dname)[0]
    prelease2 = ProjectRelease.objects.filter(project__dir_name=pname).\
            filter(release=release2)[0]
    document_to = Document.objects.filter(project_release=prelease2).\
            filter(title=dname)[0]
    doc_diff = DocDiff.objects.filter(document_from=document_from).\
            get(document_to=document_to)

    codebase1 = CodeBase.objects.filter(project_release=prelease1).\
            filter(name=bname)[0]
    codebase2 = CodeBase.objects.filter(project_release=prelease2).\
            filter(name=bname)[0]
    code_diff = CodeBaseDiff.objects.filter(codebase_from=codebase1).\
            filter(codebase_to=codebase2)[0]

    # We only care about these kinds for now.
    types = set(code_diff.added_types.all())
    methods = set(code_diff.added_methods.all())
    fields = set(code_diff.added_fields.all())
    all_elements = types.union(methods).union(fields)
    links = doc_diff.link_changes.filter(link_from__isnull=True).all()
    print('Total links: {0}'.format(links.count()))
    for link in links:
        code_element = link.link_to.code_element
        container = code_element.containers.all()[0]
        section_title = link.link_to.code_reference.local_context.title
        page_title = link.link_to.code_reference.global_context.title
        if code_element in all_elements:
            print('Link to {0} was added in {1} ({2})'.format(code_element,
                section_title, page_title))
        elif container in types:
            print('Link to {0} was added in {1} ({2}'.format(code_element,
                section_title, page_title))
        #else:
            #print('OLD: Link to {0} was added in {1} ({2}'.format(code_element,
                #section_title, page_title))

# Functions

def show_section(section_pk):
    section = Section.objects.get(pk=section_pk)
    print(section.title)
    print(section.url)
    print(section.word_count)
    print(section.pk)
    count = 0
    for code_reference in section.code_references.all():
        link = code_reference.first_link()
        if link is not None:
            count += 1
            link_str = link.code_element.human_string()
        else:
            link_str = ''
        print('{0};;{1}'.format(code_reference.content, link_str))
    print('Total links: {0}'.format(count))

def show_sectionn(number, release=None):
    section = Section.objects.filter(number=number)
    if release is None:
        pk = section.all()[0].pk
    else:
        pk = \
            section.filter(page__document__project_release__release=release).\
                all()[0].pk
    show_section(pk)


text:
'use strict';

var Game = require('./gamestatus');

module.exports = {
    Game: Game
}

redpajama_set_name: RedPajamaGithub


text: Some examples from several functional libraries in java.


text:
if(!dojo._hasResource["dojox.xmpp.widget.ChatSession"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.xmpp.widget.ChatSession"] = true;
dojo.provide("dojox.xmpp.widget.ChatSession");
dojo.declare("dojox.xmpp.widget.ChatSession",
	[dijit.layout.LayoutContainer, dijit._Templated],
	{
			templateString: dojo.cache("dojox.xmpp.widget", "templates/ChatSession.html", "
\r\n
\r\n
\r\n
<input dojoAttachPoint=\"chatInput\" dojoAttachEvent=\"onkeypress: onKeyPress\" style=\"width: 100%;height: 35px;\" />
\r\n
\r\n"),
			enableSubWidgets: true,
			widgetsInTemplate: true,

			widgetType: "ChatSession",
			chatWith: null,
			instance: null,
			postCreate: function(){
				//console.log("Neato!");
			},

			displayMessage: function(message, type) {
				//console.log("displayMessage", this, message);
				if(message) {
					var name =  message.from ? this.chatWith : "me";
					this.messages.domNode.innerHTML += "" + name + ": " +   message.body + "
";
					this.goToLastMessage();
				}

			},

			goToLastMessage: function() {
				this.messages.domNode.scrollTop = this.messages.domNode.scrollHeight;
			},

			onKeyPress: function(e){
				var key = e.keyCode || e.charCode;
				if ((key == dojo.keys.ENTER) && (this.chatInput.value != "")){
					this.instance.sendMessage({body: this.chatInput.value});
					this.displayMessage( {body: this.chatInput.value}, "out");
					this.chatInput.value = "";
				}
			}
});

}


text:
With this script it is possible to make auth for nginx host via LDAP server.

```
| --------- |    auth   | ----------------- |
|   Nginx   |  <----->  |  LDAP Auth proxy  |
| --------- |           | ----------------- |
      ˄
      |
      ˅
| --------- |
|  Backend  |
| --------- |
```

Implemented using NodeJs according to https://github.com/nginxinc/nginx-ldap-auth solution.
LDAP deamon uses cookie to store encrypted auth data.

## Nginx config

You have to modify your nginx config to add auth request

before

```
proxy_cache_path cache/ keys_zone=auth_cache:10m;

server {
  listen 80 default;
  server_name example.com;

  location / {
    proxy_pass http://your-real-service.com/;
  }
}

```

after:

```
proxy_cache_path cache/ keys_zone=auth_cache:10m;

server {
  listen 80 default;
  server_name example.com;

  location / {
    auth_request /auth-proxy;

    # redirect 401 to login form
    error_page 401 =200 /login;

    proxy_pass http://your-real-service.com/;
  }

  location /login {
    add_header Cache-Control no-cache;
    proxy_pass http://ldap-auth-proxy:8888;
  }

  location /auth-proxy {
    internal;

    proxy_pass http://ldap-auth-proxy:8888;
    proxy_cache auth_cache; # Must match the name in the proxy_cache_path directive above
    proxy_cache_valid 200 10m;

    # LDAP server
    proxy_set_header X-Ldap-URL "ldap://ldap-server:389";
    proxy_set_header X-Ldap-BindDN "cn=admin,dc=example,dc=com";
    proxy_set_header X-Ldap-BindPass "ldapAdminPassword";

    # User DN
    proxy_set_header X-Ldap-BaseDN "ou=users,dc=example,dc=com";

    # Filter By Group (replace TargetGroupName with required group name)
    # proxy_set_header X-Ldap-Group-BaseDN "ou=group,dc=example,dc=com";
    # proxy_set_header X-Ldap-Group-Template "&(memberUid={{dn}})(cn=TargetGroupName)";
    # proxy_set_header X-Ldap-Group-DNProperty "uid";
  }
}
```

## LDAP Auth Proxy server

See index.js for server implementation. To start
```
npm start
```

You also can start LDAP proxy using docker container. Here the example of docker-compose.yml with nginx and proxy containers:

```
version: '2'
services:
  nginx:
    image: nginx
    container_name: nginx-proxy
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - './conf:/etc/nginx/conf.d:ro'
    links:
      - ldap-auth-proxy
    restart: "always"
  ldap-auth-proxy:
    image: stasdemydiuk/nginx-ldap-auth-proxy
    environment:
      - COOKIE_SECRET=YourSecretKey
    restart: "always"
```


text:
cruddly.controller('CreateCtrl', function ($scope, DataSource) {
    $scope.input = '';

    $scope.create = function () {
       var person = $scope.model;
        DataSource.create(person);
        $scope.model = {};
    };
});


text:
<?php
namespace Aikidesk\SDK\Instance;

interface InstanceSdkApiTokensInterface
{

    /**
     * @return \Aikidesk\SDK\Instance\Contracts\ResponseInterface
     */
    public function current();

    /**
     * @param array $scopes
     * @return \Aikidesk\SDK\Instance\Contracts\ResponseInterface
     */
    public function createClientCredentialsToken($scopes = []);

    /**
     * @param string $email
     * @param string $password
     * @param array $scopes
     * @return \Aikidesk\SDK\Instance\Contracts\ResponseInterface
     */
    public function createPasswordFlowToken($email, $password, $scopes = []);

    /**
     * @param string $refreshToken
     * @return \Aikidesk\SDK\Instance\Contracts\ResponseInterface
     */
    public function createRefreshToken($refreshToken);

    /**
     * @param string $access_token
     */
    public function setAccessToken($access_token);

    /**
     * @return string
     */
    public function getAccessToken();

    /**
     * @return null|string
     */
    public function getOauthClientId();

    /**
     * @param null|string $oauthClientId
     */
    public function setOauthClientId($oauthClientId);

    /**
     * @return null|string
     */
    public function getOauthClientSecret();

    /**
     * @param null|string $oauthClientSecret
     */
    public function setOauthClientSecret($oauthClientSecret);
}


text:
#ifndef __itkDistanceMetric_h
#define __itkDistanceMetric_h

#include "itkFunctionBase.h"
#include "itkMeasurementVectorTraits.h"

namespace itk
{
namespace Statistics
{
/** \class DistanceMetric
 * \brief this class declares common interfaces
 * for distance functions.
 *
 * As a function derived from FunctionBase, users use Evaluate method to get
 * result.
 *
 * To use this function users should first set the origin by calling
 * SetOrigin() function, then call Evaluate() method with a point to get the
 * distance between the origin point and the evaluation point.
 *
 * \sa EuclideanSquareDistanceMetric
 * \sa EuclideanDistanceMetric
 * \sa ManhattanDistanceMetric
 *
 * \ingroup ITKStatistics
 */

template< class TVector >
class ITK_EXPORT DistanceMetric:public FunctionBase< TVector, double  >
{
public:
  /** Standard typedefs */
  typedef DistanceMetric                  Self;
  typedef FunctionBase< TVector, double > Superclass;
  typedef SmartPointer< Self >            Pointer;
  typedef SmartPointer< const Self >      ConstPointer;

  /** declare the MeasurementVector type */
  typedef TVector MeasurementVectorType;

  /** declare Measurement vector component type */
  /** Type used to represent the number of components oft he
    MeasurementVectorType */
  typedef unsigned int MeasurementVectorSizeType;

  /** Run-time type information (and related methods). */
  itkTypeMacro(DistanceMetric, FunctionBase);

  typedef Array< double > OriginType;

  /** Sets the origin point that will be used for the single point version
   * Evaluate() function. This function is necessary part of implementing the
   * Evaluate() interface. The argument of SetOrigin() must be of type
   * DistanceMetric::OriginType, which in most cases will be different from the
   * TVector type. This is necessary because often times the origin would be a
   * mean, or a vector representative of a collection of vectors. */
  void SetOrigin(const OriginType & x);

  itkGetConstReferenceMacro(Origin, OriginType);

  /** Gets the distance between the origin point and x. This function
   * work with SetOrigin() function. */
  virtual double Evaluate(const MeasurementVectorType & x) const = 0;

  /** Gets the distance between x1 and x2. This method is used by
    * KdTreeKMeans estimators. When the estimator is refactored,
    * this method should be removed. Distance between two measurement
    * vectors can be computed by setting one of them as an origin of
    * the distane and using the Evaluate method with a single argument */
  virtual double Evaluate(const MeasurementVectorType & x1,
                          const MeasurementVectorType & x2) const = 0;

  /** Set method for the length of the measurement vector */
  virtual void SetMeasurementVectorSize(MeasurementVectorSizeType s)
  {
    // Test whether the vector type is resizable or not
    MeasurementVectorType m;

    if ( MeasurementVectorTraits::IsResizable(m) )
      {
      // then this is a resizable vector type
      //
      // if the new size is the same as the previou size, just return
      if ( s == this->m_MeasurementVectorSize )
        {
        return;
        }
      else
        {
        this->m_MeasurementVectorSize = s;
        this->Modified();
        }
      }
    else
      {
      // If this is a non-resizable vector type
      MeasurementVectorType     m3;
      MeasurementVectorSizeType defaultLength =
        NumericTraits<MeasurementVectorType>::GetLength(m3);
      // and the new length is different from the default one, then throw an
      // exception
      if ( defaultLength != s )
        {
        itkExceptionMacro(
          "Attempting to change the measurement \
                           vector size of a non-resizable vector type"                                                  );
        }
      }
  }

  /** Get method for the length of the measurement vector */
  itkGetConstMacro(MeasurementVectorSize, MeasurementVectorSizeType);
protected:
  DistanceMetric();
  virtual ~DistanceMetric() {}
  void PrintSelf(std::ostream & os, Indent indent) const;

private:

  OriginType m_Origin;

  /** Number of components in the MeasurementVectorType */
  MeasurementVectorSizeType m_MeasurementVectorSize;
};  // end of class
} // end of namespace Statistics
} // end of namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkDistanceMetric.hxx"
#endif

#endif


text:
`package loadbalancer` provides a client-side load balancer abstraction.

A publisher is responsible for emitting the most recent set of endpoints for a
single logical service. Publishers exist for static endpoints, and endpoints
discovered via periodic DNS SRV lookups on a single logical name. Consul and
etcd publishers are planned.

Different load balancing strategies are implemented on top of publishers. Go
kit currently provides random and round-robin semantics. Smarter behaviors,
e.g. load balancing based on underlying endpoint priority/weight, is planned.

## Rationale

TODO

## Usage

In your client, define a publisher, wrap it with a balancing strategy, and pass
it to a retry strategy, which returns an endpoint.  Use that endpoint to make
requests, or wrap it with other value-add middleware.

```go
func main() {
	var (
		fooPublisher = loadbalancer.NewDNSSRVPublisher("foo.mynet.local", 5*time.Second, makeEndpoint)
		fooBalancer  = loadbalancer.RoundRobin(fooPublisher)
		fooEndpoint  = loadbalancer.Retry(3, time.Second, fooBalancer)
	)
	http.HandleFunc("/", handle(fooEndpoint))
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func makeEndpoint(hostport string) endpoint.Endpoint {
	// Convert a host:port to a endpoint via your defined transport.
}

func handle(foo endpoint.Endpoint) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// foo is usable as a load-balanced remote endpoint.
	}
}
```


text:
#ifndef TREE_H_
#define TREE_H_

#include <vector>	// for std::vector (childNodes)
#include <queue>	// for std::queue  (level-order-traversal)
#include <string>	// for std::string
#include <iostream>	// for std::cout
#include <iomanip>	// for std::setw(n)
#include <cstddef>  // for std::size_t

/////////////////////////
//////// N o d e ////////
/////////////////////////

template<typename _DataType>
class Node {
public:
	Node();
	Node(const _DataType & src);
	Node(_DataType && src);

	Node<_DataType> * parent;						/// parent
	std::vector<Node<_DataType> *> childNodes;		/// children
	_DataType data;									/// data
};

//////////////////////////////////////////////////

template<typename _DataType>
inline Node<_DataType>::Node()
	: parent(nullptr), childNodes(), data()
{
}

template<typename _DataType>
inline Node<_DataType>::Node(const _DataType & src)
	: parent(nullptr), childNodes(), data(src)
{
}

template<typename _DataType>
inline Node<_DataType>::Node(_DataType && src)
	: parent(nullptr), childNodes(), data(src)
{
}

/////////////////////////
//////// T r e e ////////
/////////////////////////

template <typename _DataType>
class Tree {
public:
	using NodeType = Node<_DataType>;	/// alias type for the template type used

public:
	Tree();		/// constructor
	~Tree();	/// destructor
	Tree(const Tree<_DataType>& src);	/// Copy constructor
	Tree& operator = (const Tree<_DataType> &rhs);	// copy assignment constructor
	// destructor, copy constructor and copy assignment constructor
	// just needed for when pointer is used

public:
	bool isEmpty() const;
	Node<_DataType> * getRoot() const;
	std::size_t size() const;	/// returns the number of nodes

	// Prints the n-ary tree level wise (level-order)
	static void printLevelOrder(NodeType * rootNode);
	void printLevelOrder();		// prints the level order from the position of the root node
	//enables prettier calls, eg: tree.printLevelOrder();

	NodeType * createNewNode(NodeType * dstNode);	/// creates a new node at destination with default values returning the newly created node

private:
	void clear(NodeType * node);	// clears the subtree from the position of the passed node, used by destructor
	NodeType * copyTree(NodeType * parent, NodeType * other);	// copies the tree on the right to the left, used by copy constructors

private:
	NodeType * m_root;		// stores a pointer to the root node of the tree
	int m_amountOfNodes;	// cached value of the tree size, so no traversal needed anymore to find it out
};

template <typename _DataType>
std::ostream& operator<<(std::ostream&, const Node<_DataType>& node);	// friend to ostream not needed because it has public access to struct anyways

//////////////////////////////////////////////////

template <typename _DataType>
Tree<_DataType>::Tree() : m_amountOfNodes(0) {
	//cout << "constructor called \n";
	m_root = createNewNode(nullptr);
}

template <typename _DataType>
Tree<_DataType>::~Tree() {
	//cout << "destructor called \n";
	//std::cout << "before call to clear: " << m_amountOfNodes << "\n";
	clear(m_root);
	//std::cout << "after call to clear: " << m_amountOfNodes << "\n";
}

template <typename _DataType>
Tree<_DataType>::Tree(const Tree<_DataType> &src) {
	//cout << "copy constructor called \n";
	// check for self-assignment
	if (this == &src) {
		return;
	}

	// assign the contents (deep copy)
	m_amountOfNodes = 0;
	m_root = copyTree(nullptr, src.m_root);
}

template <typename _DataType>
Tree<_DataType> & Tree<_DataType>::operator=(const Tree<_DataType> &rhs) {
	//cout << "copy assignment constructor called \n";

	// check for self-assignment
	if (this == &rhs) {
		return *this;
	}

	// assign the contents (deep copy)
	this->m_amountOfNodes = 0;
	this->m_root = copyTree(nullptr, rhs.m_root);

	return *this;
}

////////////////////////////////////////////////////////////////////////////////

template <typename _DataType>
inline bool
Tree<_DataType>::isEmpty() const {
	return !m_root;
}

template <typename _DataType>
inline Node<_DataType> *
Tree<_DataType>::getRoot() const {
	return m_root;
}

template <typename _DataType>
inline Node<_DataType> *
Tree<_DataType>::createNewNode(NodeType * dstNode) {
	NodeType *newNode = new NodeType;

	// addNodeTo destination node
	newNode->parent = dstNode;
	if (dstNode != nullptr) {
		dstNode->childNodes.push_back(newNode);
	}

	++m_amountOfNodes;
	return newNode;
}

// Print the tree level-order assisted by queue
template <typename _DataType>
inline void
Tree<_DataType>::printLevelOrder(NodeType * rootNode) {
	if (rootNode == nullptr) { return; }
	std::queue<NodeType *> q; // Create a queue (FIFO)
	q.push(rootNode); // Enqueue root

	int level = 0;
	while (!q.empty()) {
		std::cout << "\n" << level++ << ": \t";
		int n = q.size();

		// If this node has children
		while (n > 0) {
			// Dequeue an item from queue and print it
			NodeType * p = q.front();
			q.pop();
			std::cout << std::setw(10) << *p << " ";

			// Enqueue all children of the dequeued item
			for (std::size_t i = 0; i < p->childNodes.size(); i++) {
				q.push(p->childNodes[i]);
			}
			n--;
		}

		std::cout << "\n"; // Print new line between two levels
	}
	std::cout << "\n\n";
}

template<typename _DataType>
inline
void Tree<_DataType>::printLevelOrder()
{
	Tree<_DataType>::printLevelOrder(m_root);
}

template <typename _DataType>
inline std::size_t
Tree<_DataType>::size() const
{
	return m_amountOfNodes;
}

template <typename _DataType>
inline void
Tree<_DataType>::clear(NodeType * node) {
	if (node == nullptr) { return; }

	/* first delete all subtrees (from left to right) */
	for (std::size_t i = 0; i < node->childNodes.size(); ++i) {
		clear(node->childNodes[i]);
	}

	/* then delete the node */
	//cout << "\n\n Deleting node: " << node->UCTB << "\n\n";
	delete node;
	--m_amountOfNodes;
}

template <typename _DataType>
inline Node<_DataType> *
Tree<_DataType>::copyTree(NodeType * parent, NodeType * src) {
	if (src == nullptr) {
		return nullptr;
	}

	// create newNode and copy data
	NodeType * newNode = createNewNode(parent);
	newNode->data = src->data;

	// copy all subtrees from current node (parent)
	for (std::size_t i = 0; i < src->childNodes.size(); ++i) {
		newNode->childNodes[i] = copyTree(newNode, src->childNodes[i]);
	}

	// return currently copied
	return newNode;
}

template <typename _DataType>
inline std::ostream&
operator<<(std::ostream& os, const Node<_DataType>& node) {
	os << node.data;
	return os;	// enables concatenation of ostreams with <<
}

#endif /* TREE_H_ */


text:
package org.bitcoins.core.serializers.script

import org.bitcoins.core.protocol.script.{EmptyScriptPubKey, ScriptPubKey}
import org.bitcoins.core.script.bitwise.OP_EQUALVERIFY
import org.bitcoins.core.script.constant._
import org.bitcoins.core.script.crypto.{OP_CHECKSIG, OP_HASH160}
import org.bitcoins.core.script.stack.OP_DUP
import org.bitcoins.core.util.BytesUtil
import org.bitcoins.testkitcore.util.TestUtil
import org.bitcoins.testkitcore.util.BitcoinSUnitTest
import scodec.bits.ByteVector

/** Created by chris on 1/12/16.
  */
class RawScriptPubKeyParserTest extends BitcoinSUnitTest {
  val encode = BytesUtil.encodeHex(_: ByteVector)
  "RawScriptPubKeyParser" must "read then write the scriptPubKey and get the original scriptPubKey" in {
    val scriptPubKey: ScriptPubKey =
      RawScriptPubKeyParser.read(TestUtil.rawScriptPubKey)
    encode(RawScriptPubKeyParser.write(scriptPubKey)) must be(
      TestUtil.rawScriptPubKey)
  }

  it must "read an EmptyScriptPubKey" in {
    assert(RawScriptPubKeyParser.read(ByteVector.empty) == EmptyScriptPubKey)
  }

  it must "read a raw scriptPubKey and give us the expected asm" in {
    val scriptPubKey = RawScriptPubKeyParser.read(TestUtil.rawP2PKHScriptPubKey)
    val expectedAsm: Seq[ScriptToken] =
      List(OP_DUP,
           OP_HASH160,
           BytesToPushOntoStack(20),
           ScriptConstant("31a420903c05a0a7de2de40c9f02ebedbacdc172"),
           OP_EQUALVERIFY,
           OP_CHECKSIG)
    scriptPubKey.asm must be(expectedAsm)

  }
  it must "read a raw scriptPubKey from an output" in {
    //from b30d3148927f620f5b1228ba941c211fdabdae75d0ba0b688a58accbf018f3cc
    //output is index 1
    val rawScriptPubKey = "17a914af575bd77c5ce7eba3bd9ce6f89774713ae62c7987"
    val scriptPubKey = RawScriptPubKeyParser.read(rawScriptPubKey)
    encode(RawScriptPubKeyParser.write(scriptPubKey)) must be(rawScriptPubKey)
  }

  it must "read and write the scriptPubKey that pushes using a PUSHDATA1 that is negative when read as signed" in {
    val rawScriptPubKey =
      "0x4c 0xae 0x606563686f2022553246736447566b58312b5a536e587574356542793066794778625456415675534a6c376a6a334878416945325364667657734f53474f36633338584d7439435c6e543249584967306a486956304f376e775236644546673d3d22203e20743b206f70656e73736c20656e63202d7061737320706173733a5b314a564d7751432d707269766b65792d6865785d202d64202d6165732d3235362d636263202d61202d696e207460 DROP DUP HASH160 0x14 0xbfd7436b6265aa9de506f8a994f881ff08cc2872 EQUALVERIFY CHECKSIG"
    val asm = ScriptParser.fromString(rawScriptPubKey)
    val scriptPubKey = ScriptPubKey.fromAsm(asm)
    val actualRawScriptPubKey = RawScriptPubKeyParser.write(scriptPubKey)
    //the actual hex representation is from a bitcoin core test case inside of tx_valid.json
    encode(actualRawScriptPubKey) must be(
      "ca4cae606563686f2022553246736447566b58312b5a536e587574356542793066794778625456415675534a6c376a6a334878416945325364667657734f53474f36633338584d7439435c6e543249584967306a486956304f376e775236644546673d3d22203e20743b206f70656e73736c20656e63202d7061737320706173733a5b314a564d7751432d707269766b65792d6865785d202d64202d6165732d3235362d636263202d61202d696e2074607576a914bfd7436b6265aa9de506f8a994f881ff08cc287288ac")

  }

}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>A packet which instructs a node that the build is complete.</summary>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Microsoft.Build.BackEnd
{
    /// <summary>
    /// The NodeBuildComplete packet is used to indicate to a node that it should clean up its current build and
    /// possibly prepare for node reuse.
    /// </summary>
    internal class NodeBuildComplete : INodePacket
    {
        /// <summary>
        /// Flag indicating if the node should prepare for reuse after cleanup.
        /// </summary>
        private bool _prepareForReuse;

        /// <summary>
        /// Constructor.
        /// </summary>
        public NodeBuildComplete(bool prepareForReuse)
        {
            _prepareForReuse = prepareForReuse;
        }

        /// <summary>
        /// Private constructor for translation
        /// </summary>
        private NodeBuildComplete()
        {
        }

        /// <summary>
        /// Flag indicating if the node should prepare for reuse.
        /// </summary>
        public bool PrepareForReuse
        {
            [DebuggerStepThrough]
            get
            { return _prepareForReuse; }
        }

        #region INodePacket Members

        /// <summary>
        /// The packet type
        /// </summary>
        public NodePacketType Type
        {
            [DebuggerStepThrough]
            get
            { return NodePacketType.NodeBuildComplete; }
        }

        #endregion

        #region INodePacketTranslatable Members

        /// <summary>
        /// Translates the packet to/from binary form.
        /// </summary>
        /// <param name="translator">The translator to use.</param>
        public void Translate(INodePacketTranslator translator)
        {
            translator.Translate(ref _prepareForReuse);
        }

        /// <summary>
        /// Factory for deserialization.
        /// </summary>
        internal static NodeBuildComplete FactoryForDeserialization(INodePacketTranslator translator)
        {
            NodeBuildComplete packet = new NodeBuildComplete();
            packet.Translate(translator);
            return packet;
        }

        #endregion
    }
}


text:
package info.guardianproject.otr.app.im.plugin;

/** Defines the IDs of branding resources. */
public interface BrandingResourceIDs {

    /** The logo icon of the provider which is displayed in the landing page. */
    public static final int DRAWABLE_LOGO = 100;
    /** The icon of online presence status. */
    public static final int DRAWABLE_PRESENCE_ONLINE = 102;
    /** The icon of busy presence status. */
    public static final int DRAWABLE_PRESENCE_BUSY = 103;
    /** The icon of away presence status. */
    public static final int DRAWABLE_PRESENCE_AWAY = 104;
    /** The icon of invisible presence status. */
    public static final int DRAWABLE_PRESENCE_INVISIBLE = 105;
    /** The icon of offline presence status. */
    public static final int DRAWABLE_PRESENCE_OFFLINE = 106;
    /** The label of the menu to go to the contact list screen. */
    public static final int STRING_MENU_CONTACT_LIST = 107;

    /** The image displayed on the splash screen while logging in. */
    public static final int DRAWABLE_SPLASH_SCREEN = 200;
    /** The icon for blocked contacts. */
    public static final int DRAWABLE_BLOCK = 201;
    /** The water mark background for chat screen. */
    public static final int DRAWABLE_CHAT_WATERMARK = 202;
    /** The icon for the read conversation. */
    public static final int DRAWABLE_READ_CHAT = 203;
    /** The icon for the unread conversation. */
    public static final int DRAWABLE_UNREAD_CHAT = 204;

    /**
     * The title of buddy list screen. It's conjuncted with the current username
     * and should be formatted as a string like
     * "Contact List - <xliff:g id="username">%1$s</xliff:g>
     */
    public static final int STRING_BUDDY_LIST_TITLE = 301;

    /** A string array of the smiley names. */
    public static final int STRING_ARRAY_SMILEY_NAMES = 302;
    /** A string array of the smiley texts. */
    public static final int STRING_ARRAY_SMILEY_TEXTS = 303;

    /** The string of available presence status. */
    public static final int STRING_PRESENCE_AVAILABLE = 304;
    /** The string of away presence status. */
    public static final int STRING_PRESENCE_AWAY = 305;
    /** The string of busy presence status. */
    public static final int STRING_PRESENCE_BUSY = 306;
    /** The string of the idle presence status. */
    public static final int STRING_PRESENCE_IDLE = 307;
    /** The string of the invisible presence status. */
    public static final int STRING_PRESENCE_INVISIBLE = 308;
    /** The string of the offline presence status. */
    public static final int STRING_PRESENCE_OFFLINE = 309;

    /** The label of username displayed on the account setup screen. */
    public static final int STRING_LABEL_USERNAME = 310;
    /** The label of the ongoing conversation group. */
    public static final int STRING_ONGOING_CONVERSATION = 311;
    /** The title of add contact screen. */
    public static final int STRING_ADD_CONTACT_TITLE = 312;
    /** The label of the contact input box on the add contact screen. */
    public static final int STRING_LABEL_INPUT_CONTACT = 313;
    /** The label of the add contact button on the add contact screen */
    public static final int STRING_BUTTON_ADD_CONTACT = 314;
    /** The title of the contact info dialog. */
    public static final int STRING_CONTACT_INFO_TITLE = 315;
    /** The label of the menu to add a contact. */
    public static final int STRING_MENU_ADD_CONTACT = 316;
    /** The label of the menu to start a conversation. */
    public static final int STRING_MENU_START_CHAT = 317;
    /** The label of the menu to view contact profile info. */
    public static final int STRING_MENU_VIEW_PROFILE = 318;
    /** The label of the menu to end a conversation. */
    public static final int STRING_MENU_END_CHAT = 319;
    /** The label of the menu to block a contact. */
    public static final int STRING_MENU_BLOCK_CONTACT = 320;
    /** The label of the menu to delete a contact. */
    public static final int STRING_MENU_DELETE_CONTACT = 321;
    /** The label of the menu to insert a smiley. */
    public static final int STRING_MENU_INSERT_SMILEY = 322;
    /** The label of the menu to switch conversations. */
    public static final int STRING_MENU_SWITCH_CHATS = 323;
    /**
     * The string of the toast displayed when auto sign in button on the account
     * setup screen is checked.
     */
    public static final int STRING_TOAST_CHECK_AUTO_SIGN_IN = 324;
    /**
     * The string of the toast displayed when the remember password button on
     * the account setup screen is checked.
     */
    public static final int STRING_TOAST_CHECK_SAVE_PASSWORD = 325;
    /** The label of sign up a new account on the account setup screen. */
    public static final int STRING_LABEL_SIGN_UP = 326;
    /**
     * The term of use message. If provided, a dialog will be shown at the first
     * time login to ask the user if he would accept the term or not.
     */
    public static final int STRING_TOU_MESSAGE = 327;
    /** The title of the term of use dialog. */
    public static final int STRING_TOU_TITLE = 328;
    /** The label of the button to accept the term of use. */
    public static final int STRING_TOU_ACCEPT = 329;
    /** The label of the button to decline the term of use. */
    public static final int STRING_TOU_DECLINE = 330;
}


text:
/**
 * Created on 2008-6-21 06:53:10
 */
package cn.net.openid.jos.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import cn.net.openid.jos.web.AbstractJosController;

/**
 * @author Sutra Zhou
 */
public class SetPrimaryEmailController extends AbstractJosController {
	/**
	 * {@inheritDoc}
	 */
	public ModelAndView handleRequest(final HttpServletRequest request,
			final HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		if (!StringUtils.isEmpty(id)) {
			getJosService().setPrimaryEmail(getUser(request), id);
		}
		request.getRequestDispatcher("/email").forward(request, response);
		return null;
	}
}


text:
package com.k_beta.android.app.data;

import com.google.gson.*;

import java.lang.reflect.Type;

/**
 * Created by dongkai on 2015/11/3.
 */

public class MyResponseDeserializer implements JsonDeserializer<MyResponse> {
    private final static String KEY_OK = "code";
    private final static String KEY_MSG = "msg";
    private final static String KEY_DATAS = "datas";
    private final static String KEY_PAGE = "page";

    @Override
    public MyResponse deserialize(JsonElement json, Type type,
                                       JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = (JsonObject) json;
        MyResponse res = new MyResponse();
        JsonElement codeElelment= jsonObject.get(KEY_OK);
        if(codeElelment !=null && !(codeElelment instanceof JsonNull)){
            res.setCode(codeElelment.getAsInt());
        }
        JsonElement objElement = jsonObject.get(KEY_DATAS);
        if (objElement != null && !(objElement instanceof JsonNull)) {
            res.setDatas(objElement.toString());
        }
        JsonElement msgElement = jsonObject.get(KEY_MSG);
        if (msgElement != null && !(msgElement instanceof JsonNull)) {
            res.setMsg(msgElement.toString());
        }
        JsonElement pageElement = jsonObject.get(KEY_PAGE);
        if (pageElement != null && !(pageElement instanceof JsonNull)) {
            res.setMsg(pageElement.toString());
        }
        return res;
    }
}


text:
package com.asakusafw.compiler.flow.testing.external;

import com.asakusafw.compiler.flow.testing.model.ExJoined;
import com.asakusafw.compiler.testing.TemporaryOutputDescription;

/**
 * Mock exporter description for {@link ExJoined}.
 */
public class ExJoinedMockExporterDescription extends TemporaryOutputDescription {

    @Override
    public Class<?> getModelType() {
        return ExJoined.class;
    }

    @Override
    public String getPathPrefix() {
        return "target/testing/out/" + getModelType().getSimpleName() + "-*";
    }
}


text:
package pl.inpar.socketrpc.mocks;

import java.util.List;

public interface SampleService {

	void doStuff();
	int getValue();

	void intAsArg(int i);

	String stringify(List<Integer> ints);
}


text:
<?php
if (!defined('EVENT_ESPRESSO_VERSION') )
	exit('NO direct script access allowed');

class Messages_Template_List_Table extends EE_Admin_List_Table {

	/**
	 * @return Messages_Admin_Page
	 */
	public function get_admin_page() {
		return $this->_admin_page;
	}

	protected function _setup_data() {
		$this->_data = $this->get_admin_page()->get_message_templates( $this->_per_page, $this->_view, FALSE);
		$this->_all_data_count = $this->get_admin_page()->get_message_templates( $this->_per_page, $this->_view, TRUE, TRUE );
	}

	protected function _set_properties() {
		$this->_wp_list_args = array(
			'singular' => __('Message Template Group', 'event_espresso' ),
			'plural' => __('Message Template', 'event_espresso' ),
			'ajax' => TRUE, //for now,
			'screen' => $this->get_admin_page()->get_current_screen()->id
			);
		$this->_columns = array(
			//'cb' => '<input type="checkbox" />', //no deleting default (global) templates!
			'message_type' => __('Message Type', 'event_espresso'),
			'messenger' => __( 'Messenger', 'event_espresso'),
			'description' => __( 'Description', 'event_espresso' ),
			//'messages_sent' => __( 'Total Sent', 'event_espresso' ) //todo this will come later when we've got message tracking in place.
			);

		$this->_sortable_columns = array(
			'messenger' => array( 'MTP_messenger' => TRUE ),
			//'message_type' => array( 'MTP_message_type' => FALSE )
			);

		$this->_hidden_columns = array();
	}

	/**
	 * Overriding the single_row method from parent to verify whether the $item has an accessible
	 * message_type or messenger object before generating the row.
	 *
	 * @param EE_Message_Template_Group $item
	 *
	 * @return string
	 */
	public function single_row( $item ) {
		$message_type = $item->message_type_obj();
		$messenger = $item->messenger_obj();

		if ( ! $message_type instanceof EE_message_type || ! $messenger instanceof EE_messenger ) {
			echo '';
			return;
		}

		parent::single_row( $item );
	}

	/**
	 * @return array
	 */
	protected function _get_table_filters() {
		$filters = array();

		//get select inputs
		$select_inputs = array(
			$this->_get_messengers_dropdown_filter(),
			$this->_get_message_types_dropdown_filter(),
		);

		//set filters to select inputs if they aren't empty
		foreach ( $select_inputs as $select_input ) {
			if ( $select_input ) {
				$filters[] = $select_input;
			}
		}
		return $filters;
	}

	/**
	 * we're just removing the search box for message templates, not needed.
	 * @return string (empty);
	 */
	function search_box( $text, $input_id ) {
		return '';
	}

	protected function _add_view_counts() {
		foreach ( $this->_views as $view => $args )  {
			$this->_views[$view]['count'] = $this->get_admin_page()->get_message_templates( $this->_per_page, $view, TRUE, TRUE );
		}
	}

	public function column_cb( $item ) {
		return '';
	}

	function column_description( $item ) {
		return '
' . $item->message_type_obj()->description . '
';
	}

	/*function column_cb($item) {
		return sprintf( '<input type="checkbox" name="checkbox[%1$s]" />', $item->GRP_ID() );
	}/**/

	function column_messenger($item) {

		//Build row actions
		$actions = array();

		// edit link but only if item isn't trashed.
		if ( !$item->get('MTP_deleted') && EE_Registry::instance()->CAP->current_user_can( 'ee_edit_message', 'espresso_messages_edit_message_template', $item->ID() ) ) {
			$edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce( array( 'action'=>'edit_message_template', 'id'=>$item->GRP_ID() ), EE_MSG_ADMIN_URL );
			$actions['edit'] = '' . __( 'Edit', 'event_espresso' ) . '';
		}

		$name_link = ! $item->get('MTP_deleted') && EE_Registry::instance()->CAP->current_user_can( 'ee_edit_message', 'espresso_messages_edit_message_template', $item->ID() ) ? '' . ucwords( $item->messenger_obj()->label['singular'] ) . '' : ucwords( $item->messenger_obj()->label['singular'] );

		//we want to display the contexts in here so we need to set them up
		$c_label = $item->context_label();
		$c_configs = $item->contexts_config();
		$ctxt = array();
		$context_templates = $item->context_templates();
		foreach ( $context_templates as $context => $template_fields ) {
			$mtp_to = !empty( $context_templates[$context]['to'] ) && $context_templates[$context]['to'] instanceof EE_Message_Template ? $context_templates[$context]['to']->get('MTP_content') : NULL;
			$inactive = empty( $mtp_to ) && !empty( $context_templates[$context]['to'] ) ? ' class="mtp-inactive"' : '';
			$context_title = ucwords($c_configs[$context]['label']);
			$edit_link = EE_Admin_Page::add_query_args_and_nonce( array('action'=>'edit_message_template', 'id'=>$item->GRP_ID(), 'context' => $context), EE_MSG_ADMIN_URL );
			$ctxt[] = EE_Registry::instance()->CAP->current_user_can( 'ee_edit_message', 'espresso_messages_edit_message_template', $item->ID() ) ? '' . $context_title . '' : $context_title;
		}

		$ctx_content = !$item->get('MTP_deleted') && EE_Registry::instance()->CAP->current_user_can( 'ee_edit_message', 'espresso_messages_edit_message_template', $item->ID() ) ? sprintf( __('%s: ', 'event_espresso'), ucwords($c_label['plural']) ) . implode(' | ', $ctxt) : '';

		//Return the name contents
		return sprintf('%1$s (id:%2$s)
%3$s%4$s',
										/* $1%s */ $name_link,
										/* $2%s */ $item->GRP_ID(),
										/* %4$s */ $ctx_content,
										/* $3%s */ $this->row_actions( $actions )
		);
	}

	/**
	 * column_message_type
	 * @param  object $item message info for the row
	 * @return string       message_type name
	 */
	function column_message_type($item) {
		return ucwords($item->message_type_obj()->label['singular'] );
	}

	function column_messages_sent($item) {
		//todo: we need to obtain the messages sent and the link to the messages report table and output
		return __('feature in progress', 'event_espresso');
	}

	/**
	 * Generate dropdown filter select input for messengers
	 * @return string
	 */
	protected function _get_messengers_dropdown_filter() {
		$messenger_options = array();
		$active_message_template_groups_grouped_by_messenger = EEM_Message_Template_Group::instance()->get_all(
			array(
				array(
					'MTP_is_active' => true,
					'MTP_is_global' => true,
				),
				'group_by' => 'MTP_messenger',
			)
		);

		foreach ( $active_message_template_groups_grouped_by_messenger as $active_message_template_group ) {
			if ( $active_message_template_group instanceof EE_Message_Template_Group ) {
				$messenger = $active_message_template_group->messenger_obj();
				$messenger_label = $messenger instanceof EE_messenger
					? $messenger->label['singular']
					: $active_message_template_group->messenger();
				$messenger_options[ $active_message_template_group->messenger() ] = ucwords( $messenger_label );
			}
		}
		return $this->get_admin_page()->get_messengers_select_input( $messenger_options );
	}

	/**
	 * Generate dropdown filter select input for message types
	 * @return string
	 */
	protected function _get_message_types_dropdown_filter() {
		$message_type_options = array();
		$active_message_template_groups_grouped_by_message_type = EEM_Message_Template_Group::instance()->get_all(
			array(
				array(
					'MTP_is_active' => true,
					'MTP_is_global' => true,
				),
				'group_by' => 'MTP_message_type',
			)
		);

		foreach ( $active_message_template_groups_grouped_by_message_type as $active_message_template_group ) {
			if ( $active_message_template_group instanceof EE_Message_Template_Group ) {
				$message_type = $active_message_template_group->message_type_obj();
				$message_type_label = $message_type instanceof EE_message_type
					? $message_type->label['singular']
					: $active_message_template_group->message_type();
				$message_type_options[ $active_message_template_group->message_type() ] = ucwords( $message_type_label );
			}
		}
		return $this->get_admin_page()->get_message_types_select_input( $message_type_options );
	}

}


text:
@implementation MMInfoItem3

@synthesize height;
@synthesize Class;
@synthesize reuseIdentify;
@synthesize isRegisterByClass;

- (id)initWithDictionary:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        [self ms_reflectDataFromOtherDictionary:dict];

        self.height = 132;
        self.Class = [MMInfoCell3 class];
        self.reuseIdentify = @"MMInfoCell3";
    }

    return self;
}

- (instancetype)parse:(NSDictionary *)info options:(NSUInteger)options
{
    return [self initWithDictionary:info];
}

@end


text:
package io.inkstand.scribble.http.rules;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.commons.io.IOUtils;

/**
 * A {@link ResourceHttpHandler} that serves the content of a URL. It's intended for serving classpath resources
 * referenced by URL but it may also serves resource from the local filesystem or from a network resource.
 * Created by Gerald Muecke on 11.12.2015.
 */
public class UrlResourceHandler extends ResourceHttpHandler{

    private final URL resource;

    public UrlResourceHandler(URL resource ){
        this.resource = resource;
    }

    @Override
    protected void writeResource(final OutputStream outputStream) throws IOException {
            try(InputStream inputStream = resource.openStream()){
                IOUtils.copy(inputStream, outputStream);
            }
    }
}


text:
import { toast } from "react-toastify";

export const showToast = (component, params = {}) => {
  toast(component, {
    closeButton: false,
    closeOnClick: false,
    draggable: false,
    hideProgressBar: true,
    ...params,
  });
};


text:
import os

class DirConfiguration:

    def __init__ (self, path, recursive=True, debug=False):
        if not os.path.exists(path):
            raise ValueError ('Path does not exist')
        elif not os.path.isdir(path):
            raise ValueError ('Path is not a directory')

        self.path = path
        self.recursive = recursive
        self.debug = debug
        self.config = self.__read_path(path, recursive=recursive)

    def __read_path (self, rootPath, config={}, recursive=True):
        paths = os.listdir(rootPath)
        for currPath in paths:
            currPath = rootPath + "/" + currPath
            key = os.path.basename(currPath)
            if self.debug: print 'this is for path', currPath

            if os.path.isdir(currPath) and recursive:
                value = self.__read_path(currPath, {}, recursive)
                if self.debug: print 'for key ' + key + ' storing child value:', value
                config[key] = value

            elif os.path.isfile(currPath):
                currFile = open(currPath, 'r')
                key = os.path.basename(currPath)

                if key == 'children':
                    if self.debug: print 'Warning: illegal file name in "'+currPath+'":', key
                else:
                    for currLine in currFile:
                        if key not in config:
                            config[key] = []

                        if self.debug: print 'for key ' + key + ' storing:', currLine.strip()
                        config[key].append(currLine.strip())

            else:
                if self.debug: print 'Notice: odd path exists in configuration directory:', currPath

        if self.debug: print 'returning this for path "' + rootPath + '":', config
        return config


text:
package Historic;

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

public class Historic extends Observable {
	private static Historic instance = null;

	protected Historic() {
		eventList.add(" Mahjong Game ");
		eventList.add("Initialisation");
		eventList.add("--------------");
		eventList.add("Starting  Game");
		eventList.add("--------------");
	}

	public static Historic getInstance() {
		if (instance == null) {
			instance = new Historic();
		}
		return instance;
	}

	private List<String> eventList = new ArrayList<>();

	public String getEvents() {
		String events = "";
		for (int k = 0; k < 5; k++) {
			events += eventList.get(eventList.size() - (5 - k)) + "\n";
		}
		return events;
	}

	public void addEvent(String event){
		eventList.add(event);
		setChanged();
		notifyObservers();
	}
}


text:
#ifndef QSYNCABLEFUNCTIONS_H
#define QSYNCABLEFUNCTIONS_H

#include <QObject>
#include <QJSValue>
#include <QVariant>

namespace QSyncable {

    /// Assign properties from source object to the destination object.
    void assign(QVariantMap& dest, const QObject*source);

    void assign(QObject* dest, const QVariantMap& source);

    void assign(QObject* dest, const QJSValue& source);

    /// Gets the value at path of object. If the path is not found, the defaultValue is returned.
    /*
     Example:

     get(object, "a.b.c");

    */
    QVariant get(const QObject* source, const QString& path, const QVariant& defaultValue = QVariant());

    QVariant get(const QObject* source, const QStringList& path, const QVariant& defaultValue = QVariant());

    QVariant get(const QVariantMap& source, const QString& path, const QVariant& defaultValue = QVariant());

    QVariant get(const QVariantMap& source, const QStringList& path, const QVariant& defaultValue = QVariant());

    /// Sets the value at path of object. If a portion of path doesn't exist, it's created.
    /*
     Example:

     set(data, "a.b", 3); // data["a"] will be a QVariantMap that contains a key of "b".

     */
    void set(QVariantMap& dest, const QString& path, const QVariant& value);

    void set(QVariantMap& dest, const QStringList& path, const QVariant& value);

    /// Creates an QVariantMap composed of the picked object properties at paths.
    /*
     Example:

         pick(object, QStringList() << "a" << "b.c");

     If a property contains QObject pointer, it will be converted to QVariantMap.

     In case you need to obtain a QObject pointer, please use get().

     */

    QVariantMap pick(QObject* source, const QStringList& paths);

    QVariantMap pick(QVariantMap source, const QStringList& paths);

    QVariantMap pick(QVariantMap source, const QVariantMap& paths);

    /// The opposite of pick(), this method creates an QVariantMap composed of the own properties that are not omitted.
    /*
     If a property contains QObject pointer, it will be converted to QVariantMap.

     In case you need to obtain a QObject pointer, please use get().
     */
    QVariantMap omit(const QVariantMap& source, const QVariantMap& properties);

}

#endif // QSYNCABLEFUNCTIONS_H


text:
define(['Ti/_/declare', 'Ti/_/Evented'], function (declare, Evented) {

		return declare('Ti._.UI.MessagingDialog', Evented, {

			open: function () {
				var self = this,
					appControl = new tizen.ApplicationControl('http://tizen.org/appcontrol/operation/send', null, null, null, createAllParameters()),
					serviceCB = {
						onsuccess: function () {
							self.fireEvent('complete', {
								result: self.SENT,
								success: true
							});
						},
						onfailure: function () {
							self.fireEvent('complete', {
								result: self.CANCELLED,
								success: false
							});
						}
					};

				function createParameter(name, valueArray) {
					require.is(valueArray, 'Array') || (valueArray = [valueArray]);
					return new tizen.ApplicationControlData(name, valueArray);
				};

				function createAllParameters() {
					// Take the user-supplied parameters ('messageBody', 'toRecipients', etc) and convert them to the form
					// required by Tizen's email application (i.e. array of tizen.ApplicationControlData).
					// ApplicationControl requires an array, even if there is only one parameter.

					var params = [],
						i;

					for (i in self._fields) {
						self[i] && params.push(createParameter(self._fields[i], self[i]));
					}
					return params;
				};

				// Launching the native Tizen's message editing aplication
				tizen.application.launchAppControl(appControl, self._id, function () {
						console.log('Launch appControl succeeded')
					}, function (e) {
						self.fireEvent('complete', {
							result: self.FAILED,
							success: false
						});
						console.log('Launch appControl failed. Reason: ' + e.name)
					}, serviceCB);
			},

			addAttachment: function (blob) {
				require.is(this.attachment, 'Array') || (this.attachment = []);

				if (blob.nativePath) {
					this.attachment.push(blob.nativePath);
				} else {
					console.log('Tizen currently only supports attaching a blob with the path to physical file presents on the Tizen device.');
				}
			},

			isSupported: function () {
				return true;
			},

			constants: {
				CANCELLED: 0,
				FAILED: 3,
				SAVED: 1,
				SENT: 2
			},

			properties: {
				messageBody: void 0,
				toRecipients: void 0
			}
		});

	});


text:
#include "gtest/gtest.h"

#include "ChannelUri.h"
#include "ChannelUriStringBuilder.h"

using namespace aeron;

TEST(ChannelUriTest, shouldParseSimpleDefaultUris)
{
    std::shared_ptr<ChannelUri> channelUri;

    channelUri = ChannelUri::parse("aeron:udp");
    ASSERT_EQ(channelUri->prefix(), "");
    ASSERT_EQ(channelUri->media(), "udp");

    channelUri = ChannelUri::parse("aeron:ipc");
    ASSERT_EQ(channelUri->prefix(), "");
    ASSERT_EQ(channelUri->media(), "ipc");

    channelUri = ChannelUri::parse("aeron-spy:aeron:udp");
    ASSERT_EQ(channelUri->prefix(), "aeron-spy");
    ASSERT_EQ(channelUri->media(), "udp");
}

TEST(ChannelUriTest, shouldRejectUriWithoutAeronPrefix)
{
    ASSERT_THROW(ChannelUri::parse(":udp"), IllegalArgumentException);
    ASSERT_THROW(ChannelUri::parse("aeron"), IllegalArgumentException);
    ASSERT_THROW(ChannelUri::parse("aron:"), IllegalArgumentException);
    ASSERT_THROW(ChannelUri::parse("eeron:"), IllegalArgumentException);
}

TEST(ChannelUriTest, shouldRejectWithOutOfPlaceColon)
{
    ASSERT_THROW(ChannelUri::parse("aeron:udp:"), IllegalStateException);
}

TEST(ChannelUriTest, shouldRejectWithInvalidMedia)
{
    ASSERT_THROW(ChannelUri::parse("aeron:ipcsdfgfdhfgf"), IllegalArgumentException);
}

TEST(ChannelUriTest, shouldRejectWithMissingQuerySeparatorWhenFollowedWithParams)
{
    ASSERT_THROW(ChannelUri::parse("aeron:ipc|sparse=true"), IllegalStateException);
}

TEST(ChannelUriTest, shouldRejectWithInvalidParams)
{
    ASSERT_THROW(ChannelUri::parse("aeron:udp?endpoint=localhost:4652|-~@{]|=??#s!£$%===="), IllegalStateException);
}

TEST(ChannelUriTest, shouldParseWithMultipleParameters)
{
    std::shared_ptr<ChannelUri> channelUri;

    channelUri = ChannelUri::parse("aeron:udp?endpoint=224.10.9.8|port=4567|interface=192.168.0.3|ttl=16");
    ASSERT_EQ(channelUri->get("endpoint"), "224.10.9.8");
    ASSERT_EQ(channelUri->get("port"), "4567");
    ASSERT_EQ(channelUri->get("interface"), "192.168.0.3");
    ASSERT_EQ(channelUri->get("ttl"), "16");
}

TEST(ChannelUriTest, shouldAllowReturnDefaultIfParamNotSpecified)
{
    std::shared_ptr<ChannelUri> channelUri;

    channelUri = ChannelUri::parse("aeron:udp?endpoint=224.10.9.8");
    ASSERT_EQ(channelUri->get("endpoint"), "224.10.9.8");
    ASSERT_EQ(channelUri->get("interface"), "");
    ASSERT_EQ(channelUri->get("interface", "192.168.0.0"), "192.168.0.0");
}

TEST(ChannelUriTest, shouldRoundTripToString)
{
    const std::string uriString("aeron:udp?endpoint=224.10.9.8:777");
    std::shared_ptr<ChannelUri> channelUri = ChannelUri::parse(uriString);

    ASSERT_EQ(channelUri->toString(), uriString);
}

TEST(ChannelUriTest, shouldRoundTripToStringBuilder)
{
    ChannelUriStringBuilder builder;

    builder
        .media(UDP_MEDIA)
        .endpoint("224.10.9.8:777");

    const std::string uriString = builder.build();

    std::shared_ptr<ChannelUri> channelUri = ChannelUri::parse(uriString);
    ASSERT_EQ(channelUri->toString(), uriString);
}

TEST(ChannelUriTest, shouldRoundTripToStringBuilderWithPrefix)
{
    ChannelUriStringBuilder builder;

    builder
        .prefix(SPY_QUALIFIER)
        .media(UDP_MEDIA)
        .endpoint("224.10.9.8:777");

    const std::string uriString = builder.build();

    std::shared_ptr<ChannelUri> channelUri = ChannelUri::parse(uriString);
    ASSERT_EQ(channelUri->toString(), uriString);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Mvc;
using AIM.Web.Admin.Client;
using AIM.Web.Admin.Models.EntityModels;

namespace AIM.Web.Admin.Controllers
{
    public class UserController : Controller
    {
        private readonly UserServiceClient _client = new UserServiceClient();
        private User _user = new User();

        public UserController()
        {
            _client = new UserServiceClient();
        }

        // GET: /User/
        public async Task<ActionResult> Index()
        {
            IEnumerable<User> users = await _client.GetUsers();

            return View(users);
        }

        // GET: /User/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            User user = await _client.GetUserById(id);

            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // GET: /User/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /User/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "UserId,FirstName,MiddleName,LastName,Email,SocialSecurityNumber," +
                                                   "PersonalInfoId,ApplicantId,ApplicationId,EmployeeId,UserName," +
                                                   "Password,AspNetUsersId")] User user)
        {
            if (ModelState.IsValid)
            {
                User updatedUser = null;

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://aimadminstrativeservice.cloudapp.net/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // HTTP GET
                    string request = "api/User";
                    HttpResponseMessage response = await client.PostAsJsonAsync(request, user);
                    if (response.IsSuccessStatusCode)
                    {
                        updatedUser = await response.Content.ReadAsAsync<User>();
                    }
                }

                if (user != null)
                {
                    TempData["Message"] = "User " + user.FirstName + " " + user.LastName +
                                          " was successfully created.";
                }

            return RedirectToAction("Index");
            }

            var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();

            return View(user);
        }

        // GET: /User/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            User user = await _client.GetUserById(id);

            // Start change-tracking the model
            _user = user;

            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // POST: /User/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "UserId,FirstName,MiddleName,LastName,Email,SocialSecurityNumber," +
                                                   "PersonalInfoId,ApplicantId,ApplicationId,EmployeeId,UserName," +
                                                   "Password,AspNetUsersId")] User user)
        {
            if (ModelState.IsValid)
            {
                User updatedUser = user;

                await _client.DeleteUser(user.UserId);

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://aimadminstrativeservice.cloudapp.net/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // HTTP GET
                    string request = "api/User";
                    HttpResponseMessage response = await client.PostAsJsonAsync(request, user);
                    if (response.IsSuccessStatusCode)
                    {
                        updatedUser = await response.Content.ReadAsAsync<User>();
                    }
                }

                TempData["Message"] = "User " + user.FirstName + " " + user.LastName +
                                          " was successfully updated.";

                return RedirectToAction("Index");
            }

            return View(user);
        }

        // GET: /User/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            User user = await _client.GetUserById(id);

            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // POST: /User/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            // Delete the user
            await _client.DeleteUser(id);

            // Verify order was deleted
            User deletedUser = await _client.GetUserById(id);
            if (deletedUser == null)
            {
                TempData["Message"] = "User was successfully deleted.";
            }
            else
            {
                TempData["Message"] = "User was not deleted.";
            }

            return RedirectToAction("Index");
        }
    }
}


text: Website repo for the http://compsust.fas.sfu.ca


text:
layout: post
title: Mou
categories:
- Logiciel
tags:
- Editeur
- Logiciel
- Markdown
- Mou
- Syntaxe
status: publish
type: post
published: true
meta:
  _edit_last: '1'
  layout: default
  post_color: default
  hide_post_title: default
  unlink_post_title: default
  hide_post_meta: default
  hide_post_date: default
  hide_post_image: default
  _thumbnail_id: '5944'
  tmac_last_id: '256453601025736704'
---
Mou, un éditeur markdown pour les développeurs web.

La semaine prochaine, je m'en vais en formation. Mon vieux MacBook étant au bord du précipice et déjà dépourvu de batterie ayant une autonomie supérieur à trente seconde, c'est le MacBook du bureau qui m'accompagnera dans les conférences.

Oui, vous avez bien compris. Je vais me retrouver là-bas sans mes petits programme adorés qui me rendent la vie tellement plus facile. Je suis donc partie à la recherche d'une alternative à mon chère iA Writer.

Au coin d'une recherche Google, je suis tombé sur Mou. Un programme gratuit qui comme iA Writer permet de taper du texte au moyen de la syntaxe Markdown. Si comme moi vous êtes des adepte de cette syntaxe, Mou mérite qu'on s'y attarde.

La fenêtre est scindée en deux. Dans partie de droite, vous taper votre texte en Markdown et celui-ci est mis en page dans la partie de droite. Du plus, vous bénéficier d'une colorisation syntaxique. Le tout est sans fioriture, très bien fait et ... gratuit.

On verra ce que cela donne après une utilisation intensive.


text:
package mobi.bbhn.brightberry;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import org.json.me.JSONArray;
import org.json.me.JSONObject;

class DirectMessageSentThread extends Thread {
	String url = "http://brightkite.com/me/sent_messages.json?limit=";
	HttpConnection httpConnection = null;
	InputStream httpInput = null;
	String serverResponse = "";
	DirectMessageSentScreen screen;
	Settings settings = Settings.getInstance();
	String offset = "&offset=";

	public DirectMessageSentThread(DirectMessageSentScreen directMessageSentScreen, int maxMessages, int start) {
		this.screen = directMessageSentScreen;
		this.url = this.url + maxMessages + this.offset + start;
	}

	public void run() {
		try {
			this.url += NetworkConfig.getConnectionParameters(this.settings.getConnectionMode());
			this.httpConnection = ((HttpConnection)Connector.open(this.url));
			this.httpConnection.setRequestProperty("User-Agent", BrightBerry.useragent);
			this.httpConnection.setRequestProperty("Content-Language", "en-US");
			this.httpConnection.setRequestProperty("Authorization", this.settings.getAuthHeader());
			this.httpConnection.setRequestProperty("x-rim-transcode-content", "none");
			this.httpInput = this.httpConnection.openInputStream();
			int rc = this.httpConnection.getResponseCode();
			if (rc == 503) {
				BrightBerry.displayAlert("Error", "BrightKite is too busy at the moment try again later");
			} else if (rc == 401 || rc == 403) {
				BrightBerry.errorUnauthorized();
			} else {
				StringBuffer buffer = new StringBuffer();
				int ch = 0;
				while (ch != -1) {
					ch = this.httpInput.read();
					buffer.append((char)ch);
				}
				this.screen.updateMessages(parseJSON(buffer.toString()));
			}
			if (this.httpInput != null) {
				this.httpInput.close();
			}
			if (this.httpConnection != null) {
				this.httpConnection.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	private DirectMessageSent[] parseJSON(String json) {
		JSONArray jsonArray = null;
		Vector msgsent = new Vector();
		Vector imagescached = new Vector();
		DirectMessageSent[] rv = null;

		try {
			jsonArray = new JSONArray(json);

			for (int x = 0; x < jsonArray.length(); ++x) {
				JSONObject jsonStream = jsonArray.getJSONObject(x);
				String createdwords = jsonStream.getString("created_at_as_words");
				JSONObject jsonCreator = jsonStream.getJSONObject("recipient");
				String creator = jsonCreator.getString("login");
				String avatar = jsonCreator.getString("small_avatar_url");
				if (ImageCache.inCache(creator) == false && imagescached.contains(creator) == false) {
					imagescached.addElement(creator);
					AvatarThread getavtr = new AvatarThread(creator, avatar);
					getavtr.start();
				}
				String body = jsonStream.getString("body");
				int id = jsonStream.getInt("id");
				msgsent.addElement(new DirectMessageSent(creator, body, createdwords, id));
			}
			rv = new DirectMessageSent[jsonArray.length()];
			msgsent.copyInto(rv);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return rv;
	}
}


text:
.carousel-indicators, .carousel-control {
    display:none;
}


text:
layout: page
title: Statistik
permalink: "webclient/de/statistik/"
language: de
---

Auf der Statistikseite werden konfigurierte Statistiken aus der Datenbank angezeigt. Es gibt vier verschiedene Diagrammtypen: Kreis-, vertikale Balken-, horizontale Balken- und Liniendiagramm.

![X]({{ site.baseUrl }}/assets/content-images/webclient/de/statisticsPage.PNG "Statistik Seite")

### Statistik Übersicht
Die Funktionen erstellen, editieren und löschen stehen nur für Nutzer mit Admin-/Konfiguratorrechten zur Verfügung.
Links werden alle Statistikbereiche angezeigt und rechts die Statistiken des momentan aktiven Bereichs.
Falls kein Bereich in der Datenbank vorhanden ist, wird der Bereich "Allgemeine Statistiken" erstellt.
Ein Bereich kann nur gelöscht werden, wenn er keine Statistiken enthält.

#### 1. Statistikbereich
Hier wird der Name des Bereichs angezeigt, man kann neue Statistiken erstellen und den Bereich bearbeiten.
Wenn der Bereich Statistiken enthält, wird das Icon zum Löschen ausgegraut und erst wieder aktiviert, wenn alle Statistiken von diesem Bereich gelöscht wurden.
Beim Erstellen wird der aktuelle Bereich schon selektiert.

#### 2. Statistik editieren und löschen
Mit einem Klick auf das Icon mit dem Stift und dem Papier kann die Statistik bearbeitet werden. Mit dem Abfalleimer Icon erscheint ein Dialog mit einer Info, dass diese Aktion schlussendlich ausgeführt. Die Statistik wird aus der Datenbank gelöscht und auch gleich von der Seite entfernt.

Mittels drap-and-drop kann die Reihenfolge der Statistiken innerhalb eines Bereichs verschoben werden. Dadurch wird auch sofort die Reihenfolge der Diagramme angepasst.

#### 3. Statistikbereich hinzufügen
Hier kann ein neuer Statistikbereich hinzugefügt werden.

#### 4. Statistik Anzeige
Die Diagramme des momentan aktiven Bereichs werden hier angezeigt. Fährt man mit der Maus über ein Diagramm, werden oben rechts 3 Icons eingeblendet um die Statistik zu **aktualisieren**, **editieren** oder zu **löschen**.

![X]({{ site.baseUrl }}/assets/content-images/webclient/de/statisticrefresh.png "Statistik aktualisieren/editieren/löschen")

Mittels drap-and-drop kann die Reihenfolge der Diagramme geändert werden. Dadurch wird auch sofort die Reihenfolge der Statistiken im Statistikbereich geändert.

### Statistik bearbeiten

Durch Klicken auf das Bearbeiten-Icon wird der Dialog mit den Eigenschaften der Statistik geöffnet:

![X]({{ site.baseUrl }}/assets/content-images/webclient/de/statisticInputDial.PNG "Statistik erstellen/editieren Dialog")

* **Name:**	Der Statistik kann ein Name gegeben werden um dem Betrachter informationen über den Inhalt zu geben.
* **Diagramm Typ:**	Die Art des Diagramms kann hier ausgewählt werden.
* **Höche/Breite:**	Um das Diagramm besser lesbar zu gestalten, kann man selber definieren wie gross/klein es dargestellt werden soll.
* **Legende:** Hier können per Komma getrennt die Legenden eingegeben werden.
* **Sql:** Die Abfrage der Datenbank, welche dazu benötigt wird, die anzuzeigenden Daten zu liefern. Das Ergebnis muss im Format: Label, String \| FirstValue, int \| SecondValue, int zurückgegeben werden. Wobei das Feld SecondValue optional ist.

### Statistikbereich bearbeiten

Klickt man auf das Bearbeiten-Icon eines Statistikbereichs oder auf das Icon zum Erstellen eines neuen Bereichs, wird der Dialog mit den Eigenschaften des Statistikbereichs geöffnet:

![X]({{ site.baseUrl }}/assets/content-images/webclient/de/addStatisticArea.PNG "Statistikbereich erstellen/editieren Dialog")

* **Name:**	Dem Statistikbereich kann ein Name gegeben werden um dem Betrachter Informationen über den Inhalt zu geben.


text:
START_ATF_NAMESPACE
    CNationSettingDataTW::CNationSettingDataTW()
    {
        using org_ptr = void (WINAPIV*)(struct CNationSettingDataTW*);
        (org_ptr(0x14022f9b0L))(this);
    };
    void CNationSettingDataTW::ctor_CNationSettingDataTW()
    {
        using org_ptr = void (WINAPIV*)(struct CNationSettingDataTW*);
        (org_ptr(0x14022f9b0L))(this);
    };
    struct CashDbWorker* CNationSettingDataTW::CreateWorker()
    {
        using org_ptr = struct CashDbWorker* (WINAPIV*)(struct CNationSettingDataTW*);
        return (org_ptr(0x140230040L))(this);
    };
    int CNationSettingDataTW::GetCashItemPrice(struct _CashShop_str_fld* pFld)
    {
        using org_ptr = int (WINAPIV*)(struct CNationSettingDataTW*, struct _CashShop_str_fld*);
        return (org_ptr(0x1402300f0L))(this, pFld);
    };
    char* CNationSettingDataTW::GetItemName(struct _NameTxt_fld* pFld)
    {
        using org_ptr = char* (WINAPIV*)(struct CNationSettingDataTW*, struct _NameTxt_fld*);
        return (org_ptr(0x14022fb10L))(this, pFld);
    };
    int CNationSettingDataTW::Init()
    {
        using org_ptr = int (WINAPIV*)(struct CNationSettingDataTW*);
        return (org_ptr(0x14022fa10L))(this);
    };
    bool CNationSettingDataTW::IsPersonalFreeFixedAmountBillingType(int16_t* pDest1, int16_t* pDest2)
    {
        using org_ptr = bool (WINAPIV*)(struct CNationSettingDataTW*, int16_t*, int16_t*);
        return (org_ptr(0x14022fff0L))(this, pDest1, pDest2);
    };
    bool CNationSettingDataTW::ReadSystemPass()
    {
        using org_ptr = bool (WINAPIV*)(struct CNationSettingDataTW*);
        return (org_ptr(0x140230110L))(this);
    };
    bool CNationSettingDataTW::ValidMacAddress()
    {
        using org_ptr = bool (WINAPIV*)(struct CNationSettingDataTW*);
        return (org_ptr(0x14022fb30L))(this);
    };
END_ATF_NAMESPACE


text:
namespace boost {
  namespace BOOST_SIGNALS_NAMESPACE {
    namespace detail {
      class BOOST_SIGNALS_DECL slot_base {
        // We would have to enumerate all of the signalN classes here as
        // friends to make this private (as it otherwise should be). We can't
        // name all of them because we don't know how many there are.
      public:
        struct data_t {
          std::vector<const trackable*> bound_objects;
          connection watch_bound_objects;
        };
        shared_ptr<data_t> get_data() const { return data; }

        // Get the set of bound objects
        std::vector<const trackable*>& get_bound_objects() const
        { return data->bound_objects; }

        // Determine if this slot is still "active", i.e., all of the bound
        // objects still exist
        bool is_active() const
        { return data->watch_bound_objects.connected(); }

      protected:
        // Create a connection for this slot
        void create_connection();

        shared_ptr<data_t> data;

      private:
        static void bound_object_destructed(void*, void*) {}
      };
    } // end namespace detail

    // Get the slot so that it can be copied
    template<typename F>
    reference_wrapper<const F>
    get_invocable_slot(const F& f, BOOST_SIGNALS_NAMESPACE::detail::signal_tag)
      { return reference_wrapper<const F>(f); }

    template<typename F>
    const F&
    get_invocable_slot(const F& f, BOOST_SIGNALS_NAMESPACE::detail::reference_tag)
      { return f; }

    template<typename F>
    const F&
    get_invocable_slot(const F& f, BOOST_SIGNALS_NAMESPACE::detail::value_tag)
      { return f; }

    // Get the slot so that it can be inspected for trackable objects
    template<typename F>
    const F&
    get_inspectable_slot(const F& f, BOOST_SIGNALS_NAMESPACE::detail::signal_tag)
      { return f; }

    template<typename F>
    const F&
    get_inspectable_slot(const reference_wrapper<F>& f, BOOST_SIGNALS_NAMESPACE::detail::reference_tag)
      { return f.get(); }

    template<typename F>
    const F&
    get_inspectable_slot(const F& f, BOOST_SIGNALS_NAMESPACE::detail::value_tag)
      { return f; }

    // Determines the type of the slot - is it a signal, a reference to a
    // slot or just a normal slot.
    template<typename F>
    typename BOOST_SIGNALS_NAMESPACE::detail::get_slot_tag<F>::type
    tag_type(const F&)
    {
      typedef typename BOOST_SIGNALS_NAMESPACE::detail::get_slot_tag<F>::type
        the_tag_type;
      the_tag_type tag = the_tag_type();
      return tag;
    }

  } // end namespace BOOST_SIGNALS_NAMESPACE

  template<typename SlotFunction>
  class slot : public BOOST_SIGNALS_NAMESPACE::detail::slot_base {
    typedef BOOST_SIGNALS_NAMESPACE::detail::slot_base inherited;
    typedef typename inherited::data_t data_t;

  public:
    template<typename F>
    slot(const F& f) : slot_function(BOOST_SIGNALS_NAMESPACE::get_invocable_slot(f, BOOST_SIGNALS_NAMESPACE::tag_type(f)))
    {
      this->data.reset(new data_t);

      // Visit each of the bound objects and store them for later use
      // An exception thrown here will allow the basic_connection to be
      // destroyed when this goes out of scope, and no other connections
      // have been made.
      BOOST_SIGNALS_NAMESPACE::detail::bound_objects_visitor
        do_bind(this->data->bound_objects);
      visit_each(do_bind,
                 BOOST_SIGNALS_NAMESPACE::get_inspectable_slot
                   (f, BOOST_SIGNALS_NAMESPACE::tag_type(f)));
      create_connection();
    }

#ifdef __BORLANDC__
    template<typename F>
    slot(F* f) : slot_function(f)
    {
      this->data.reset(new data_t);
      create_connection();
    }
#endif // __BORLANDC__

    // We would have to enumerate all of the signalN classes here as friends
    // to make this private (as it otherwise should be). We can't name all of
    // them because we don't know how many there are.
  public:
    // Get the slot function to call the actual slot
    const SlotFunction& get_slot_function() const { return slot_function; }

    void release() const { data->watch_bound_objects.set_controlling(false); }

  private:
    slot(); // no default constructor
    slot& operator=(const slot&); // no assignment operator

    SlotFunction slot_function;
  };
} // end namespace boost

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_SIGNALS_SLOT_HEADER


text:
CREATE TABLE `squash_results` (
  `resultid` int(11) NOT NULL default '0',
  `match_date` date NOT NULL default '0000-00-00',
  `player1` int(11) NOT NULL default '0',
  `player2` int(11) NOT NULL default '0',
  `result` int(11) NOT NULL default '0',
  PRIMARY KEY  (`resultid`)
) TYPE=MyISAM;


text:
from bibliopixel.drivers.visualizer import DriverVisualizer
from bibliopixel.drivers.dummy_driver import DriverDummy
from bibliopixel.drivers.APA102 import DriverAPA102, ChannelOrder
from bibliopixel.led import LEDStrip
from ledstrip import IndicatorStrip
import logging
import yaml
from app import strips, scheduler
from plugins.plugin_loader import load_plugins
from . import set_pixel

def _create_bibliopixel_strip(config):
    driver_type = config['driver_type']
    if driver_type == 'Dummy':
        driver = DriverDummy(num=config['pixel_count'])
    elif driver_type == 'Visualizer':
        driver = DriverVisualizer(width=config['pixel_count'], height=1, stayTop=config.get('stay_on_top', True))
    elif driver_type == 'APA102':
        driver = DriverAPA102(config['pixel_count'], c_order=ChannelOrder.GBR, dev='/dev/spidev32766.0')
    else:
        raise 'Unknown driver_type: {0}'.format(driver_type)
    bibliopixel_base_thing = LEDStrip(driver)
    return IndicatorStrip(bibliopixel_base_thing,
                          config['pixel_count'],
                          is_reversed=config.get('is_reversed', False),
                          is_disabled=config.get('is_disabled', False),
                          disabled_pixels=config.get('disabled_pixels', None))

def _load_strips(config):
    logger = logging.getLogger(__name__)
    new_strips = {}
    if config is None or len(config) == 0:
        logger.info("No strips configured")
    else:
        for key in config:
            logger.info("Loading strip: %s" % key)
            new_strips[key] = _create_bibliopixel_strip(config[key])
    strips.update(new_strips)

def load_configuration_file(configuration_filename):
    logger = logging.getLogger(__name__)
    logger.info("Reloading configuration file: %s" % configuration_filename)
    config = yaml.load(file(configuration_filename, mode='r'))
    _load_strips(config['strips'])
    load_plugins(config['runners'], scheduler, set_pixel)


text:
using System;
using System.Xml.Serialization;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace JdSdk.Domain.Kuaiche.AccountJosService
{
    [Serializable]
    public class AccountVO : JdObject
    {
        [JsonProperty("total_amount")]
        public String TotalAmount
        {
            get;
            set;
        }

        [JsonProperty("available_amount")]
        public String AvailableAmount
        {
            get;
            set;
        }

        [JsonProperty("freeze_amount")]
        public String FreezeAmount
        {
            get;
            set;
        }

    }

}


text:
First time users and those looking for a quick and easy deployment, see the
instructions in the [quickstart](quickstart) directory.

For more customized use cases with more complex requirements, see the
configuration in the [py](py) directory which uses several startup scripts in
the [scripts](scripts) directory.


text:
from setuptools import setup

from pycl import __version__

setup(
    name='pycl',
    version=__version__,
    author="Ken Watford",
    author_email="kwatford@gmail.com",
    url="https://github.com/ucb-sejits/pycl",
    download_url="https://github.com/ucb-sejits/pycl",
    py_modules=['pycl'],
    license='MIT',
    description="OpenCL wrapper using ctypes",
    # long_description=open('README.md').read(),
    tests_require=['nose'],
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Topic :: Software Development :: Libraries',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        ],
    entry_points={
        'console_scripts': ['pycl = pycl:main'],
    }

)


text:
package duo

import (
	"encoding/json"
	"net/url"

	duoapi "github.com/duosecurity/duo_api_golang"

	"github.com/authelia/authelia/v4/internal/middlewares"
)

// API interface wrapping duo api library for testing purpose.
type API interface {
	Call(ctx *middlewares.AutheliaCtx, values url.Values, method string, path string) (*Response, error)
	PreAuthCall(ctx *middlewares.AutheliaCtx, values url.Values) (*PreAuthResponse, error)
	AuthCall(ctx *middlewares.AutheliaCtx, values url.Values) (*AuthResponse, error)
}

// APIImpl implementation of DuoAPI interface.
type APIImpl struct {
	*duoapi.DuoApi
}

// Device holds all necessary info for frontend.
type Device struct {
	Capabilities []string `json:"capabilities"`
	Device       string   `json:"device"`
	DisplayName  string   `json:"display_name"`
	Name         string   `json:"name"`
	SmsNextcode  string   `json:"sms_nextcode"`
	Number       string   `json:"number"`
	Type         string   `json:"type"`
}

// Response coming from Duo API.
type Response struct {
	Response      json.RawMessage `json:"response"`
	Code          int             `json:"code"`
	Message       string          `json:"message"`
	MessageDetail string          `json:"message_detail"`
	Stat          string          `json:"stat"`
}

// AuthResponse is a response for a authorization request.
type AuthResponse struct {
	Result             string `json:"result"`
	Status             string `json:"status"`
	StatusMessage      string `json:"status_msg"`
	TrustedDeviceToken string `json:"trusted_device_token"`
}

// PreAuthResponse is a response for a preauthorization request.
type PreAuthResponse struct {
	Result          string   `json:"result"`
	StatusMessage   string   `json:"status_msg"`
	Devices         []Device `json:"devices"`
	EnrollPortalURL string   `json:"enroll_portal_url"`
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using FlatRedBall.Glue.Plugins.Interfaces;
using FlatRedBall.Glue.Plugins.ExportedInterfaces;
using FlatRedBall.Glue.CodeGeneration;
using FlatRedBall.Glue.Plugins;
using FlatRedBall.Glue.Parsing;

namespace PluginTestbed.MoveToLayerPlugin
{

    [Export(typeof(PluginBase))]
    class MoveToLayerContainer : PluginBase
    {
        List<ElementComponentCodeGenerator> mGeneratorList = new List<ElementComponentCodeGenerator>();

        bool mIsEnabled = true;

        [Import("GlueCommands")]
        public IGlueCommands GlueCommands
        {
            get;
            set;
        }

        public void CodeGenerationStart(FlatRedBall.Glue.SaveClasses.IElement element)
        {
        }

        public IEnumerable<FlatRedBall.Glue.CodeGeneration.ElementComponentCodeGenerator> CodeGeneratorList
        {
            get { return mGeneratorList; }
        }

        public override string FriendlyName
        {
            get { return "Move to Layer Plugin"; }
        }

        public override Version Version
        {
            get { return new Version(1,1); }
        }

        public override void StartUp()
        {
            mIsEnabled = true;

            mGeneratorList.Add(new MoveToLayerComponentGenerator());

            foreach(var generator in mGeneratorList)
            {
                CodeWriter.CodeGenerators.Add(generator);
            }
        }

        public override bool ShutDown(PluginShutDownReason shutDownReason)
        {
            mIsEnabled = false;

            foreach (var generator in mGeneratorList)
            {
                if (CodeWriter.CodeGenerators.Contains(generator))
                {
                    CodeWriter.CodeGenerators.Remove(generator);
                }
            }

            return true;

        }
    }
}


text:
class GameProcess : public IGameProcess {
 public:
    GameProcess();
    explicit GameProcess(Vector2i mapSize);
    virtual void getNextGeneration();
    virtual int getMapHeight();
    virtual int getMapWidth();
    virtual Vector2i getMapSize();
    virtual void fillMapWithRandomPopulations(unsigned int seed);
    virtual void setMapCell(int col, int row, int populationID);
    virtual void updateGeneration();
};

#endif  // MODEL_INCLUDE_GAMEPROCESS_H


text:
.markdown-editor {
	-mwfx-inline-background-color: #f6f6f6;
}

/* editor padding */
/* disabled because of character hitting issue in RichTextFX
   https://github.com/TomasMikula/RichTextFX/pull/396
.markdown-editor .paragraph-box .paragraph-text {
    -fx-padding: 0 1em 0 1em;
}
.markdown-editor .paragraph-box:last-paragraph .paragraph-text {
    -fx-padding: 0 1em 1em 1em;
}
.markdown-editor .paragraph-box:first-paragraph .paragraph-text {
    -fx-padding: 1em 1em 0 1em;
}
*/

/* highlight current line */
.markdown-editor .paragraph-box:has-caret {
    -fx-background-color: #f2f9fc;
}

/*---- gutter ----*/

.markdown-editor .paragraph-graphic .gutter {
	-fx-border-width: 0 1 0 0;
	-fx-border-color: #eee;
}

.markdown-editor .paragraph-graphic .lineno {
	-fx-text-fill: #aaa;
	-fx-padding: 0 0.25em 0 0.25em;
}

/* editor padding */
/* disabled because of character hitting issue in RichTextFX
   https://github.com/TomasMikula/RichTextFX/pull/396
.markdown-editor .paragraph-box:first-paragraph .paragraph-graphic .gutter {
    -fx-padding: 1em 0 0 0;
}
.markdown-editor .paragraph-box:first-paragraph .paragraph-graphic .gutter.lineno {
	-fx-padding: 1em 0.25em 0 0.25em;
}
*/

/*---- headers ----*/

.markdown-editor .h1 { -fx-font-size: 2em; }
.markdown-editor .h2 { -fx-font-size: 1.75em; }
.markdown-editor .h3 { -fx-font-size: 1.5em; }
.markdown-editor .h4 { -fx-font-size: 1.25em; }
.markdown-editor .h5 { -fx-font-size: 1.1em; }
.markdown-editor .h6 { -fx-font-size: 1em; }

.markdown-editor .h1,
.markdown-editor .h2,
.markdown-editor .h3,
.markdown-editor .h4,
.markdown-editor .h5,
.markdown-editor .h6 {
	-fx-font-weight: bold;
	-fx-fill: #c62828;
}

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

.markdown-editor .strong {
	-fx-font-weight: bold;
	-rtfx-background-color: -mwfx-inline-background-color;
}

.markdown-editor .em {
	-fx-font-style: italic;
	-rtfx-background-color: -mwfx-inline-background-color;
}

.markdown-editor .del {
	-fx-strikethrough: true;
	-rtfx-background-color: -mwfx-inline-background-color;
}

.markdown-editor .a {
	-fx-fill: #4183C4 !important;
	-rtfx-background-color: -mwfx-inline-background-color;
}

.markdown-editor .img {
	-fx-fill: #BF360C !important;
	-rtfx-background-color: -mwfx-inline-background-color;
}

.markdown-editor .code {
	-fx-fill: #388E3C !important;
	-rtfx-background-color: -mwfx-inline-background-color;
}

.markdown-editor .br {
	-rtfx-background-color: #c8eafb;
}

/*---- blocks ----*/

.markdown-editor .pre.paragraph-text {
    -fx-background-color: -mwfx-inline-background-color;
}
.markdown-editor .pre.text {
	-fx-fill: #2E7D32 !important;
}

.markdown-editor .blockquote {
	-fx-fill: #777;
}
.markdown-editor .aside {
	-fx-fill: #BF360C;
}

/*---- lists ----*/

.markdown-editor .ul {
}

.markdown-editor .ol {
}

.markdown-editor .li {
	-fx-fill: #444;
}

.markdown-editor .liopen {
	-fx-fill: #BF360C;
	-fx-font-weight: bold;
}

.markdown-editor .liopentask {
	-fx-fill: #283593;
	-fx-font-weight: bold;
}

.markdown-editor .dl {
}

.markdown-editor .dt {
	-fx-font-weight: bold;
	-fx-font-style: italic;
}

.markdown-editor .dd {
	-fx-fill: #444;
}

/*---- table ----*/

.markdown-editor .table.paragraph-text {
    -fx-background-color: -mwfx-inline-background-color;
}

.markdown-editor .thead {
}

.markdown-editor .tbody {
}

.markdown-editor .tr {
}

.markdown-editor .th {
	-fx-font-weight: bold;
}

.markdown-editor .td {
}

/*---- misc ----*/

.markdown-editor .html {
	-fx-fill: derive(crimson, -50%);
}

.markdown-editor .reference {
	-fx-fill: derive(#4183C4,30%) !important;
}

.markdown-editor .abbrdef,
.markdown-editor .abbr {
	-fx-fill: #004D40;
}


text:
layout: "fluid/docs_base"
version: "4.20.0"
versionHref: "/docs/native"
path: ""
category: native
id: "speechkit"
title: "SpeechKit"
header_sub_title: "Class in module "
doc: "SpeechKit"
docType: "class"
---

SpeechKit

  Improve this doc

Implementation of Nuance SpeechKit SDK on Ionic

Repo:

    https://github.com/Shmarkus/cordova-plugin-nuance-speechkit

Installation

Install the Cordova and Ionic Native plugins:

$ ionic cordova plugin add cordova-plugin-nuance-speechkit
$ npm install --save @ionic-native/speechkit@4

Add this plugin to your app's module

Supported platforms

Android

iOS

Usage

import { SpeechKit } from '@ionic-native/speechkit';

constructor(private speechkit: SpeechKit) { }

// find voice names that match language from: https://developer.nuance.com/public/index.php?task=supportedLanguages
this.speechkit.tts('Text to be read out loud', 'ENG-GBR', 'Serena').then(
  (msg) => { console.log(msg); },
  (err) => { console.log(err); }
);

Instance Members

tts()

Speak text out loud in given language

  Returns: Promise<string>

asr()

  Platforms:Android

Try to recognize what the user said

  Returns: Promise<string>


text:
'use strict';

// MODULES //

var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var format = require( '@stdlib/string/format' );

// MAIN //

/**
* Validates function options.
*
* @private
* @param {Object} opts - destination for function options
* @param {Options} options - function options
* @param {NonNegativeInteger} [options.depth] - depth to flatten
* @param {boolean} [options.copy] - boolean indicating whether to deep copy array elements
* @returns {(Error|null)} error or null
*
* @example
* var opts = {};
* var options = {
*     'depth': 10,
*     'copy': false
* };
* var err = validate( opts, options );
* if ( err ) {
*     throw err;
* }
*/
function validate( opts, options ) {
	if ( !isObject( options ) ) {
		return new TypeError( format( 'invalid argument. Options argument must be an object. Value: `%s`.', options ) );
	}
	if ( hasOwnProp( options, 'depth' ) ) {
		opts.depth = options.depth;
		if ( !isNonNegativeInteger( opts.depth ) ) {
			return new TypeError( format( 'invalid option. `%s` option must be a nonnegative integer. Option: `%s`.', 'depth', opts.depth ) );
		}
	}
	if ( hasOwnProp( options, 'copy' ) ) {
		opts.copy = options.copy;
		if ( !isBoolean( opts.copy ) ) {
			return new TypeError( format( 'invalid option. `%s` option must be a boolean. Option: `%s`.', 'copy', opts.copy ) );
		}
	}
	return null;
}

// EXPORTS //

module.exports = validate;


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Mitth. Thüring. Bot. Vereins new ser. , 13-14:66. 1899 "Triticum aegilopoides race thaoudar"

#### Original name
null

### Remarks
null