text:
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { AssignmentForm, SSHLoginForm, GraderList, OutputContainer } from 'components';
import { asyncConnect } from 'redux-async-connect';
import { destroy, isLoaded, load, runScript, update, getGraders } from 'redux/modules/assignment';

@asyncConnect([{
  promise: (options) => {
    const { store: { dispatch, getState }, params: { repoId, assignmentId } } = options;

    if (!isLoaded(getState(), repoId, assignmentId)) {
      return dispatch(load(repoId, assignmentId));
    }
  }
}])
@connect(
  state => ({
    repo: state.repo.repo,
    assignment: state.assignment.assignment,
    hasChanged: state.assignment.hasChanged,
    previewList: state.assignment.previewList,
    loading: state.assignment.loading,
    error: state.assignment.error
  }), {
    runScript,
    destroy,
    getGraders,
    update
  }
)
export default class AssignmentPage extends Component {
  static propTypes = {
    error: PropTypes.object,
    loading: PropTypes.bool,
    params: PropTypes.object.isRequired,
    destroy: PropTypes.func.isRequired,
    assignment: PropTypes.object,
    repo: PropTypes.object,
    runScript: PropTypes.func.isRequired,
    hasChanged: PropTypes.bool,
    update: PropTypes.func.isRequired,
    getGraders: PropTypes.func.isRequired,
    previewList: PropTypes.array
  }

  constructor(props, context) {
    super(props, context);

    this.state = { previewIndex: 0 };
  }

  componentWillMount() {
    if (this.props.hasChanged) {
      // We just created this assignment so we should run the script
      this.props.runScript({
        socketId: socket.id,
        assignment: this.props.assignment
      });
      this.setState({ previewIndex: 0 });
    } else if (this.props.repo) {
      // We're navigating into this assignment and we are already logged in
      this.props.getGraders(socket.id, this.props.params.assignmentId);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.hasChanged) {
      // User just updated the assignment arguments so we should run the script
      this.props.runScript({
        socketId: socket.id,
        assignment: nextProps.assignment
      });
      this.setState({ previewIndex: 0 });
    } else if (!this.props.repo && nextProps.repo) {
      // We just logged into the repository
      this.props.getGraders(socket.id, this.props.params.assignmentId);
    }
  }

  componentWillUnmount() {
    this.props.destroy();
  }

  handleRefreshClick = (event) => {
    event.preventDefault();

    if (event.target.className.indexOf('disabled') === -1) {
      this.props.getGraders(socket.id, this.props.params.assignmentId);
      this.setState({ previewIndex: 0 });
    }
  }

  handleLeftClick = (event) => {
    event.preventDefault();
    if (event.target.className.indexOf('disabled') === -1) {
      const { previewList } = this.props;
      const { previewIndex } = this.state;

      this.setState({ previewIndex: previewIndex ? previewIndex - 1 : previewList.length - 1 });
    }
  }

  handleRightClick = (event) => {
    event.preventDefault();
    if (event.target.className.indexOf('disabled') === -1) {
      const { previewList } = this.props;
      const { previewIndex } = this.state;

      this.setState({ previewIndex: (previewIndex + 1) % previewList.length });
    }
  }

  handleSubmit = (data) => {
    if (confirm('Are you sure you want to re-run the script?')) {
      this.props.update(data);
    }
  }

  render() {
    const { assignmentId, repoId } = this.props.params;
    const { assignment, error, repo, loading, previewList } = this.props;
    const { previewIndex } = this.state;

    return (

        <Helmet title={ assignmentId } />

          { repo && repo.username === repoId &&

                { repoId }

                <GraderList
                  assignmentId={ assignmentId }
                  repoId={ repoId }
                />
                {
                  previewList && previewList.length &&

                      Preview

                    { !loading &&
                      <OutputContainer
                        viewHeight="50"
                        multireducerKey="studentOutput"
                        assignmentId={ assignmentId }
                        graderId={ previewList[previewIndex].split('/')[0] }
                        fileName={ previewList[previewIndex].split('/')[1] }
                      />
                    }

 || !error && !loading &&

                    No assignments found! Please try running the script again
                    or make sure the repository path is correct!

 || error &&

                    { error.message }

                }

                  <AssignmentForm
                    repo={ repo }
                    error={ error }
                    loading={ loading }
                    folderDisabled
                    assignment={ assignment }
                    submitText="Re-Run Script"
                    onSubmit={ this.handleSubmit }
                  />

 ||
            <SSHLoginForm repoId={ repoId } />
          }

    );
  }
}


text:
layout: default
title: Routing
---

# Routing

  Respite is built on top of Scalatra, a Scala port of Ruby's Sinatra. For background and further detail on the routing DSL refer to the docs.

Respite controllers provide a powerful routing DSL & come standard with type-safe, JSON to case class conversion, including field-level validation.

Other out-of-the-box features include:

* CRUD for case class entities
* Route Caching & Simple Cache DSL
* Metrics & Health Check Support
* CORS Support
* API Key Authentication
* Output logging

## REST Controllers

For out-of-the-box CRUD services for your [Models](/models), create and register an instance of a `RestController`. This can be done in one of two ways: declaring a new `Class` extending `RestController` (recommended for all but the simplest of controllers) or creating a new value object of type `RestController`:

The following examples highlight the two forms:

**New Class**

```scala
class ProductController(repository: ReactiveRepository[Product, BSONObjectID])(override implicit val bindingModule: BindingModule, override implicit val tag: ClassTag[Product], override implicit val objectIdConverter: String => BSONObjectID) extends RestController[Product, BSONObjectID]("products", Product.format, repository)
```

**Value Object**

```scala
def route = new RestController[Product, BSONObjectID]("products", Product.format, new ProductRepository) with MetricsRestSupport[Product, BSONObjectID], "/products")
```

The latter form is generally only useful for fairly uninteresting CRUD services.

## JSON Services

If you don't require `Model` persistence, mixin the `PlayJsonSupport[T]` Trait, specifying the type that will be converted to/from JSON.

```scala
val playServlet = new TestServlet with PlayJsonSupport[User]
```

## Registering Controllers
Once you have created your `Controller`, simply add an instance of one with the `context.mount()` method in your `ScalatraBootstrap` class:

```scala
class ScalatraBootstrap extends LifeCycle {
  protected implicit def executor: ExecutionContext = ExecutionContext.global

  override def init(context: ServletContext) {

    // Import implicit definitions into Scope
    implicit val bindingModule = ProductionConfigurationModule  // DI Configuration object
    import au.com.onegeek.respite.models.ModelJsonExtensions._  // JSON extensions

    // Add Controllers here
    context.mount(new RestController[User, BSONObjectID]("users", User.format, new UserRepository), "/users/")
    context.mount(new MyModelController(new MyRepository), "/mymodels/")
  }
}
```

## API Keys & Authentication
API Keys are a simple way to control access to your APIs, but

### Manually managed keys

Useful during development, these keys are essentially an in-memory map that are not persisted between application restarts.

Create an instance of a `ConfigAuthenticationStrategy` setting the keys in the map:

```scala
// Authentication API with default keys
object ConfigAuthStrategy extends ConfigAuthenticationStrategy {
  override var keys = Map("admin" -> ApiKey(application = "admin", description = "Test App", key = "testkey")) ++
                      Map("murray" -> ApiKey(application = "bill", description = "Foo App", key = "murray"))
}
```

### Database Persisted Keys

Ensure a local Mongo database is available with the table 'apikeys' available. Respite provides a `ApiKeyRepository` class to persist keys, which you can use when creating the `DatabaseAuthenticationStrategy` object:

```scala
val repository = new ApiKeyRepository
override implicit val authenticationStrategy = new DatabaseAuthenticationStrategy(repository)
  ...
}
```

### Mixin the Authentication magic

Once you've created the `AuthenticationStrategy` object, mixin the `Authentication` Trait to your `Controller` and set the `authenticationStrategy` to your new configuration object:

```
class UserController(repository: ReactiveRepository[User, BSONObjectID])(override implicit val bindingModule: BindingModule, override implicit val tag: ClassTag[User], override implicit val objectIdConverter: String => BSONObjectID) extends RestController[User, BSONObjectID]("users", User.format, repository)[User, BSONObjectID] with Authentication {
  override implicit val authenticationStrategy = ConfigAuthStrategy
}
```

### API Key Management REST API

Respite provides a simple REST API to manage API tokens at run time:

      Method	Path	Body

        GET	<servlet>/tokens/

        DELETE	<servlet>/tokens/:key

        POST	<servlet>/tokens/ 	{"application" : "kickass", "key" : "pants", "description":"We sell awesome pants" }

## Metrics

  Visit the section Monitoring & Metrics for a detailed description of Respite's capabilities in the space.

`RestController` classes are already instrumented with the typed `MetricsRestSupport[T]` Trait, containing a default health check implementation. For other `Controller` classes, use the `MetricsSupport` Trait.

## Caching

As with metrics, `RestController` classes require a the `CachingRouteSupport` and non-`RestController` `Route`s should use `CachingSupport` Trait. However, unlike Metrics, caching is disabled by default.

### Creating Custom Cache entries

The caching DSL is fairly straightforward, wrapping a block with `cache(key)` will return a `Future[Any]`. The following example wraps the contents of a `POST` operation (something which is not automatically cached for obvious reasons):

```scala
  post("/foobar") {
    cache("es") {
      Future {
        logger.info("About to find all")
        repository.findAll
      }
    }
  }
```

### Expiring Cache Entries

The cache can be completely expired via the `clear` method on the `cache` property. A REST service also exists at `DELETE /cache/` and `DELETE /cache/:key`.

### Overriding caching TTLs

By default, responses are cached forever, unless the cache is invalidated by way of a `DELETE` or `POST` operation.If you'd like to change this behaviour, simply override the following properties of any class instrumented via `CachingSupport`.

```scala
  override val timeToLive = 300 seconds
  override val timeToIdle = 60 seconds
```

  NOTE: The Caching implementation uses the `scala.concurrent.duration` package for its unit of time declarations.

## Logging

Mixin `LoggingSupport` to access a Logback `logger` object with the standard methods. By default, this will be sent to `stdout` (see [logs](http://12factor.net/logs) for best practice on 12 factor apps) but can be easily [configured](http://logback.qos.ch/) to log to another location.

```scala
// Creates a route on "/logme" which will log to console on request
get("/logme") {
  logger.debug("This is a debug log on path `/logme`")
}
```

redpajama_set_name: RedPajamaGithub


text:
package com.graduate.system.wecat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.graduate.api.arrage.ArrageController;
import com.graduate.common.BaseController;
import com.graduate.common.BaseJsonData;
import com.graduate.common.WordService;
import com.graduate.system.arrage.model.Arrage;
import com.graduate.system.arrage.service.ArrageService;
import com.graduate.system.evaluate.model.Evaluate;
import com.graduate.system.evaluate.service.EvaluateService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static org.aspectj.weaver.tools.cache.SimpleCacheFactory.path;

/**
 * Created by konglinghai on 2017/5/25.
 */
@Controller
@RequestMapping("/wecat")
public class WecatController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(WecatController.class);

    @Autowired
    private ArrageService<Arrage> arrageService;

    @Autowired
    private EvaluateService<Evaluate> evaluateService;

    @Autowired
    private WordService wordService;

    @RequestMapping("/arrage/detail")
    @ResponseBody
    public BaseJsonData getArrageDetail(@RequestParam("id") Long id,@RequestParam("userId")Long userId){
        BaseJsonData data = new BaseJsonData();
        try {
            Arrage arrage = arrageService.findOne(id);
            List<Evaluate> evaluates = evaluateService.findEvaluateByArrageId(id);
            String evaluateContent ="";
            for(Evaluate evaluate :evaluates){
                if (evaluate.getCreator().equals(userId)) {
                    evaluateContent = evaluate.getContent();
                    break;
                }
            }
            HashMap<String,Object> result = new HashMap<>();
            result.put("arrage",arrage);
            result.put("evaluate",evaluateContent);
            return data.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
            return data.fail(e.getMessage());
        }
    }

    @RequestMapping("/evaluate/normal")
    @ResponseBody
    public BaseJsonData saveEvaluateNormal(@RequestParam("id")Long id,@RequestParam("userId")Long userId,@RequestBody String body){
        BaseJsonData data = new BaseJsonData();
        try{
            JSONObject object = JSON.parseObject(body);
            int normal0 = Integer.parseInt(object.getString("normal0"));
            int normal1 = Integer.parseInt(object.getString("normal1"));
            int normal2 = Integer.parseInt(object.getString("normal2"));
            int normal3 = Integer.parseInt(object.getString("normal3"));
            int normal4 = Integer.parseInt(object.getString("normal4"));
            int normal5 = Integer.parseInt(object.getString("normal5"));
            int normal6 = Integer.parseInt(object.getString("normal6"));
            int normal7 = Integer.parseInt(object.getString("normal7"));
            int grade = normal0+normal1+normal2+normal3+normal4+normal5+normal6+normal7;

            List<Evaluate> evaluates = evaluateService.findEvaluateByArrageId(id);
            Evaluate evaluate = null;
            for(Evaluate e :evaluates){
                if (e.getCreator().equals(userId)) {
                    evaluate = e;
                    break;
                }
            }

            //生成word文档
            String savePath = "";
            String saveName = "";
            if(evaluate == null){
                saveName = String.valueOf(new Date().getTime());
                evaluate = new Evaluate();
            }else{
                saveName = StringUtils.substringBefore(StringUtils.substringAfterLast(evaluate.getPath(),"\\"),".");
            }

            Arrage arrage = arrageService.findOne(id);
            savePath = wordService.fillNormalSuparvisorFile(arrage,object,saveName,String.valueOf(userId),grade);

            evaluate.setCreateTime(new Date());
            evaluate.setCreator(userId);
            evaluate.setArrageId(id);
            evaluate.setContent(body);
            evaluate.setPath(savePath);
            evaluate.setGrade(grade);
            evaluateService.save(evaluate);
            return data.ok();
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
            return data.fail(e.getMessage());
        }
    }

    @RequestMapping("/evaluate/chief")
    @ResponseBody
    public BaseJsonData saveEvaluateChief(@RequestParam("id")Long id,@RequestParam("userId")Long userId,@RequestBody String body){
        BaseJsonData data = new BaseJsonData();
        try{
            JSONObject object = JSON.parseObject(body);
            int chief0 = Integer.parseInt(object.getString("chief0"));

            List<Evaluate> evaluates = evaluateService.findEvaluateByArrageId(id);
            Evaluate evaluate = null;
            for(Evaluate e :evaluates){
                if (e.getCreator().equals(userId)) {
                    evaluate = e;
                    break;
                }
            }
            String savePath = "";
            //生成word文档
            String saveName = "";
            if(evaluate == null){
                saveName = String.valueOf(new Date().getTime());
                evaluate = new Evaluate();
            }else{
                saveName = StringUtils.substringBefore(StringUtils.substringAfterLast(evaluate.getPath(),"\\"),".");
            }
            Arrage arrage = arrageService.findOne(id);
            savePath = wordService.fillChiefSuparvisorFile(arrage,object,saveName);

            evaluate.setCreateTime(new Date());
            evaluate.setCreator(userId);
            evaluate.setArrageId(id);
            evaluate.setContent(body);
            evaluate.setPath(savePath);
            evaluate.setGrade(chief0);
            evaluateService.save(evaluate);

            return data.ok();
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
            return data.fail(e.getMessage());
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeComb.Models.WebAPI
{
    public class GroupChats : Base
    {
        public List<GroupChat> List { get; set; }
        public int PageCount { get; set; }
    }
    public class GroupChat
    {
        public int ID { get; set; }
        public DateTime Time { get; set; }
        public int UserID { get; set; }
        public string Nickname { get; set; }
        public string AvatarURL { get; set; }
        public string Message { get; set; }
        public int GroupID { get; set; }
    }
}


text:
import sys
import os.path
import time
from collections import defaultdict

# requires a custom version of Flask-Autodoc:
#   pip install git+https://github.com/lukeyeager/flask-autodoc.git
from flask.ext.autodoc import Autodoc

try:
    import digits
except ImportError:
    # Add path for DIGITS package
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import digits.config; digits.config.load_config()
from digits.webapp import app, _doc as doc

class DocGenerator(object):
    """
    Generates markdown for Flask routes
    """

    def __init__(self, autodoc,
            include_groups=None, exclude_groups=None):
        """
        Arguments:
        autodoc -- an Autodoc instance

        Keyword arguments:
        include_groups -- a list of groups to print
        exclude_groups -- a list of groups not to print
        """
        self.autodoc = autodoc
        self.include_groups = include_groups
        self.exclude_groups = exclude_groups
        self._handle = None

        # get list of groups
        group_names = defaultdict(int)
        for func, groups in self.autodoc.func_groups.iteritems():
            for group in groups:
                group_names[group] += 1

        first_groups = ['home', 'jobs', 'datasets', 'models']
        hidden_groups = ['all']
        other_groups = [g for g in sorted(group_names.keys())
                if g not in first_groups + hidden_groups]
        self._groups = first_groups + other_groups

    def generate(self, filename):
        """
        Writes the documentation to file
        """
        with open(os.path.join(
                    os.path.dirname(__file__),
                    filename), 'w') as self._handle:
            groups = []
            for group in self._groups:
                if (not self.include_groups or group in self.include_groups) and \
                        (not self.exclude_groups or group not in self.exclude_groups):
                    groups.append(group)

            self.print_header()
            self._print_toc(groups)
            for group in groups:
                self._print_group(group, print_header=(len(groups)>1))

    def w(self, line='', add_newline=True):
        """
        Writes a line to file
        """
        if add_newline:
            line = '%s\n' % line
        self._handle.write(line)

    def _print_header(self, header):
        """
        Print the document page header
        """
        pass

    def timestamp(self):
        """
        Returns a string which notes the current time
        """
        return time.strftime('*Generated %b %d, %Y*')

    def _print_toc(self, groups=None):
        """
        Print the table of contents
        """
        if groups is None:
            groups = self._groups

        if len(groups) <= 1:
            # No sense printing the TOC
            return

        self.w('### Table of Contents')
        self.w()
        for group in groups:
            self.w('* [%s](#%s)' % (group.capitalize(), group))
        self.w()

    def _print_group(self, group, print_header=True):
        """
        Print a group of routes
        """
        routes = self.get_routes(group)
        if not routes:
            return

        if print_header:
            self.w('## %s' % group.capitalize())
            self.w()

        for route in routes:
            self._print_route(route)

    def get_routes(self, group):
        """
        Get the routes for this group
        """
        return self.autodoc.generate(groups=group)

    def _print_route(self, route):
        """
        Print a route
        """
        self.w('### `%s`' % route['rule'])
        self.w()
        if route['docstring']:
            for line in route['docstring'].strip().split('\n'):
                self.w('> %s' % line.strip())
                self.w()
        self.w('Methods: ' + ', '.join(['**%s**' % m.upper() for m in
            sorted(route['methods']) if m not in ['HEAD', 'OPTIONS']]))
        self.w()
        if route['args'] and route['args'] != ['None']:
            args = []
            for arg in route['args']:
                args.append('`%s`' % arg)
                if route['defaults'] and arg in route['defaults']:
                    args[-1] = '%s (`%s`)' % (args[-1], route['defaults'][arg])
            self.w('Arguments: ' + ', '.join(args))
            self.w()
        if 'location' in route:
            # get location relative to digits root
            digits_root = os.path.dirname(
                    os.path.dirname(
                        os.path.normpath(digits.__file__)
                        )
                    )
            filename = os.path.normpath(route['location']['filename'])
            if filename.startswith(digits_root):
                filename = os.path.relpath(filename, digits_root).replace("\\","/")
                self.w('Location: [`%s`](%s)' % (
                    filename,
                    os.path.join('..', filename).replace("\\","/"),
                    ))
                self.w()

class ApiDocGenerator(DocGenerator):
    """
    Generates API.md
    """

    def __init__(self, *args, **kwargs):
        super(ApiDocGenerator, self).__init__(include_groups=['api'], *args, **kwargs)

    def print_header(self):
        text = """
# REST API

%s

DIGITS exposes its internal functionality through a REST API. You can access these endpoints by performing a GET or POST on the route, and a JSON object will be returned.

For more information about other routes used for the web interface, see [this page](FlaskRoutes.md).
""" % self.timestamp()
        self.w(text.strip())
        self.w()

    def get_routes(self, group):
        for route in self.autodoc.generate(groups=group):
            if '.json' in route['rule']:
                yield route

class FlaskRoutesDocGenerator(DocGenerator):
    """
    Generates FlaskRoutes.md
    """

    def __init__(self, *args, **kwargs):
        super(FlaskRoutesDocGenerator, self).__init__(exclude_groups=['api'], *args, **kwargs)

    def print_header(self):
        text = """
# Flask Routes

%s

Documentation on the various routes used internally for the web application.

These are all technically RESTful, but they return HTML pages. To get JSON responses, see [this page](API.md).
""" % self.timestamp()
        self.w(text.strip())
        self.w()

    def get_routes(self, group):
        for route in self.autodoc.generate(groups=group):
            if '.json' not in route['rule']:
                yield route

if __name__ == '__main__':
    with app.app_context():
        ApiDocGenerator(doc).generate('../docs/API.md')
        FlaskRoutesDocGenerator(doc).generate('../docs/FlaskRoutes.md')


text:
"""General utility functions

__author__ = Sasha Ouellet (www.sashaouellet.com)
__version__ = 1.0.0
__date__ = 11/30/17
"""

import re

def splitByCamelCase(word):
	"""Splits the input word by camel case

	'fooBar' --> ['foo', 'Bar']
	'FOOBar' --> ['FOO', 'Bar']

	Args:
		word (str): Input word to split

	Returns:
		list: The split word
	"""
	matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', word)

	return [m.group(0) for m in matches]

def convertToCamelCase(input, firstIsLowercase=False):
	"""Given an input string of words (separated by space), converts
	it back to camel case.

	'Foo Bar' (firstIsLowercase=False)  --> 'FooBar'
	'Foo Bar' (firstIsLowercase=True)   --> 'fooBar'
	'foo bar' (firstIsLowercase=False)  --> 'FooBar'

	Args:
	    input (str): The string of words to convert
	    firstIsLowercase (bool, optional): By default, title cases all words
	    	in the input string (i.e. 'foo bar' will become
	    	'FooBar' rather than 'fooBar'). If True, the first word is forced
	    	to become lowercase

	Returns:
	    str: The camelcased string
	"""
	words = input.split()

	for i, word in enumerate(words):
		if i == 0 and firstIsLowercase:
			words[0] = words[0].lower()
		else:
			words[i] = words[i].title()

	return ''.join(words)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>DirectionFinderAdapter</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="date" content="2018-04-23">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

SEARCH:
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package lejos.robotics

Class DirectionFinderAdapter

<map id="G" name="G">
<area shape="rect" id="node1_0" href="./Calibrate.html" title="lejos.robotics.Calibrate" alt="" coords="118,11,234,108"/>
<area shape="rect" id="node1" href="./Calibrate.html" title="<TABLE>" alt="" coords="107,5,245,113"/>
<area shape="rect" id="node2_1" href="./DirectionFinder.html" title="lejos.robotics.DirectionFinder" alt="" coords="16,167,197,264"/>
<area shape="rect" id="node2" href="./DirectionFinder.html" title="<TABLE>" alt="" coords="5,161,208,269"/>
<area shape="rect" id="node3_2" href="./DirectionFinderAdapter.html" title="lejos.robotics.DirectionFinderAdapter" alt="" coords="27,323,325,493"/>
<area shape="rect" id="node3" href="./DirectionFinderAdapter.html" title="<TABLE>" alt="" coords="17,317,335,499"/>
<area shape="rect" id="node4_3" href="./SampleProvider.html" title="lejos.robotics.SampleProvider" alt="" coords="57,552,295,649"/>
<area shape="rect" id="node4" href="./SampleProvider.html" title="<TABLE>" alt="" coords="46,547,306,655"/>
</map>

java.lang.Object

lejos.robotics.DirectionFinderAdapter

All Implemented Interfaces:

Calibrate, DirectionFinder

public class DirectionFinderAdapter
extends java.lang.Object
implements DirectionFinder

Field Summary

Fields

Modifier and Type
Field and Description

private Calibrate
calibrator

private SampleProvider
initialProvider

private SampleProvider
provider

private float[]
sample

Constructor Summary

Constructors

Constructor and Description

DirectionFinderAdapter(SampleProvider provider)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

float
getDegreesCartesian()

Compass readings increase clockwise from 0 to 360, but Cartesian
 coordinate systems increase counter-clockwise.

void
resetCartesianZero()

Changes the current direction the compass is facing into the zero
 angle.

void
startCalibration()

Starts calibration.

void
stopCalibration()

Ends calibration sequence.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

calibrator

private Calibrate calibrator

provider

private SampleProvider provider

initialProvider

private SampleProvider initialProvider

sample

private float[] sample

Constructor Detail

DirectionFinderAdapter

public DirectionFinderAdapter(SampleProvider provider)

Method Detail

getDegreesCartesian

public float getDegreesCartesian()

Description copied from interface: DirectionFinder

Compass readings increase clockwise from 0 to 360, but Cartesian
 coordinate systems increase counter-clockwise. This method returns
 the Cartesian compass reading. Also, the resetCartesianZero() method
 can be used to designate any direction as zero, rather than relying
 on North as being zero.

Specified by:

getDegreesCartesian in interface DirectionFinder

Returns:

Cartesian direction. Between 0 and 360, excluding 360. Values increase counter-clockwise.

startCalibration

public void startCalibration()

Description copied from interface: Calibrate

Starts calibration.
 Must call stopCalibration() when done.

Specified by:

startCalibration in interface Calibrate

stopCalibration

public void stopCalibration()

Description copied from interface: Calibrate

Ends calibration sequence.

Specified by:

stopCalibration in interface Calibrate

resetCartesianZero

public void resetCartesianZero()

Description copied from interface: DirectionFinder

Changes the current direction the compass is facing into the zero
 angle.

Specified by:

resetCartesianZero in interface DirectionFinder

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package uk.ac.soton.ecs.comp3204.l3;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.io.IOException;

import javax.swing.JPanel;

import org.openimaj.content.slideshow.Slide;
import org.openimaj.content.slideshow.SlideshowApplication;
import org.openimaj.data.dataset.VFSGroupDataset;
import org.openimaj.image.DisplayUtilities.ImageComponent;
import org.openimaj.image.FImage;
import org.openimaj.image.ImageUtilities;

import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider;
import uk.ac.soton.ecs.comp3204.utils.Utils;
import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;

/**
 * Visualise mean-centered face images
 *
 * @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
 *
 */
@Demonstration(title = "Mean-centred faces demo")
public class MeanCenteredFacesDemo implements Slide {

	@Override
	public Component getComponent(int width, int height) throws IOException {
		final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset();

		final FImage mean = dataset.getRandomInstance().fill(0f);
		for (final FImage i : dataset) {
			mean.addInplace(i);
		}
		mean.divideInplace(dataset.numInstances());

		final JPanel outer = new JPanel();
		outer.setOpaque(false);
		outer.setPreferredSize(new Dimension(width, height));
		outer.setLayout(new GridBagLayout());

		final JPanel base = new JPanel();
		base.setOpaque(false);
		base.setPreferredSize(new Dimension(width, height - 50));
		base.setLayout(new FlowLayout());

		for (int i = 0; i < 60; i++) {
			final FImage img = dataset.getRandomInstance().subtract(mean).normalise();
			final ImageComponent ic = new ImageComponent(true, false);
			ic.setAllowPanning(false);
			ic.setAllowZoom(false);
			ic.setShowPixelColours(false);
			ic.setShowXYPosition(false);
			ic.setImage(ImageUtilities.createBufferedImageForDisplay(img));
			base.add(ic);
		}
		outer.add(base);

		return outer;
	}

	@Override
	public void close() {
		// do nothing
	}

	public static void main(String[] args) throws IOException {
		new SlideshowApplication(new MeanCenteredFacesDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
	}
}


text:
import * as ReactDnd from "react-dnd";

export namespace NativeTypes {
    const FILE: string;
    const URL: string;
    const TEXT: string;
}
export function getEmptyImage(): any; // Image
export default class HTML5Backend implements ReactDnd.Backend {}


text:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include <arpa/inet.h>
#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#define LINE_LENGTH (1024)
#define BUFFER_SIZE (1<<16)
#define NUMBER_OF_CHANNELS (100)
#define NUMBER_OF_STREAMS (100)

#define DATA_CHANNEL_PPID_CONTROL   50
#define DATA_CHANNEL_PPID_DOMSTRING 51
#define DATA_CHANNEL_PPID_BINARY    52

/* As specified in the W3C specification */
#define DATA_CHANNEL_CONNECTING 1
#define DATA_CHANNEL_OPEN       2
#define DATA_CHANNEL_CLOSING    3
#define DATA_CHANNEL_CLOSED     4

#define DATA_CHANNEL_FLAGS_SEND_REQ 0x00000001
#define DATA_CHANNEL_FLAGS_SEND_ACK 0x00000002
#define DATA_CHANNEL_FLAGS_I_RESET  0x00000004
#define DATA_CHANNEL_FLAGS_O_RESET  0x00000008

struct channel {
	uint16_t sid;
	uint16_t pr_policy;
	uint32_t pr_value;
	uint8_t unordered;
	uint8_t type;
	uint16_t priority;
	char *label;
	char *protocol;
	uint8_t state;
	uint32_t flags;
};

struct peer_connection {
	struct channel channels[NUMBER_OF_CHANNELS];
	pthread_mutex_t mutex;
	int fd;
	int client;
} peer_connection;

#define DATA_CHANNEL_ACK_MESSAGE_TYPE           2
#define DATA_CHANNEL_OPEN_MESSAGE_TYPE          3

#define DATA_CHANNEL_RELIABLE                          0x00
#define DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT           0x01
#define DATA_CHANNEL_PARTIAL_RELIABLE_TIMED            0x02
#define DATA_CHANNEL_RELIABLE_UNORDERED                0x80
#define DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED 0x81
#define DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED  0x82
#define DATA_CHANNEL_UNORDERED                         0x80

struct rtcweb_datachannel_open {
	uint8_t message_type; /* DATA_CHANNEL_OPEN */
	uint8_t channel_type;
	uint16_t priority;
	uint32_t reliability_parameter;
	uint16_t label_length;
	uint16_t protocol_length;
	char label_and_protocol[];
} __attribute__((packed));

struct rtcweb_datachannel_ack {
	uint8_t message_type; /* DATA_CHANNEL_ACK */
} __attribute__((packed));

static void
init_peer_connection(struct peer_connection *pc, int fd, int client)
{
	uint32_t i;
	struct channel *channel;

	for (i = 0; i < NUMBER_OF_CHANNELS; i++) {
		channel = &(pc->channels[i]);
		channel->sid = i;
		channel->pr_policy = SCTP_PR_SCTP_NONE;
		channel->pr_value = 0;
		channel->unordered = 0;
		channel->type = 0xff;
		channel->priority = 0;
		channel->label = NULL;
		channel->protocol = NULL;
		channel->state = DATA_CHANNEL_CLOSED;
		channel->flags = 0;
	}
	pc->fd = fd;
	pc->client = client;
	pthread_mutex_init(&pc->mutex, NULL);
}

static void
lock_peer_connection(struct peer_connection *pc)
{
	pthread_mutex_lock(&pc->mutex);
}

static void
unlock_peer_connection(struct peer_connection *pc)
{
	pthread_mutex_unlock(&pc->mutex);
}

static struct channel *
find_channel_by_id(struct peer_connection *pc, uint16_t id)
{
	if (id < NUMBER_OF_STREAMS) {
		return (&(pc->channels[id]));
	} else {
		return (NULL);
	}
}

static struct channel *
find_free_channel(struct peer_connection *pc)
{
	uint32_t i;

	for (i = pc->client ? 0 : 1; i < NUMBER_OF_CHANNELS; i += 2) {
		if (pc->channels[i].state == DATA_CHANNEL_CLOSED) {
			break;
		}
	}
	if (i >= NUMBER_OF_CHANNELS) {
		return (NULL);
	} else {
		return (&(pc->channels[i]));
	}
}

static int
send_data_channel_open_message(int fd,
                               uint16_t sid,
                               uint8_t channel_type,
                               uint16_t priority,
                               uint32_t reliability_parameter,
                               char *label,
                               char *protocol)
{
	struct rtcweb_datachannel_open dc_open;
	struct sctp_sndinfo sndinfo;
	struct iovec iov[3];

	assert(label != NULL);
	assert(strlen(label) < 65536);
	assert(protocol != NULL);
	assert(strlen(protocol) < 65536);
	dc_open.message_type = DATA_CHANNEL_OPEN_MESSAGE_TYPE;
	dc_open.channel_type = channel_type;
	dc_open.priority = htons(priority);
	dc_open.reliability_parameter = htonl(reliability_parameter);
	dc_open.label_length = htons((uint16_t)strlen(label));
	dc_open.protocol_length = htons((uint16_t)strlen(protocol));
	iov[0].iov_base = &dc_open;
	iov[0].iov_len = sizeof(struct rtcweb_datachannel_open);
	iov[1].iov_base = label;
	iov[1].iov_len = strlen(label);
	iov[2].iov_base = protocol;
	iov[2].iov_len = strlen(protocol);
	memset(&sndinfo, 0, sizeof(struct sctp_sndinfo));
	sndinfo.snd_sid = sid;
	sndinfo.snd_flags = SCTP_EOR;
	sndinfo.snd_ppid = htonl(DATA_CHANNEL_PPID_CONTROL);
	if (sctp_sendv(fd,
	               iov, 3,
	               NULL, 0,
	               &sndinfo, (socklen_t)sizeof(struct sctp_sndinfo),
	               SCTP_SENDV_SNDINFO, 0) < 0) {
		perror("sctp_sendv");
		return (0);
	} else {
		return (1);
	}
}

static int
send_data_channel_ack_message(int fd,
                              uint16_t sid)
{
	struct rtcweb_datachannel_ack dc_ack;
	struct sctp_sndinfo sndinfo;
	struct iovec iov[1];

	dc_ack.message_type = DATA_CHANNEL_ACK_MESSAGE_TYPE;
	iov[0].iov_base = &dc_ack;
	iov[0].iov_len = sizeof(struct rtcweb_datachannel_ack);
	memset(&sndinfo, 0, sizeof(struct sctp_sndinfo));
	sndinfo.snd_sid = sid;
	sndinfo.snd_flags = SCTP_EOR;
	sndinfo.snd_ppid = htonl(DATA_CHANNEL_PPID_CONTROL);
	if (sctp_sendv(fd,
	               iov, 1,
	               NULL, 0,
	               &sndinfo, (socklen_t)sizeof(struct sctp_sndinfo),
	               SCTP_SENDV_SNDINFO, 0) < 0) {
		perror("sctp_sendv");
		return (0);
	} else {
		return (1);
	}
}

static void
send_deferred_messages(struct peer_connection *pc)
{
	uint32_t i;
	struct channel *channel;

	for (i = 0; i < NUMBER_OF_CHANNELS; i++) {
		channel = &(pc->channels[i]);
		if (channel->flags & DATA_CHANNEL_FLAGS_SEND_REQ) {
			if (send_data_channel_open_message(pc->fd, channel->sid, channel->type, channel->priority, channel->pr_value, channel->label, channel->protocol)) {
				channel->flags &= ~DATA_CHANNEL_FLAGS_SEND_REQ;
			} else {
				if (errno != EAGAIN) {
					/* XXX: error handling */
				}
			}
		}
		if (channel->flags & DATA_CHANNEL_FLAGS_SEND_ACK) {
			if (send_data_channel_ack_message(pc->fd, channel->sid)) {
				channel->flags &= ~DATA_CHANNEL_FLAGS_SEND_ACK;
			} else {
				if (errno != EAGAIN) {
					/* XXX: error handling */
				}
			}
		}
	}
	return;
}

static struct channel *
open_channel(struct peer_connection *pc,
             uint8_t unordered,
             uint16_t pr_policy, uint32_t pr_value,
             uint16_t priority,
             char *label,
             char *protocol)
{
	struct channel *channel;

	if ((pr_policy != SCTP_PR_SCTP_NONE) &&
	    (pr_policy != SCTP_PR_SCTP_RTX) &&
	    (pr_policy != SCTP_PR_SCTP_TTL)) {
		return (NULL);
	}
	if ((unordered != 0) && (unordered != 1)) {
		return (NULL);
	}
	if ((pr_policy == SCTP_PR_SCTP_NONE) && (pr_value != 0)) {
		return (NULL);
	}
	if ((label == NULL) || (protocol == NULL)) {
		return (NULL);
	}
	if ((strlen(label) > 65535) || (strlen(protocol) > 65535)) {
		return (NULL);
	}
	if ((channel = find_free_channel(pc)) == NULL) {
		return (NULL);
	}
	channel->pr_policy = pr_policy;
	channel->pr_value = pr_value;
	channel->unordered = unordered;
	switch (pr_policy) {
	case SCTP_PR_SCTP_NONE:
		channel->type = DATA_CHANNEL_RELIABLE;
		break;
	case SCTP_PR_SCTP_RTX:
		channel->type = DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT;
		break;
	case SCTP_PR_SCTP_TTL:
		channel->type = DATA_CHANNEL_PARTIAL_RELIABLE_TIMED;
		break;
	}
	if (unordered) {
		channel->type |= DATA_CHANNEL_UNORDERED;
	}
	channel->priority = priority;
	channel->label = strdup(label);
	channel->protocol = strdup(protocol);
	channel->state = DATA_CHANNEL_CONNECTING;
	channel->flags = 0;
	if (send_data_channel_open_message(pc->fd, channel->sid, channel->type, channel->priority, channel->pr_value, channel->label, channel->protocol)) {
		channel->state = DATA_CHANNEL_CONNECTING;
	} else {
		if (errno == EAGAIN) {
			channel->flags |= DATA_CHANNEL_FLAGS_SEND_REQ;
		} else {
			channel->pr_policy = SCTP_PR_SCTP_NONE;
			channel->pr_value = 0;
			channel->unordered = 0;
			channel->type = 0xff;
			channel->priority = 0;
			free(channel->label);
			channel->label = NULL;
			free(channel->protocol);
			channel->protocol = NULL;
			channel->state = DATA_CHANNEL_CLOSED;
			channel->flags = 0;
			channel = NULL;
		}
	}
	return (channel);
}

static int
send_user_message(struct peer_connection *pc, struct channel *channel, char *message, size_t length)
{
	struct sctp_sendv_spa spa;
	struct iovec iov;

	if (channel == NULL) {
		return (0);
	}
	if ((channel->state != DATA_CHANNEL_OPEN) &&
	    (channel->state != DATA_CHANNEL_CONNECTING)) {
		/* XXX: What to do in other states */
		return (0);
	}

	iov.iov_base = message;
	iov.iov_len = length;
	memset(&spa, 0, sizeof(struct sctp_sendv_spa));
	spa.sendv_sndinfo.snd_sid = channel->sid;
	if ((channel->state == DATA_CHANNEL_OPEN) &&
	    (channel->unordered)) {
		spa.sendv_sndinfo.snd_flags = SCTP_EOR | SCTP_UNORDERED;
	} else {
		spa.sendv_sndinfo.snd_flags = SCTP_EOR;
	}
	spa.sendv_sndinfo.snd_ppid = htonl(DATA_CHANNEL_PPID_DOMSTRING);
	spa.sendv_flags = SCTP_SEND_SNDINFO_VALID;
	if ((channel->pr_policy == SCTP_PR_SCTP_TTL) ||
	    (channel->pr_policy == SCTP_PR_SCTP_RTX)) {
		spa.sendv_prinfo.pr_policy = channel->pr_policy;
		spa.sendv_prinfo.pr_value = channel->pr_value;
		spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
	}
	if (sctp_sendv(pc->fd,
	               &iov, 1,
	               NULL, 0,
	               &spa, (socklen_t)sizeof(struct sctp_sendv_spa),
	               SCTP_SENDV_SPA, 0) < 0) {
		perror("sctp_sendv");
		return (0);
	} else {
		return (1);
	}
}

static void
reset_outgoing_stream(struct peer_connection *pc, uint16_t sid)
{
	struct sctp_reset_streams *srs;
	size_t len;

	len = sizeof(struct sctp_reset_streams) + sizeof(uint16_t);
	srs = (struct sctp_reset_streams *)malloc(len);
	if (srs == NULL) {
		return;
	}
	memset(srs, 0, len);
	srs->srs_flags = SCTP_STREAM_RESET_OUTGOING;
	srs->srs_number_streams = 1;
	srs->srs_stream_list[0] = sid;
	if (setsockopt(pc->fd, IPPROTO_SCTP, SCTP_RESET_STREAMS, srs, (socklen_t)len) < 0) {
		perror("setsockopt");
		printf("reset_outgoing_stream: Can't reset stream %u.\n", sid);
	}
	free(srs);
}

static void
close_channel(struct peer_connection *pc, struct channel *channel)
{
	if (channel == NULL) {
		return;
	}
	if (channel->state != DATA_CHANNEL_OPEN) {
		return;
	}
	reset_outgoing_stream(pc, channel->sid);
	channel->state = DATA_CHANNEL_CLOSING;
	return;
}

static void
handle_open_ack_message(struct peer_connection *pc,
                        struct rtcweb_datachannel_ack *ack,
                        size_t length, uint16_t sid)
{
	struct channel *channel;

	channel = find_channel_by_id(pc, sid);
	if (channel == NULL) {
		/* XXX: some error handling */
		return;
	}
	if (channel->state == DATA_CHANNEL_OPEN) {
		return;
	}
	if (channel->state != DATA_CHANNEL_CONNECTING) {
		/* XXX: error handling */
		return;
	}
	channel->state = DATA_CHANNEL_OPEN;
	return;
}

static void
handle_open_request_message(struct peer_connection *pc,
                            struct rtcweb_datachannel_open *dc_open,
                            size_t length,
                            uint16_t sid)
{
	struct channel *channel;
	uint16_t label_length;
	uint16_t protocol_length;

	label_length = ntohs(dc_open->label_length);
	protocol_length = ntohs(dc_open->protocol_length);
	if (sizeof(struct rtcweb_datachannel_open) + label_length + protocol_length != length) {
		printf("handle_open_request_message: invalid packet.\n");
	}
	if ((channel = find_channel_by_id(pc, sid)) == NULL) {
		printf("handle_open_request_message: Can't find channel for id = %u.\n",
		       sid);
		/* XXX: some error handling */
		return;
	}
	if (channel->state != DATA_CHANNEL_CLOSED) {
		printf("handle_open_request_message: channel for id = %u not in CLOSED (state = %u).\n",
		       sid, channel->state);
		/* XXX: some error handling */
		return;
	}
	channel->type = dc_open->channel_type;
	switch (dc_open->channel_type) {
	case DATA_CHANNEL_RELIABLE:
		channel->pr_policy = SCTP_PR_SCTP_NONE;
		channel->pr_value = ntohl(dc_open->reliability_parameter);
		channel->unordered = 0;
		break;
	case DATA_CHANNEL_RELIABLE_UNORDERED:
		channel->pr_policy = SCTP_PR_SCTP_NONE;
		channel->pr_value = ntohl(dc_open->reliability_parameter);
		channel->unordered = 1;
		break;
	case DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT:
		channel->pr_policy = SCTP_PR_SCTP_RTX;
		channel->pr_value = ntohl(dc_open->reliability_parameter);
		channel->unordered = 0;
		break;
	case DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED:
		channel->pr_policy = SCTP_PR_SCTP_RTX;
		channel->pr_value = ntohl(dc_open->reliability_parameter);
		channel->unordered = 1;
		break;
	case DATA_CHANNEL_PARTIAL_RELIABLE_TIMED:
		channel->pr_policy = SCTP_PR_SCTP_TTL;
		channel->pr_value = ntohl(dc_open->reliability_parameter);
		channel->unordered = 0;
		break;
	case DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED:
		channel->pr_policy = SCTP_PR_SCTP_TTL;
		channel->pr_value = ntohl(dc_open->reliability_parameter);
		channel->unordered = 1;
		break;
	default:
		/* XXX error handling */
		break;
	}
	channel->type = dc_open->channel_type;
	channel->priority = ntohs(dc_open->priority);
	channel->label = malloc((size_t)label_length + 1);
	memcpy(channel->label, dc_open->label_and_protocol, label_length);
	channel->label[label_length] = '\0';
	channel->protocol = malloc((size_t)protocol_length + 1);
	memcpy(channel->protocol, dc_open->label_and_protocol + label_length, protocol_length);
	channel->label[protocol_length] = '\0';
	channel->state = DATA_CHANNEL_OPEN;
	channel->flags = 0;
	if (send_data_channel_ack_message(pc->fd, sid) == 0) {
		if (errno == EAGAIN) {
			channel->flags |= DATA_CHANNEL_FLAGS_SEND_ACK;
		} else {
			/* XXX error handling*/
		}
	}
}

static void
handle_unknown_message(char *msg, size_t length, uint16_t i_stream)
{
	/* XXX: Send an error message */
	return;
}

static void
handle_data_message(struct peer_connection *pc,
                    char *buffer, size_t length, uint16_t sid)
{
	struct channel *channel;

	channel = find_channel_by_id(pc, sid);
	if (channel == NULL) {
		/* XXX: Some error handling */
		return;
	}
	if (channel->state == DATA_CHANNEL_CONNECTING) {
		/* Implicit ACK */
		channel->state = DATA_CHANNEL_OPEN;
	}
	if (channel->state != DATA_CHANNEL_OPEN) {
		/* XXX: What about other states? */
		/* XXX: Some error handling */
		return;
	} else {
		/* Assuming DATA_CHANNEL_PPID_DOMSTRING */
		/* XXX: Protect for non 0 terminated buffer */
		printf("Message received of length %lu on channel with id %d: %.*s\n",
		       length, channel->sid, (int)length, buffer);
	}
	return;
}

static void
handle_message(struct peer_connection *pc, char *buffer, size_t length, uint32_t ppid, uint16_t sid)
{
	struct rtcweb_datachannel_open *dc_open;
	struct rtcweb_datachannel_ack *dc_ack;
	uint8_t type;

	switch (ppid) {
	case DATA_CHANNEL_PPID_CONTROL:
		if (length < sizeof(uint8_t)) {
			return;
		}
		type = *(uint8_t *)buffer;
		switch (type) {
		case DATA_CHANNEL_ACK_MESSAGE_TYPE:
			if (length < sizeof(struct rtcweb_datachannel_ack)) {
				/* XXX: error handling? */
				return;
			}
			dc_ack = (struct rtcweb_datachannel_ack *)buffer;
			handle_open_ack_message(pc, dc_ack, length, sid);
			break;
		case DATA_CHANNEL_OPEN_MESSAGE_TYPE:
			if (length < sizeof(struct rtcweb_datachannel_open)) {
				/* XXX: error handling? */
				return;
			}
			dc_open = (struct rtcweb_datachannel_open *)buffer;
			handle_open_request_message(pc, dc_open, length, sid);
			break;
		default:
			handle_unknown_message(buffer, length, sid);
			break;
		}
		break;
	case DATA_CHANNEL_PPID_DOMSTRING:
	case DATA_CHANNEL_PPID_BINARY:
		handle_data_message(pc, buffer, length, sid);
		break;
	default:
		printf("Message of length %lu, PPID %u on stream %u received.\n",
		       length, ppid, sid);
		break;
	}
}

static void
handle_association_change_event(struct sctp_assoc_change *sac)
{
	unsigned int i, n;

	printf("Association change ");
	switch (sac->sac_state) {
	case SCTP_COMM_UP:
		printf("SCTP_COMM_UP");
		break;
	case SCTP_COMM_LOST:
		printf("SCTP_COMM_LOST");
		break;
	case SCTP_RESTART:
		printf("SCTP_RESTART");
		break;
	case SCTP_SHUTDOWN_COMP:
		printf("SCTP_SHUTDOWN_COMP");
		break;
	case SCTP_CANT_STR_ASSOC:
		printf("SCTP_CANT_STR_ASSOC");
		break;
	default:
		printf("UNKNOWN");
		break;
	}
	printf(", streams (in/out) = (%u/%u)",
	       sac->sac_inbound_streams, sac->sac_outbound_streams);
	n = sac->sac_length - sizeof(struct sctp_assoc_change);
	if (((sac->sac_state == SCTP_COMM_UP) ||
	     (sac->sac_state == SCTP_RESTART)) && (n > 0)) {
		printf(", supports");
		for (i = 0; i < n; i++) {
			switch (sac->sac_info[i]) {
			case SCTP_ASSOC_SUPPORTS_PR:
				printf(" PR");
				break;
			case SCTP_ASSOC_SUPPORTS_AUTH:
				printf(" AUTH");
				break;
			case SCTP_ASSOC_SUPPORTS_ASCONF:
				printf(" ASCONF");
				break;
			case SCTP_ASSOC_SUPPORTS_MULTIBUF:
				printf(" MULTIBUF");
				break;
			case SCTP_ASSOC_SUPPORTS_RE_CONFIG:
				printf(" RE-CONFIG");
				break;
			default:
				printf(" UNKNOWN(0x%02x)", sac->sac_info[i]);
				break;
			}
		}
	} else if (((sac->sac_state == SCTP_COMM_LOST) ||
	            (sac->sac_state == SCTP_CANT_STR_ASSOC)) && (n > 0)) {
		printf(", ABORT =");
		for (i = 0; i < n; i++) {
			printf(" 0x%02x", sac->sac_info[i]);
		}
	}
	printf(".\n");
	if ((sac->sac_state == SCTP_CANT_STR_ASSOC) ||
	    (sac->sac_state == SCTP_SHUTDOWN_COMP) ||
	    (sac->sac_state == SCTP_COMM_LOST)) {
		exit(0);
	}
	return;
}

static void
handle_peer_address_change_event(struct sctp_paddr_change *spc)
{
	char addr_buf[INET6_ADDRSTRLEN];
	const char *addr;
	struct sockaddr_in *sin;
	struct sockaddr_in6 *sin6;

	switch (spc->spc_aaddr.ss_family) {
	case AF_INET:
		sin = (struct sockaddr_in *)&spc->spc_aaddr;
		addr = inet_ntop(AF_INET, &sin->sin_addr, addr_buf, INET6_ADDRSTRLEN);
		break;
	case AF_INET6:
		sin6 = (struct sockaddr_in6 *)&spc->spc_aaddr;
		addr = inet_ntop(AF_INET6, &sin6->sin6_addr, addr_buf, INET6_ADDRSTRLEN);
		break;
	default:
		break;
	}
	printf("Peer address %s is now ", addr);
	switch (spc->spc_state) {
	case SCTP_ADDR_AVAILABLE:
		printf("SCTP_ADDR_AVAILABLE");
		break;
	case SCTP_ADDR_UNREACHABLE:
		printf("SCTP_ADDR_UNREACHABLE");
		break;
	case SCTP_ADDR_REMOVED:
		printf("SCTP_ADDR_REMOVED");
		break;
	case SCTP_ADDR_ADDED:
		printf("SCTP_ADDR_ADDED");
		break;
	case SCTP_ADDR_MADE_PRIM:
		printf("SCTP_ADDR_MADE_PRIM");
		break;
	case SCTP_ADDR_CONFIRMED:
		printf("SCTP_ADDR_CONFIRMED");
		break;
	default:
		printf("UNKNOWN");
		break;
	}
	printf(" (error = 0x%08x).\n", spc->spc_error);
	return;
}

static void
handle_adaptation_indication(struct sctp_adaptation_event *sai)
{
	printf("Adaptation indication: %x.\n", sai-> sai_adaptation_ind);
	return;
}

static void
handle_shutdown_event(struct sctp_shutdown_event *sse)
{
	printf("Shutdown event.\n");
	/* XXX: notify all channels. */
	return;
}

static void
handle_stream_reset_event(struct peer_connection *pc, struct sctp_stream_reset_event *strrst)
{
	uint32_t n, i;
	struct channel *channel;

	n = (strrst->strreset_length - sizeof(struct sctp_stream_reset_event)) / sizeof(uint16_t);
	printf("Stream reset event: flags = %x, ", strrst->strreset_flags);
	if (strrst->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
		if (strrst->strreset_flags & SCTP_STREAM_RESET_OUTGOING_SSN) {
			printf("incoming/");
		}
		printf("incoming ");
	}
	if (strrst->strreset_flags & SCTP_STREAM_RESET_OUTGOING_SSN) {
		printf("outgoing ");
	}
	printf("stream ids = ");
	for (i = 0; i < n; i++) {
		if (i > 0) {
			printf(", ");
		}
		printf("%d", strrst->strreset_stream_list[i]);
	}
	printf(".\n");
	if (!(strrst->strreset_flags & SCTP_STREAM_RESET_DENIED) &&
	    !(strrst->strreset_flags & SCTP_STREAM_RESET_FAILED)) {
		for (i = 0; i < n; i++) {
			channel = find_channel_by_id(pc, strrst->strreset_stream_list[i]);
			if (channel == NULL) {
				printf("handle_stream_reset_event: channel not found for id = %u.\n", strrst->strreset_stream_list[i]);
				continue;
			}
			if (strrst->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
				if ((channel->flags & DATA_CHANNEL_FLAGS_O_RESET) == 0) {
					reset_outgoing_stream(pc, channel->sid);
				}
				channel->flags |= DATA_CHANNEL_FLAGS_I_RESET;
			}
			if (strrst->strreset_flags & SCTP_STREAM_RESET_OUTGOING_SSN) {
				channel->flags |= DATA_CHANNEL_FLAGS_O_RESET;
			}
			if ((channel->flags & DATA_CHANNEL_FLAGS_I_RESET) &&
			    (channel->flags & DATA_CHANNEL_FLAGS_O_RESET)) {
				channel->pr_policy = SCTP_PR_SCTP_NONE;
				channel->pr_value = 0;
				channel->unordered = 0;
				channel->type = 0xff;
				channel->priority = 0;
				free(channel->label);
				channel->label = NULL;
				free(channel->protocol);
				channel->protocol = NULL;
				channel->state = DATA_CHANNEL_CLOSED;
				channel->flags = 0;
			}
		}
	}
	return;
}

static void
handle_remote_error_event(struct sctp_remote_error *sre)
{
	size_t i, n;

	n = sre->sre_length - sizeof(struct sctp_remote_error);
	printf("Remote Error (error = 0x%04x): ", sre->sre_error);
	for (i = 0; i < n; i++) {
		printf(" 0x%02x", sre-> sre_data[i]);
	}
	printf(".\n");
	return;
}

static void
handle_send_failed_event(struct sctp_send_failed_event *ssfe)
{
	size_t i, n;

	if (ssfe->ssfe_flags & SCTP_DATA_UNSENT) {
		printf("Unsent ");
	}
	if (ssfe->ssfe_flags & SCTP_DATA_SENT) {
		printf("Sent ");
	}
	if (ssfe->ssfe_flags & ~(SCTP_DATA_SENT | SCTP_DATA_UNSENT)) {
		printf("(flags = %x) ", ssfe->ssfe_flags);
	}
	printf("message with PPID = %d, SID = %d, flags: 0x%04x due to error = 0x%08x",
	       ntohl(ssfe->ssfe_info.snd_ppid), ssfe->ssfe_info.snd_sid,
	       ssfe->ssfe_info.snd_flags, ssfe->ssfe_error);
	n = ssfe->ssfe_length - sizeof(struct sctp_send_failed_event);
	for (i = 0; i < n; i++) {
		printf(" 0x%02x", ssfe->ssfe_data[i]);
	}
	printf(".\n");
	return;
}

static void
handle_notification(struct peer_connection *pc, union sctp_notification *notif, size_t n)
{
	if (notif->sn_header.sn_length != (uint32_t)n) {
		return;
	}
	switch (notif->sn_header.sn_type) {
	case SCTP_ASSOC_CHANGE:
		handle_association_change_event(&(notif->sn_assoc_change));
		break;
	case SCTP_PEER_ADDR_CHANGE:
		handle_peer_address_change_event(&(notif->sn_paddr_change));
		break;
	case SCTP_REMOTE_ERROR:
		handle_remote_error_event(&(notif->sn_remote_error));
		break;
	case SCTP_SHUTDOWN_EVENT:
		handle_shutdown_event(&(notif->sn_shutdown_event));
		break;
	case SCTP_ADAPTATION_INDICATION:
		handle_adaptation_indication(&(notif->sn_adaptation_event));
		break;
	case SCTP_PARTIAL_DELIVERY_EVENT:
		break;
	case SCTP_AUTHENTICATION_EVENT:
		break;
	case SCTP_SENDER_DRY_EVENT:
		break;
	case SCTP_NOTIFICATIONS_STOPPED_EVENT:
		break;
	case SCTP_SEND_FAILED_EVENT:
		handle_send_failed_event(&(notif->sn_send_failed_event));
		break;
	case SCTP_STREAM_RESET_EVENT:
		handle_stream_reset_event(pc, &(notif->sn_strreset_event));
		send_deferred_messages(pc);
		break;
	case SCTP_ASSOC_RESET_EVENT:
		break;
	case SCTP_STREAM_CHANGE_EVENT:
		break;
	default:
		break;
	}
}

static void
print_status(struct peer_connection *pc)
{
	struct sctp_status status;
	socklen_t len;
	uint32_t i;
	struct channel *channel;

	len = (socklen_t)sizeof(struct sctp_status);
	if (getsockopt(pc->fd, IPPROTO_SCTP, SCTP_STATUS, &status, &len) < 0) {
		perror("getsockopt");
		return;
	}
	printf("Association state: ");
	switch (status.sstat_state) {
	case SCTP_CLOSED:
		printf("CLOSED\n");
		break;
	case SCTP_BOUND:
		printf("BOUND\n");
		break;
	case SCTP_LISTEN:
		printf("LISTEN\n");
		break;
	case SCTP_COOKIE_WAIT:
		printf("COOKIE_WAIT\n");
		break;
	case SCTP_COOKIE_ECHOED:
		printf("COOKIE_ECHOED\n");
		break;
	case SCTP_ESTABLISHED:
		printf("ESTABLISHED\n");
		break;
	case SCTP_SHUTDOWN_PENDING:
		printf("SHUTDOWN_PENDING\n");
		break;
	case SCTP_SHUTDOWN_SENT:
		printf("SHUTDOWN_SENT\n");
		break;
	case SCTP_SHUTDOWN_RECEIVED:
		printf("SHUTDOWN_RECEIVED\n");
		break;
	case SCTP_SHUTDOWN_ACK_SENT:
		printf("SHUTDOWN_ACK_SENT\n");
		break;
	default:
		printf("UNKNOWN\n");
		break;
	}
	printf("Number of streams (i/o) = (%u/%u)\n",
	       status.sstat_instrms, status.sstat_outstrms);
	for (i = 0; i < NUMBER_OF_CHANNELS; i++) {
		channel = &(pc->channels[i]);
		if (channel->state == DATA_CHANNEL_CLOSED) {
			continue;
		}
		printf("Channel with id = %u: state ", channel->sid);
		switch (channel->state) {
		case DATA_CHANNEL_CLOSED:
			printf("CLOSED");
			break;
		case DATA_CHANNEL_CONNECTING:
			printf("CONNECTING");
			break;
		case DATA_CHANNEL_OPEN:
			printf("OPEN");
			break;
		case DATA_CHANNEL_CLOSING:
			printf("CLOSING");
			break;
		default:
			printf("UNKNOWN(%d)", channel->state);
			break;
		}
		printf(", ");
		printf("type ");
		switch (channel->type) {
		case DATA_CHANNEL_RELIABLE:
			printf("DATA_CHANNEL_RELIABLE");
			break;
		case DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT:
			printf("DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT");
			break;
		case DATA_CHANNEL_PARTIAL_RELIABLE_TIMED:
			printf("DATA_CHANNEL_PARTIAL_RELIABLE_TIMED");
			break;
		case DATA_CHANNEL_RELIABLE_UNORDERED:
			printf("DATA_CHANNEL_RELIABLE_UNORDERED");
			break;
		case DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED:
			printf("DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED");
			break;
		case DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED:
			printf("DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED");
			break;
		default:
			printf("%u.\n", channel->type);
			break;
		}
		printf(", ");
		if (channel->unordered) {
			printf("unordered, ");
		} else {
			printf("ordered, ");
		}
		printf("priority %u, ", channel->priority);
		switch (channel->pr_policy) {
		case SCTP_PR_SCTP_NONE:
			printf("reliable.\n");
			break;
		case SCTP_PR_SCTP_TTL:
			printf("unreliable (timeout %ums).\n", channel->pr_value);
			break;
		case SCTP_PR_SCTP_RTX:
			printf("unreliable (max. %u rtx).\n", channel->pr_value);
			break;
		default:
			printf("unkown policy %u.\n", channel->pr_policy);
			break;
		}
	}
}

static void *
handle_messages(void *arg)
{
	struct peer_connection *pc;
	struct iovec iov;
	struct sctp_rcvinfo rcvinfo;
	socklen_t infolen;
	unsigned int infotype;
	ssize_t n;
	int flags;
	char buffer[BUFFER_SIZE];

	pc = (struct peer_connection *)arg;
	for (;;) {
		iov.iov_base = buffer;
		iov.iov_len = BUFFER_SIZE;
		memset(&rcvinfo, 0, sizeof(struct sctp_rcvinfo));
		infolen = sizeof(struct sctp_rcvinfo);
		infotype = SCTP_RECVV_NOINFO;
		flags = 0;
		n = sctp_recvv(pc->fd, &iov, 1, NULL, NULL, &rcvinfo, &infolen, &infotype, &flags);
		if (n <= 0) {
			break;
		}
		lock_peer_connection(pc);
		if (flags & MSG_NOTIFICATION) {
			handle_notification(pc, (union sctp_notification *)buffer, n);
		} else {
			if (infotype  == SCTP_RECVV_RCVINFO) {
				handle_message(pc, buffer, n, ntohl(rcvinfo.rcv_ppid), rcvinfo.rcv_sid);
			} else {
				unlock_peer_connection(pc);
				break;
			}
		}
		unlock_peer_connection(pc);
	}
	return (NULL);
}

int
main(int argc, char *argv[])
{
	int fd;
	struct sockaddr_in addr;
	socklen_t addr_len;
	char line[LINE_LENGTH + 1];
	unsigned int unordered, policy, value, priority, id, seconds;
	unsigned int i;
	struct channel *channel;
	const int on = 1;
	struct sctp_assoc_value av;
	struct sctp_event event;
	pthread_t tid;
	struct sctp_initmsg initmsg;
	int client;
	uint16_t event_types[] = {SCTP_ASSOC_CHANGE,
	                          SCTP_PEER_ADDR_CHANGE,
	                          SCTP_REMOTE_ERROR,
	                          SCTP_SHUTDOWN_EVENT,
	                          SCTP_ADAPTATION_INDICATION,
	                          SCTP_SEND_FAILED_EVENT,
	                          SCTP_STREAM_RESET_EVENT,
	                          SCTP_STREAM_CHANGE_EVENT};

	if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP)) < 0) {
		perror("socket");
	}
	if (setsockopt(fd, IPPROTO_SCTP, SCTP_RECVRCVINFO, &on, sizeof(int)) < 0) {
		perror("setsockopt SCTP_RECVRCVINFO");
	}
	if (setsockopt(fd, IPPROTO_SCTP, SCTP_EXPLICIT_EOR, &on, sizeof(int)) < 0) {
		perror("setsockopt SCTP_EXPLICIT_EOR");
	}
	/* Disable the Explicit Congestion Notification extension */
	av.assoc_id = 0;
	av.assoc_value = 0;
	if (setsockopt(fd, IPPROTO_SCTP, SCTP_ECN_SUPPORTED, (char*) &av, (socklen_t)sizeof(struct sctp_assoc_value)) < 0) {
		perror("setsockopt(SCTP_ECN_SUPPORTED)");
	}
	/* Disable the Address Reconfiguration extension */
	av.assoc_id = 0;
	av.assoc_value = 0;
	if (setsockopt(fd, IPPROTO_SCTP, SCTP_ASCONF_SUPPORTED, (char*) &av, (socklen_t)sizeof(struct sctp_assoc_value)) < 0) {
		perror("setsockopt(SCTP_ASCONF_SUPPORTED)");
	}
	/* Disable the Authentication extension */
	av.assoc_id = 0;
	av.assoc_value = 0;
	if (setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_SUPPORTED, (char*) &av, (socklen_t)sizeof(struct sctp_assoc_value)) < 0) {
		perror("setsockopt(SCTP_AUTH_SUPPORTED)");
	}
	/* Disable the NR-SACK extension */
	av.assoc_id = 0;
	av.assoc_value = 0;
	if (setsockopt(fd, IPPROTO_SCTP, SCTP_NRSACK_SUPPORTED, (char*) &av, (socklen_t)sizeof(struct sctp_assoc_value)) < 0) {
		perror("setsockopt(SCTP_NRSACK_SUPPORTED)");
	}
	/* Disable the Packet Drop Report extension */
	av.assoc_id = 0;
	av.assoc_value = 0;
	if (setsockopt(fd, IPPROTO_SCTP, SCTP_PKTDROP_SUPPORTED, (char*) &av, (socklen_t)sizeof(struct sctp_assoc_value)) < 0) {
		perror("setsockopt(SCTP_PKTDROP_SUPPORTED)");
	}
	/* Enable the Partial Reliability extension */
	av.assoc_id = SCTP_ALL_ASSOC;
	av.assoc_value = 1;
	if (setsockopt(fd, IPPROTO_SCTP, SCTP_PR_SUPPORTED, &av, (socklen_t)sizeof(struct sctp_assoc_value)) < 0) {
		perror("setsockopt SCTP_PR_SUPPORTED");
	}
	/* Enable the Stream Reconfiguration extension. */
	av.assoc_id = SCTP_ALL_ASSOC;
	av.assoc_value = SCTP_ENABLE_RESET_STREAM_REQ;
	if (setsockopt(fd, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET, &av, (socklen_t)sizeof(struct sctp_assoc_value)) < 0) {
		perror("setsockopt SCTP_ENABLE_STREAM_RESET");
	}

	/* Enable the events of interest. */
	memset(&event, 0, sizeof(event));
	event.se_assoc_id = SCTP_ALL_ASSOC;
	event.se_on = 1;
	for (i = 0; i < sizeof(event_types)/sizeof(uint16_t); i++) {
		event.se_type = event_types[i];
		if (setsockopt(fd, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(event)) < 0) {
			perror("setsockopt SCTP_EVENT");
		}
	}
	memset(&initmsg, 0, sizeof(struct sctp_initmsg));
	initmsg.sinit_num_ostreams = 65535;
	initmsg.sinit_max_instreams = 65535;
	if (setsockopt(fd, IPPROTO_SCTP, SCTP_INITMSG, &initmsg, sizeof(struct sctp_initmsg)) < 0) {
		perror("setsockopt SCTP_INITMSG");
	}

	if (argc > 2) {
		client = 1;
		/* operating as client */
		if (argc > 3) {
			memset(&addr, 0, sizeof(struct sockaddr_in));
			addr.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
			addr.sin_len = sizeof(struct sockaddr_in);
#endif
			addr.sin_addr.s_addr = INADDR_ANY;
			addr.sin_port = htons(atoi(argv[3]));
			if (bind(fd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) {
				perror("bind");
			}
		}
		memset(&addr, 0, sizeof(struct sockaddr_in));
		addr.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
		addr.sin_len = sizeof(struct sockaddr_in);
#endif
		addr.sin_addr.s_addr = inet_addr(argv[1]);
		addr.sin_port = htons(atoi(argv[2]));
		if (connect(fd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) {
			perror("connect");
		}
		printf("Connected to %s:%d.\n",
		       inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
	} else if (argc > 1) {
		int afd;

		/* operating as server */
		client = 0;
		memset(&addr, 0, sizeof(struct sockaddr_in));
		addr.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
		addr.sin_len = sizeof(struct sockaddr_in);
#endif
		addr.sin_addr.s_addr = INADDR_ANY;
		addr.sin_port = htons(atoi(argv[1]));
		if (bind(fd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) {
			perror("bind");
		}
		if (listen(fd, 1) < 0) {
			perror("listen");
		}
		addr_len = (socklen_t)sizeof(struct sockaddr_in);
		memset(&addr, 0, sizeof(struct sockaddr_in));
		if ((afd = accept(fd, (struct sockaddr *)&addr, &addr_len)) < 0) {
			perror("accept");
		}
		if (close(fd) < 0) {
			perror("close");
		}
		fd = afd;
		printf("Connected to %s:%d.\n",
		       inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
	} else {
		printf("Usage: %s local_port when operating as server\n"
		       "       %s remote_addr remote_port [local_port] when operating as client\n",
		       argv[0], argv[0]);
		return (0);
	}

	init_peer_connection(&peer_connection, fd, client);
	pthread_create(&tid, NULL, &handle_messages, &peer_connection);

	for (;;) {
		if (fgets(line, LINE_LENGTH, stdin) == NULL) {
			shutdown(peer_connection.fd, SHUT_WR);
			break;
		}
		if (strncmp(line, "?", strlen("?")) == 0 ||
		    strncmp(line, "help", strlen("help")) == 0) {
			printf("Commands:\n"
			       "open unordered pr_policy pr_value priority - opens a channel\n"
			       "close channel - closes the channel\n"
			       "send channel:string - sends string using channel\n"
			       "status - prints the status\n"
			       "sleep n - sleep for n seconds\n"
			       "help - this message\n");
		} else if (strncmp(line, "status", strlen("status")) == 0) {
			lock_peer_connection(&peer_connection);
			print_status(&peer_connection);
			unlock_peer_connection(&peer_connection);
		} else if (sscanf(line, "open %u %u %u %u", &unordered, &policy, &value, &priority) == 4) {
			lock_peer_connection(&peer_connection);
			channel = open_channel(&peer_connection, (uint8_t)unordered, (uint16_t)policy, (uint32_t)value, priority, "", "");
			unlock_peer_connection(&peer_connection);
			if (channel == NULL) {
				printf("Creating channel failed.\n");
			} else {
				printf("Channel with id %u created.\n", channel->sid);
			}
		} else if (sscanf(line, "close %u", &id) == 1) {
			if (id < NUMBER_OF_CHANNELS) {
				lock_peer_connection(&peer_connection);
				close_channel(&peer_connection, &peer_connection.channels[id]);
				unlock_peer_connection(&peer_connection);
			}
		} else if (sscanf(line, "send %u", &id) == 1) {
			if (id < NUMBER_OF_CHANNELS) {
				char *msg;

				msg = strstr(line, ":");
				if (msg) {
					msg++;
					lock_peer_connection(&peer_connection);
					if (send_user_message(&peer_connection, &peer_connection.channels[id], msg, strlen(msg) - 1)) {
						printf("Message sent.\n");
					} else {
						printf("Message sending failed.\n");
					}
					unlock_peer_connection(&peer_connection);
				}
			}
		} else if (sscanf(line, "sleep %u", &seconds) == 1) {
			sleep(seconds);
		} else {
			printf("Unknown command: %s", line);
		}
	}
	pthread_join(tid, NULL);
	if (close(peer_connection.fd) < 0) {
		perror("close");
	}
	return (0);
}


text:
package org.apereo.cas.web;

import org.apereo.cas.CasEmbeddedValueResolver;
import org.apereo.cas.configuration.CasConfigurationPropertiesValidator;

import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.val;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.TaskManagementConfigUtils;

/**
 * This is {@link CasWebApplicationContext}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
@ToString
@NoArgsConstructor
public class CasWebApplicationContext extends AnnotationConfigServletWebServerApplicationContext {

    /**
     * {@inheritDoc}
     * Reset the value resolver on the inner {@link ScheduledAnnotationBeanPostProcessor}
     * so that we can parse durations. This is due to how {@link org.springframework.scheduling.annotation.SchedulingConfiguration}
     * creates the processor and does not provide a way for one to inject a value resolver.
     */
    @Override
    protected void onRefresh() {
        val sch = (ScheduledAnnotationBeanPostProcessor) getBeanFactory()
            .getBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME, BeanPostProcessor.class);
        sch.setEmbeddedValueResolver(new CasEmbeddedValueResolver(this));

        if (!Boolean.getBoolean("SKIP_CONFIG_VALIDATION")) {
            val validator = new CasConfigurationPropertiesValidator(this);
            validator.validate();
        }
        super.onRefresh();
    }
}


text:
import java.util.*;
import java.util.stream.*;

class Test {
  static class MyType<A,B> extends ArrayList<String> {
    public MyType() {}

    public MyType(Collection<String> coll) {
      super(coll);
    }
  }

  public static void testMy(List<String> s) {
      new MyType<String, Number>(s).contains("abc");
  }
}


text:
import React from 'react';
import {Input, MenuItem} from 'react-bootstrap';
import $ from 'jquery';
import ResourceTypeDirectory from './ResourceTypeDirectory'
import ResourceTypeGit from './ResourceTypeGit'
import { resourcesURI } from '../../utils/Config'

const ResourceSelector = React.createClass({

    loadData() {
        return $.getJSON(resourcesURI());
    },
    getInitialState() {
        return {data: [], selected: this.props.selected};
    },

    onChange(event) {
        this.setState({selected: event.target.value});
    },

    componentDidMount(){
        this.loadData().success(function (data) {
            if (this.isMounted()) {
                this.setState({data: data});
            }
        }.bind(this))
    },
    render() {
        return (
            <div>
                <Input value={this.state.selected}
                       type="select"
                       label="Resource" placeholder="Resource"
                       onChange={this.onChange}>
                    {
                        this.state.data.map(function (item, i) {
                                return <option value={item.name} key={i}>{item.name}</option>
                            }
                        )}
                </Input>

            </div>
        );
    }
});
export default ResourceSelector;


text:
<?php
namespace Payum\Paypal\ExpressCheckout\Nvp\Action\Api;

use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Exception\LogicException;
use Payum\Paypal\ExpressCheckout\Nvp\Request\Api\DoExpressCheckoutPayment;

class DoExpressCheckoutPaymentAction extends BaseApiAwareAction
{
    /**
     * {@inheritDoc}
     */
    public function execute($request)
    {
        /** @var $request DoExpressCheckoutPayment */
        RequestNotSupportedException::assertSupports($this, $request);

        $model = ArrayObject::ensureArrayObject($request->getModel());

        if (null === $model['TOKEN']) {
            throw new LogicException('TOKEN must be set. Have you run SetExpressCheckoutAction?');
        }
        if (null === $model['PAYERID']) {
            throw new LogicException('PAYERID must be set. Has user authorized this transaction?');
        }
        if (null === $model['PAYMENTREQUEST_0_PAYMENTACTION']) {
            throw new LogicException('PAYMENTREQUEST_0_PAYMENTACTION must be set.');
        }
        if (null === $model['PAYMENTREQUEST_0_AMT']) {
            throw new LogicException('PAYMENTREQUEST_0_AMT must be set.');
        }

        $model->replace(
            $this->api->doExpressCheckoutPayment((array) $model)
        );
    }

    /**
     * {@inheritDoc}
     */
    public function supports($request)
    {
        return
            $request instanceof DoExpressCheckoutPayment &&
            $request->getModel() instanceof \ArrayAccess
        ;
    }
}


text:
#ifndef CCFRAMEWORK_H_
#define CCFRAMEWORK_H_

//routing functor
#define create_routing_functor(class_name, function_name) new ccSpecificRouterFunctor< class_name >(this, &class_name::function_name)

#include <iostream>
#include <fstream>
#include "yaml-cpp/yaml.h"

#include "ccPreforkServer.h"
#include "ccHttpCodes.h"
#include "ccAcl.h"
#include "ccApp.h"
#include "ccBaseFormElement.h"
#include "ccBaseForm.h"
#include "ccBaseHelper.h"
#include "ccCommon.h"
#include "ccComponentHelper.h"
#include "ccConfig.h"
#include "ccConfigLoader.h"
#include "ccController.h"
#include "ccCookie.h"
#include "ccEventDispatcher.h"
#include "ccEvent.h"
#include "ccException.h"
#include "ccFormElementFormStart.h"
#include "ccFormElementLabel.h"
#include "ccFormElementText.h"
#include "ccMultipartParser.h"
#include "ccPregRoute.h"
#include "ccQueryParser.h"
#include "ccRequest.h"
#include "ccResource.h"
#include "ccResponse.h"
#include "ccRole.h"
#include "ccRoute.h"
#include "ccRouter.h"
#include "ccSession.h"
#include "ccSessionProvider.h"
#include "ccMemorySessionProvider.h"
#include "ccStaticRoute.h"
#include "ccTemplateResponse.h"
#include "ccYamlSessionProvider.h"

#endif /* CCFRAMEWORK_H_ */


text:
require 'test_helper'

class GrapeSwaggerTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, GrapeSwagger
  end
end


text:
*   Add extension for automatic defaults description

*   Add missing required dependencies

    *Pavol Zbell*

## 0.5.0

*   Support parsing of options with typed array value and multiple typed arguments

*   Support underscore pattern syntax in string definitions

*   Make parsing methods backwards compatible with `OptionParser` again

*   Add extensions for parsing mode, known types, and custom handlers

*   Add a lot of new test cases, minor bug fixes, and enhancements

    *Pavol Zbell*

## 0.4.0

*   Support binding options to class variables

*   Support argument patterns and types, make argument processing in fact same as option processing

*   Enable setting program name via constant and set both program name and version for both default and supplied parsers

*   Enable non-destructive parsing for ARGV

*   Raise an error on parsing failure instead of totally aborting execution

*   Remove `order` and `permute` methods

*   Conform to Ruby 2.3 and frozen strings

    *Pavol Zbell*

## 0.3.2

*   Fix handling of blanks as array arguments

    *Pavol Zbell*

## 0.3.1

*   Fix critical bug when parsing arguments

    *Pavol Zbell*

## 0.3.0

*   Add support for access to assigned variables

*   Fix default argument handler when encountering blank arguments

    *Pavol Zbell*

## 0.2.2

*   Fix default option handler when encountering blank arguments

    *Pavol Zbell*

## 0.2.1

*   Fix multiple argument parsing with arrays as default values

    *Pavol Zbell*

## 0.2.0

*   Unconditionally abort on any parse error

    *Pavol Zbell*

## 0.1.1

*   Fix critical bug when parsing arguments

    *Pavol Zbell*

## 0.1.0

*   Fix optional argument handling and help text generation

*   Update default help text

    *Pavol Zbell*

## 0.0.2

*   Fix gem files

    *Pavol Zbell*

## 0.0.1

*   Add initial extension to standard command line option parsing, setup Gem environment and RSpec tests

    *Pavol Zbell*


text:
module.exports = function(grunt) {
  var banner = '/*! <%= pkg.name %> <%= pkg.version %> | (c) <%= grunt.template.today("yyyy") %>, One World Schoolhouse, University of Toledo | The MIT License (MIT) */\n';

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    clean: ["dist/**/*.js"],

    jshint: {
      all: ['Gruntfile.js', 'src/**/*.js'],
    },

    uglify: {
      options: {
        banner: banner
      },
      build: {
        src: 'dist/<%= pkg.name %>.js',
        dest: 'dist/<%= pkg.name %>.min.js'
      },
      dist:{
        src: 'dist/<%= pkg.name %>.standalone.js',
        dest: 'dist/<%= pkg.name %>.standalone.min.js'
      }
    },

    concat: {
      options: {
        stripBanners: false,
        separator: ';\n',
      },
      build: {
        src: [
          'src/**/*.js'
        ],
        dest: 'dist/<%= pkg.name %>.js',
      },
      dist: {
        src: [
          'node_modules/formulajs/node_modules/jStat/dist/jstat.min.js',
          'node_modules/formulajs/node_modules/numeral/min/numeral.min.js',
          'node_modules/formulajs/node_modules/numeric/numeric-*.min.js',
          'node_modules/formulajs/node_modules/bessel/bessel.js',
          'node_modules/formulajs/dist/formula.min.js',
          'src/**/*.js'
        ],
        dest: 'dist/<%= pkg.name %>.standalone.js',
      },
    },
    watch: {
      files: ['Gruntfile.js','src/**/*'],
      tasks: ['clean', 'jshint','concat:build', 'uglify:build', 'concat:dist', 'uglify:dist'],
    },
  });

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Default task(s).
  grunt.registerTask('default', ['clean', 'jshint','concat:build', 'uglify:build']);
  grunt.registerTask('standalone', ['default', 'concat:dist', 'uglify:dist']);
  grunt.registerTask('dev', ['default', 'standalone', 'watch']);

};


text:
package net.faintedge.rube.codec;

import com.artemis.Component;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import net.faintedge.rube.components.physics.Colliders;
import net.faintedge.rube.components.physics.Joints;
import net.faintedge.rube.components.*;

import java.lang.reflect.Type;
import java.util.Map;

/**
 *
 */
public class ComponentCodec implements JsonSerializer<Component>, JsonDeserializer<Component> {

  private final static BiMap<String, Class<? extends Component>> types = createTypesMap();

  private static BiMap<String, Class<? extends Component>> createTypesMap() {
    HashBiMap<String, Class<? extends Component>> result = HashBiMap.create();
    result.put("render", Render.class);
    result.put("anchors", Anchors.class);
    result.put("camera", Camera.class);
    result.put("colliders", Colliders.class);
    result.put("joints", Joints.class);
    result.put("name", Name.class);
    result.put("physics", Physics.class);
    result.put("physics-motion", PhysicsMotion.class);
    result.put("transform", Transform.class);
    result.put("transform-motion", TransformMotion.class);
    result.put("wheel-motion", WheelMotion.class);
    return result;
  }

  @Override
  public Component deserialize(JsonElement jsonElement, Type type,
                               JsonDeserializationContext ctx) throws JsonParseException {
    JsonObject obj = jsonElement.getAsJsonObject();
    Preconditions.checkArgument(obj.has("type"));
    String typeString = obj.get("type").getAsString();
    return ctx.deserialize(jsonElement, getType(typeString));
  }

  @Override
  public JsonElement serialize(Component object, Type type, JsonSerializationContext ctx) {
    JsonObject result = new JsonObject();
    result.addProperty("type", getTypeString(object.getClass()));

    JsonObject base = ctx.serialize(object).getAsJsonObject();
    Preconditions.checkArgument(!base.has("type"));
    for (Map.Entry<String, JsonElement> entry : base.entrySet()) {
      result.add(entry.getKey(), entry.getValue());
    }
    return result;
  }

  private Class<? extends Component> getType(String typeString) {
    Preconditions.checkArgument(types.containsKey(typeString), "Unknown component type: " + typeString);
    return types.get(typeString);
  }

  private String getTypeString(Class<? extends Component> componentType) {
    Preconditions.checkArgument(types.containsValue(componentType), "Unknown component type class: " + componentType);
    return types.inverse().get(componentType);
  }
}


text:
<!DOCTYPE html>

<title>node_wrappers_node.http.Server.js</title>
<link rel="stylesheet" href="../../css/prettify_wynn.css" media="all"></link>
<link rel="stylesheet" href="../../css/all.css" media="all"></link>

goog.provide("node.http.Server");

/**
 * This is an <code>EventEmitter</code> with the following events:
 * @constructor
 */
node.http.Server = function() {};

/**
 * @type {string|null}
 */
node.http.Server.prototype.connections = null;

/**
 * @type {string|null}
 */
node.http.Server.prototype.allowHalfOpen = null;

/**
 * @type {string|null}
 */
node.http.Server.prototype.watcher = null;

/**
 * @param {string} msecs
 */
node.http.Server.prototype.pause = function(msecs) {
  return node.http.Server.core_.pause(msecs);
};

/**
 * Start a UNIX socket server listening for connections on the given <code>path</code>.
 *
 * This function is asynchronous. The last parameter <code>callback</code> will be called
 * when the server has been bound.
 */
node.http.Server.prototype.listen = function() {
  return node.http.Server.core_.listen();
};

/**
 * @param {string} fd
 * @param {string} type
 */
node.http.Server.prototype.listenFD = function(fd, type) {
  return node.http.Server.core_.listenFD(fd, type);
};

/**
 *
 */
node.http.Server.prototype.address = function() {
  return node.http.Server.core_.address();
};

/**
 * Stops the server from accepting new connections.
 */
node.http.Server.prototype.close = function() {
  return node.http.Server.core_.close();
};

/**
 * @param {string} n
 */
node.http.Server.prototype.setMaxListeners = function(n) {
  return node.http.Server.core_.setMaxListeners(n);
};

/**
 * @param {string} type
 */
node.http.Server.prototype.emit = function(type) {
  return node.http.Server.core_.emit(type);
};

/**
 * @param {string} type
 * @param {string} listener
 */
node.http.Server.prototype.addListener = function(type, listener) {
  return node.http.Server.core_.addListener(type, listener);
};

/**
 * @param {string} type
 * @param {string} listener
 */
node.http.Server.prototype.on = function(type, listener) {
  return node.http.Server.core_.on(type, listener);
};

/**
 * @param {string} type
 * @param {string} listener
 */
node.http.Server.prototype.once = function(type, listener) {
  return node.http.Server.core_.once(type, listener);
};

/**
 * @param {string} type
 * @param {string} listener
 */
node.http.Server.prototype.removeListener = function(type, listener) {
  return node.http.Server.core_.removeListener(type, listener);
};

/**
 * @param {string} type
 */
node.http.Server.prototype.removeAllListeners = function(type) {
  return node.http.Server.core_.removeAllListeners(type);
};

/**
 * @param {string} type
 */
node.http.Server.prototype.listeners = function(type) {
  return node.http.Server.core_.listeners(type);
};

/**
 * @private
 * @type {*}
 */
node.http.Server.core_ = require("http").Server;


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

require APPPATH.'/libraries/REST_Controller.php';

class User extends REST_Controller
{
	function __construct()
    {
    	parent::__construct();
		$this->load->model('user_model');
    }

	function login_post()
	{
		$username = $this->post('nik');
		$password = $this->post('password');
		if(!empty($username) || !empty($password)){
			$model = $this->user_model->login($username, $password);
			if(empty($model)){
				$this->response(array('errorCode' => 404, 'message' => 'Login Failed'), 404);
			} else {
				$this->response(array('errorCode' => 0, 'message' => 'Success', 'data' => $model), 200);
			}
		} else {
			$this->response(array('errorCode' => 400, 'message' => 'Parameter not completed'), 400);
		}

	}

	public function register_post()
	{
		if($this->validateCreate()){
			$model = $this->user_model->check_username(post('username'));
			if(empty($model)){
				$model = $this->user_model->register(post('username'), post('password'), post('full_name'), post('gender'), post('birthdate'), post('imei_number'), post('status'));
				if(empty($model)){
					$this->response(array('success' => false, 'message' => 'Registration Failed', 'responseCode' => 406), 406);
				} else {
					$this->response(array('success' => true, 'message' => 'Registration Successfull', 'responseCode' => 200), 200);
				}
			} else {
				$this->response(array('success' => false, 'message' => 'Username already exist', 'responseCode' => 409), 409);
			}
		} else {
			$this->response(array('success' => false, 'message' => 'Registration Not Completed', 'responseCode' => 400), 400);
		}
	}

	function profile_get($username)
	{
		if(!empty($username)){
			$model = $this->user_model->profile($username);
			if(empty($model)){
				$this->response(array('errorCode' => 404, 'message' => 'Get Profile Failed'), 404);
			} else {
				$this->response(array('errorCode' => 0, 'message' => 'Success', 'data' => $model), 200);
			}
		} else {
			$this->response(array('errorCode' => 400, 'message' => 'Parameter not completed'), 400);
		}

	}

	public function validateCreate()
	{
		if(!post('user_role_id') || !post('user_active_id') || !post('username') || !post('password') || !post('birthdate') || !post('gender'))
			return false;
		else
			return true;
	}

}

?>