text:
//License

package com.ghgande.j2mod.modbus.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.ModbusIOException;
import com.ghgande.j2mod.modbus.msg.ModbusMessage;
import com.ghgande.j2mod.modbus.msg.ModbusRequest;
import com.ghgande.j2mod.modbus.msg.ModbusResponse;
import com.ghgande.j2mod.modbus.net.TCPMasterConnection;
import com.ghgande.j2mod.modbus.util.ModbusUtil;

/**
 * Class that implements the Modbus transport flavor.
 *
 * @author Dieter Wimberger
 * @version 1.2rc1 (09/11/2004)
 *
 * @version 110410-jfh Cleaned up unused variables. Stopped spewing out error
 *          messages.
 */
public class ModbusTCPTransport implements ModbusTransport {

	// instance attributes
	private DataInputStream m_Input; // input stream
	private DataOutputStream m_Output; // output stream
	private BytesInputStream m_ByteIn;
	private BytesOutputStream m_ByteOut; // write frames
	private int m_Timeout = Modbus.DEFAULT_TIMEOUT;
	private Socket m_Socket = null;
	private	TCPMasterConnection m_Master = null;
	private boolean headless = false; // Some TCP implementations are.

	/**
	 * Sets the <tt>Socket</tt> used for message transport and prepares the
	 * streams used for the actual I/O.
	 *
	 * @param socket
	 *            the <tt>Socket</tt> used for message transport.
	 * @throws IOException
	 *             if an I/O related error occurs.
	 */
	public void setSocket(Socket socket) throws IOException {
		if (m_Socket != null) {
			m_Socket.close();
			m_Socket = null;
		}
		m_Socket = socket;
		setTimeout(m_Timeout);

		prepareStreams(socket);
	}// setSocket

	public void setHeadless() {
		headless = true;
	}

	public void setTimeout(int time) {
		m_Timeout = time;

		if (m_Socket != null) {
			try {
				m_Socket.setSoTimeout(time);
			} catch (SocketException e) {
				// Not sure what to do.
				return;
			}
		}
	}

	public void close() throws IOException {
		m_Input.close();
		m_Output.close();
		m_Socket.close();
	}// close

	  public ModbusTransaction createTransaction() {
		  if (m_Master == null) {
			  m_Master = new TCPMasterConnection(m_Socket.getInetAddress());
			  m_Master.setPort(m_Socket.getPort());
			  m_Master.setModbusTransport(this);
		  }
		  ModbusTCPTransaction trans = new ModbusTCPTransaction(m_Master);
		  return trans;
	  }

	public void writeMessage(ModbusMessage msg) throws ModbusIOException {
		try {
			byte message[] = msg.getMessage();

			m_ByteOut.reset();
			if (!headless) {
				m_ByteOut.writeShort(msg.getTransactionID());
				m_ByteOut.writeShort(msg.getProtocolID());
				m_ByteOut
						.writeShort((message != null ? message.length : 0) + 2);
			}
			m_ByteOut.writeByte(msg.getUnitID());
			m_ByteOut.writeByte(msg.getFunctionCode());
			if (message != null && message.length > 0)
				m_ByteOut.write(message);

			m_Output.write(m_ByteOut.toByteArray());
			m_Output.flush();
			if (Modbus.debug)
				System.err.println("Sent: "
						+ ModbusUtil.toHex(m_ByteOut.toByteArray()));
			// write more sophisticated exception handling
		} catch (SocketException ex) {
			if (! m_Master.isConnected()) {
				try {
					m_Master.connect();
				} catch (Exception e) {
					// Do nothing.
				}
			}
			throw new ModbusIOException("I/O exception - failed to write.");
		} catch (Exception ex) {
			throw new ModbusIOException("I/O exception - failed to write.");
		}
	}

	/**
	 * readRequest -- Read a Modbus TCP encoded request. The packet has a 6 byte
	 * header containing the protocol, transaction ID and length.
	 *
	 * @returns Modbus response for message
	 * @throws ModbusIOException
	 */
	public ModbusRequest readRequest() throws ModbusIOException {

	try {
			ModbusRequest req = null;
			m_ByteIn.reset();

			synchronized (m_ByteIn) {
				byte[] buffer = m_ByteIn.getBuffer();

				if (!headless) {
					if (m_Input.read(buffer, 0, 6) == -1)
						throw new EOFException(
								"Premature end of stream (Header truncated).");

					int transaction = ModbusUtil.registerToShort(buffer, 0);
					int protocol = ModbusUtil.registerToShort(buffer, 2);
					int count = ModbusUtil.registerToShort(buffer, 4);

					if (m_Input.read(buffer, 6, count) == -1)
						throw new ModbusIOException(
								"Premature end of stream (Message truncated).");

					if (Modbus.debug)
						System.err.println("Read: "
								+ ModbusUtil.toHex(buffer, 0, count + 6));

					m_ByteIn.reset(buffer, (6 + count));
					m_ByteIn.skip(6);

					int unit = m_ByteIn.readByte();
					int functionCode = m_ByteIn.readUnsignedByte();

					m_ByteIn.reset();
					req = ModbusRequest.createModbusRequest(functionCode);
					req.setUnitID(unit);
					req.setHeadless(false);

					req.setTransactionID(transaction);
					req.setProtocolID(protocol);
					req.setDataLength(count);

					req.readFrom(m_ByteIn);
				} else {

					/*
					 * This is a headless request.
					 */
					int unit = m_Input.readByte();
					int function = m_Input.readByte();

					req = ModbusRequest.createModbusRequest(function);
					req.setUnitID(unit);
					req.setHeadless(true);

					req.readData(m_Input);

					/*
					 * Discard the CRC. This is a TCP/IP connection, which has
					 * proper error correction and recovery.
					 */
					m_Input.readShort();
					if (Modbus.debug)
						System.err.println("Read: "	+ req.getHexMessage());
				}
			}
			return req;
		} catch (EOFException eoex) {
			throw new ModbusIOException("End of File", true);
		} catch (SocketTimeoutException x) {
			throw new ModbusIOException("Timeout reading request");
		} catch (SocketException sockex) {
			throw new ModbusIOException("Socket Exception", true);
		} catch (Exception ex) {
			throw new ModbusIOException("I/O exception - failed to read.");
		}
	}

	public ModbusResponse readResponse() throws ModbusIOException {

		try {

			ModbusResponse response = null;

			synchronized (m_ByteIn) {
				// use same buffer
				byte[] buffer = m_ByteIn.getBuffer();
				if (Modbus.debug)
					System.err.println("Read: " +
							ModbusUtil.toHex(buffer, 0, m_ByteIn.count));

				if (!headless) {
					/*
					 * All Modbus TCP transactions start with 6 bytes. Get them.
					 */
					if (m_Input.read(buffer, 0, 6) == -1)
						throw new ModbusIOException(
								"Premature end of stream (Header truncated).");

					/*
					 * The transaction ID is the first word (offset 0) in the
					 * data that was just read. It will be echoed back to the
					 * requester.
					 *
					 * The protocol ID is the second word (offset 2) in the
					 * data. It should always be 0, but I don't check.
					 *
					 * The length of the payload is the third word (offset 4) in
					 * the data that was just read. That's what I need in order
					 * to read the rest of the response.
					 */
					int transaction = ModbusUtil.registerToShort(buffer, 0);
					int protocol = ModbusUtil.registerToShort(buffer, 2);
					int count = ModbusUtil.registerToShort(buffer, 4);

					if (m_Input.read(buffer, 6, count) == -1)
						throw new ModbusIOException(
								"Premature end of stream (Message truncated).");

					m_ByteIn.reset(buffer, (6 + count));

					m_ByteIn.reset();
					m_ByteIn.skip(7);
					int function = m_ByteIn.readUnsignedByte();
					response = ModbusResponse.createModbusResponse(function);

					/*
					 * Rewind the input buffer, then read the data into the
					 * response.
					 */
					m_ByteIn.reset();
					response.readFrom(m_ByteIn);

					response.setTransactionID(transaction);
					response.setProtocolID(protocol);
				} else {
					/*
					 * This is a headless response. It has the same format as a
					 * RTU over Serial response.
					 */
					int unit = m_Input.readByte();
					int function = m_Input.readByte();

					response = ModbusResponse.createModbusResponse(function);
					response.setUnitID(unit);
					response.setHeadless();
					response.readData(m_Input);

					/*
					 * Now discard the CRC. Which hopefully wasn't needed
					 * because this is a TCP transport.
					 */
					m_Input.readShort();
				}
			}
			return response;
		} catch (SocketTimeoutException ex) {
			throw new ModbusIOException("Timeout reading response");
		} catch (Exception ex) {
			throw new ModbusIOException("I/O exception - failed to read.");
		}
	}

	/**
	 * Prepares the input and output streams of this <tt>ModbusTCPTransport</tt>
	 * instance based on the given socket.
	 *
	 * @param socket
	 *            the socket used for communications.
	 * @throws IOException
	 *             if an I/O related error occurs.
	 */
	private void prepareStreams(Socket socket) throws IOException {

		/*
		 * Close any open streams if I'm being called because a new socket was
		 * set to handle this transport.
		 */
		try {
			if (m_Input != null)
				m_Input.close();

			if (m_Output != null)
				m_Output.close();
		} catch (IOException x) {
			// Do nothing.
		}

		m_Input = new DataInputStream(new BufferedInputStream(
				socket.getInputStream()));

		m_Output = new DataOutputStream(new BufferedOutputStream(
				socket.getOutputStream()));

		/*
		 * Modbus/TCP adds a header which must be accounted for.
		 */
		m_ByteIn = new BytesInputStream(Modbus.MAX_MESSAGE_LENGTH+6);

		m_ByteOut = new BytesOutputStream(Modbus.MAX_MESSAGE_LENGTH+6);
	}

	/**
	 * Constructs a new <tt>ModbusTransport</tt> instance, for a given
	 * <tt>Socket</tt>.
	 * <p>
	 *
	 * @param socket
	 *            the <tt>Socket</tt> used for message transport.
	 */
	public ModbusTCPTransport(Socket socket) {
		try {
			setSocket(socket);
			socket.setSoTimeout(m_Timeout);
		} catch (IOException ex) {
			if (Modbus.debug)
				System.out.println("ModbusTCPTransport::Socket invalid.");

			throw new IllegalStateException("Socket invalid.");
		}
	}
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class FileUser extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('file_user', function(Blueprint $table) {
            $table->integer('user_id')->unsigned()->index();
            $table->integer('file_id')->unsigned()->index();
            $table->boolean('owner')->default(0)->index();
            $table->text('permissions')->nullable();
            $table->timestamps();

            $table->unique(['file_id', 'user_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('file_user');
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class TagTest < ActiveSupport::TestCase
  test "have all its relationships ok" do
    tag = Tag.create(title: "ex1")
    assert tag.user_channel_tag_relationships
    assert tag.users
    assert tag.channels
  end

  test "don't create 2 tags with the same title" do
    tag_count = Tag.count
    tag1 = Tag.create(title: "ex1")
    assert_equal tag_count + 1, Tag.count
    assert tag1.persisted?

    #second tag with same uid is not created
    tag2 = Tag.create(title: "ex1")
    assert_equal tag_count + 1, Tag.count
    assert !tag2.persisted?
  end

  test "get tag with channels count hash" do
    tags_hash = Tag.all_with_channels_count
    assert_equal({"TitleOne"=>1, "TitleTwo"=>2}, tags_hash)
  end

  test "all tags with channels hash" do
    assert_equal({"TitleTwo"=>["UidTwo", "UidOne"], "TitleOne"=>["UidOne"]}, Tag.all_with_channels)
  end
end


text:
var express = require('express'),
    http = require('http'),
    path = require('path'),
    favicon = require('static-favicon'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    socket = require('./sockets');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.use(require('connect').bodyParser());
app.use(favicon());
app.use(express.methodOverride());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

app.use(app.router);

app.get('/', function(req, res){
    res.render('index.html', { title: 'Page me bro' });
});

app.post('/page', function (req, res) {
    socket.io.sockets.emit('message:new', {
        Body: req.body.Body,
        From: req.body.From
    });
    res.end('sent');
});

module.exports = app;


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="EditorFileSystemDirectory" inherits="Object" category="Core" version="3.0-alpha">
	<brief_description>
		A diretory for the resource filesystem.
	</brief_description>
	<description>
	</description>
	<tutorials>
	</tutorials>
	<demos>
	</demos>
	<methods>
		<method name="find_dir_index" qualifiers="const">
			<return type="int">
			</return>
			<argument index="0" name="name" type="String">
			</argument>
			<description>
			</description>
		</method>
		<method name="find_file_index" qualifiers="const">
			<return type="int">
			</return>
			<argument index="0" name="name" type="String">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_file" qualifiers="const">
			<return type="String">
			</return>
			<argument index="0" name="idx" type="int">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_file_count" qualifiers="const">
			<return type="int">
			</return>
			<description>
			</description>
		</method>
		<method name="get_file_import_is_valid" qualifiers="const">
			<return type="bool">
			</return>
			<argument index="0" name="idx" type="int">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_file_path" qualifiers="const">
			<return type="String">
			</return>
			<argument index="0" name="idx" type="int">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_file_type" qualifiers="const">
			<return type="String">
			</return>
			<argument index="0" name="idx" type="int">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_name">
			<return type="String">
			</return>
			<description>
			</description>
		</method>
		<method name="get_parent">
			<return type="EditorFileSystemDirectory">
			</return>
			<description>
			</description>
		</method>
		<method name="get_path" qualifiers="const">
			<return type="String">
			</return>
			<description>
			</description>
		</method>
		<method name="get_subdir">
			<return type="EditorFileSystemDirectory">
			</return>
			<argument index="0" name="idx" type="int">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_subdir_count" qualifiers="const">
			<return type="int">
			</return>
			<description>
			</description>
		</method>
	</methods>
	<constants>
	</constants>
</class>


text:
import React, { Component } from 'react';
import Scroll from 'react-scroll';

import logo from './logo.svg';
import './stylesheets/style.css';

let Link       = Scroll.Link;
let Element    = Scroll.Element;
let Events     = Scroll.Events;
let scroll     = Scroll.animateScroll;
let scrollSpy  = Scroll.scrollSpy;

class App extends Component {
  /**
   * Constructor.
   * @constructor
   */
   constructor (props){
       super(props);
       this.scrollToTop = this.scrollToTop.bind(this);
   }

   componentDidMount() {

     Events.scrollEvent.register('begin', function(to, element) {
       console.log("begin", to, element);
     });

     Events.scrollEvent.register('end', function(to, element) {
       console.log("begin", to, element);
     });

     scrollSpy.update();

   }
   scrollToTop() {
     scroll.scrollToTop();
   }
   componentWillUnmount() {
     Events.scrollEvent.remove('begin');
     Events.scrollEvent.remove('end');
   }

  render() {
    return (

                <Link className="nav-link" activeClass="active" to="what" spy={true} smooth={true} offset={-45} duration={500}>
                  What is Kyo
                </Link>

                <Link className="nav-link" activeClass="active" to="who" spy={true} smooth={true} offset={-45} duration={500}>
                  Who is this for
                </Link>

                <Link className="nav-link" activeClass="active" to="how" spy={true} smooth={true} offset={-45} duration={600}>
                  How does it work
                </Link>

                <Link className="nav-link" activeClass="active" to="contact" spy={true} smooth={true} offset={-45} duration={700}>
                  Contact us
                </Link>

Meet Kyo

Your personal color stylist that provides outfits solutions through fashion illustrations

What is Kyo

                Kyo is your personal fashion color app that delivers an artful  dressing experience. Weather, occasion, your skin tone, preferred colors and materials will all be taken care by Kyo.  Kyo provides aesthetic coordinated outfits based on intensive research from popular brands, books and paintings. It has never been easier and more fun to mix and match colors with Kyo's inspirational illustrations. Kyo's travel feature enables you to pack fashionable outfits with cultural awareness.

Who is this for

                If you ever wondered what colors you should wear, Kyo is the perfect app for you. No matter who you are and where you are going, Kyo is able to find you a great outfit with beautiful colors you will fall in love with.

                Jen is one of many who want her outfit colors to be playful and perhaps a bit experimental. Let's show you how Kyo has improved Jen's daily life.

How does it work

                Daily Outfit Recommendations

                Every morning, Jen opens Kyo before opening her wardrobe to check what to wear. She knows Kyo will recommend the right outfit for the day based on her fashion preferences and weather. On a rainy day, Kyo suggests Jen to wear a yellow raincoat with green jeans and purple rain boots.

How does it work

                Special Occasion

                Last weekend, Jen went to a friend's wedding. She chose to check out some suggestions from Kyo. Kyo suggested a navy floral dress with white flowers. She gladly took the advice. She posted her look on Kyo's social media platform, many likes received. A week later, she received a gift from Kyo as she won the weekly fashion contest.

How does it work

                Travel with Kyo

                Jen is planning a one-week trip to Tokyo for Christmas. She asks Kyo what to pack. She simply enters her travel destination and dates. Kyo quickly populates several outfits based on local weather and culture through its AI engine. Jen is very happy with the recommendations. She also adds items she doesn't own to her shopping list. Kyo will remind Jen before the trip to be prepared with her outfits. She manages to pack everything in her suitcase and ready to board for Tokyo.

Contact us

                Kyo is currently under development. If you're interested in investment, or just want to chat about your passion on fashion, message us at dresswithkyo@gmail.com

Copyright Kyo 2017

    );
  }
}

export default App;


text:
#nullable enable

namespace Snittlistan.Queue.Messages;

public class OneTimeKeyTask : TaskBase
{
    public OneTimeKeyTask(string email, string oneTimePassword)
        : base(new(typeof(OneTimeKeyTask).FullName, email))
    {
        Subject = "Logga in till Snittlistan";
        Email = email;
        OneTimePassword = oneTimePassword;
    }

    public string Subject { get; }

    public string Email { get; }

    public string OneTimePassword { get; }
}


text:
GoAst Viewer
================================================================

Golang AST visualizer.

## Demo

[GoAst Viewer Demo](http://goast.yuroyoro.net/)

![](https://raw.githubusercontent.com/yuroyoro/goast-viewer/master/goast-viewer.png)

## Usage

You just run `goas-viewer` and go `http://localhost:7650/`

```bash
$ goast-viewer
2014/06/30 18:57:10 Server listening on : :7650
```

## Installation

To install, use `go get` and `make install`.

```bash
$ go get -d github.com/yuroyoro/goast-viewer
$ cd $GOPATH/src/github.com/yuroyoro/goast-viewer
$ make install
```

## Author

[yuroyoro](https://github.com/yuroyoro)


text:
@interface WebViewController () <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = [ConfigManager sharedInstance].appName;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[ConfigManager sharedInstance].websiteURL]];
}

- (void)changeURL:(NSURL *)url {
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}

@end


text:
@interface PodsDummy_Pods_FHWebView_Tests : NSObject
@end
@implementation PodsDummy_Pods_FHWebView_Tests
@end


text:
package egovframework.com.sym.sym.srv.web;
import java.util.List;

import egovframework.com.cmm.ComDefaultCodeVO;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.LoginVO;
import egovframework.com.cmm.annotation.IncludedInfo;
import egovframework.com.cmm.service.EgovCmmUseService;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import egovframework.com.sym.sym.srv.service.EgovServerService;
import egovframework.com.sym.sym.srv.service.Server;
import egovframework.com.sym.sym.srv.service.ServerEqpmn;
import egovframework.com.sym.sym.srv.service.ServerEqpmnRelate;
import egovframework.com.sym.sym.srv.service.ServerEqpmnRelateVO;
import egovframework.com.sym.sym.srv.service.ServerEqpmnVO;
import egovframework.com.sym.sym.srv.service.ServerVO;

import egovframework.rte.fdl.idgnr.EgovIdGnrService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springmodules.validation.commons.DefaultBeanValidator;

/**
 * 개요
 * - 서버정보관리에 대한 controller 클래스를 정의한다.
 *
 * 상세내용
 * - 서버정보관리에 대한 등록, 수정, 삭제, 조회 등의 기능을 제공한다.
 * - 서버정보관리의 조회기능은 목록조회, 상세조회로 구분된다.
 * @author lee.m.j
 * @version 1.0
 * @created 28-6-2010 오전 10:44:31
 * <pre>
 * == 개정이력(Modification Information) ==
 *
 *   수정일       수정자           수정내용
 *  -------     --------    ---------------------------
 *  2010.06.28   이문준     최초 생성
 *  2011.8.26	정진오			IncludedInfo annotation 추가
 * </pre>
 */

@Controller
public class EgovServerController {

	@Resource(name="egovMessageSource")
    EgovMessageSource egovMessageSource;

    @Resource(name = "egovServerService")
    private EgovServerService egovServerService;

    /** ID Generation */
    @Resource(name="egovServerEqpmnIdGnrService")
    private EgovIdGnrService egovServerEqpmnIdGnrService;

    /** ID Generation */
    @Resource(name="egovServerIdGnrService")
    private EgovIdGnrService egovServerIdGnrService;

    @Autowired
	private DefaultBeanValidator beanValidator;

    @Resource(name = "EgovCmmUseService")
    EgovCmmUseService EgovCmmUseService;

	/**
	 * 서버장비관리 목록화면으로 이동
	 * @return String
	 */
    @RequestMapping(value="/sym/sym/srv/selectServerEqpmnListView.do")
	public String selectServerEqpmnListView() throws Exception {
		return "egovframework/com/sym/sym/srv/EgovServerEqpmnList";
	}

	/**
	 * 서버장비를 관리하기 위해 등록된 서버장비목록을 조회한다.
	 * @param serverEqpmnVO - 서버장비 Vo
	 * @return String - 리턴 Url
	 *
	 * @param serverEqpmnVO
	 */
    @IncludedInfo(name="서버정보관리", order = 1170 ,gid = 60)
    @RequestMapping(value="/sym/sym/srv/selectServerEqpmnList.do")
	public String selectServerEqpmnList(@ModelAttribute("serverEqpmnVO") ServerEqpmnVO serverEqpmnVO,
			                             ModelMap model) throws Exception {

    	/** paging */
    	PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(serverEqpmnVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(serverEqpmnVO.getPageUnit());
		paginationInfo.setPageSize(serverEqpmnVO.getPageSize());

		serverEqpmnVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		serverEqpmnVO.setLastIndex(paginationInfo.getLastRecordIndex());
		serverEqpmnVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

		serverEqpmnVO.setServerEqpmnList(egovServerService.selectServerEqpmnList(serverEqpmnVO));

		model.addAttribute("serverEqpmnList", serverEqpmnVO.getServerEqpmnList());

        int totCnt = egovServerService.selectServerEqpmnListTotCnt(serverEqpmnVO);
		paginationInfo.setTotalRecordCount(totCnt);
        model.addAttribute("paginationInfo", paginationInfo);
        model.addAttribute("message", egovMessageSource.getMessage("success.common.select"));

		return "egovframework/com/sym/sym/srv/EgovServerEqpmnList";
	}

	/**
	 * 등록된 서버장비의 상세정보를 조회한다.
	 * @param serverEqpmnVO - 서버장비 Vo
	 * @return String - 리턴 Url
	 *
	 * @param serverEqpmnVO
	 */
    @RequestMapping(value="/sym/sym/srv/getServerEqpmn.do")
	public String selectServerEqpmn(@RequestParam("serverEqpmnId") String serverEqpmnId,
			                        @ModelAttribute("serverEqpmnVO") ServerEqpmnVO serverEqpmnVO,
					                 Model model) throws Exception {
		serverEqpmnVO.setServerEqpmnId(serverEqpmnId);
		model.addAttribute("serverEqpmn", egovServerService.selectServerEqpmn(serverEqpmnVO));
		model.addAttribute("message", egovMessageSource.getMessage("success.common.select"));

		return "egovframework/com/sym/sym/srv/EgovServerEqpmnDetail";
	}

	/**
	 * 서버장비정보 등록 화면으로 이동한다.
	 * @param serverEqpmnVO - 서버장비 Vo
	 * @return String - 리턴 Url
	 */
    @RequestMapping(value="/sym/sym/srv/addViewServerEqpmn.do")
	public String insertViewServerEqpmn(@ModelAttribute("serverEqpmnVO") ServerEqpmnVO serverEqpmnVO,
			                             ModelMap model) throws Exception {

    	model.addAttribute("serverEqpmn", serverEqpmnVO);
    	return "egovframework/com/sym/sym/srv/EgovServerEqpmnRegist";
	}

	/**
	 * 서버장비정보를 신규로 등록한다.
	 * @param serverEqpmn - 서버장비 model
	 * @return String - 리턴 Url
	 *
	 * @param serverEqpmn
	 */
    @RequestMapping(value="/sym/sym/srv/addServerEqpmn.do")
	public String insertServerEqpmn(@ModelAttribute("serverEqpmnVO") ServerEqpmnVO serverEqpmnVO,
			                        @ModelAttribute("serverEqpmn") ServerEqpmn serverEqpmn,
			                         BindingResult bindingResult,
				                     ModelMap model) throws Exception {

		beanValidator.validate(serverEqpmn, bindingResult); //validation 수행

		if (bindingResult.hasErrors()) {
    		model.addAttribute("serverEqpmnVO", serverEqpmnVO);
    		return "egovframework/com/sym/sym/srv/EgovServerEqpmnRegist";
		} else {
	   	    LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	   	    serverEqpmn.setFrstRegisterId(user.getId());
	   	    serverEqpmn.setLastUpdusrId(user.getId());
	   	    serverEqpmn.setServerEqpmnId(egovServerEqpmnIdGnrService.getNextStringId());
	   	    model.addAttribute("serverEqpmn", egovServerService.insertServerEqpmn(serverEqpmn, serverEqpmnVO));
			model.addAttribute("message", egovMessageSource.getMessage("success.common.insert"));
			return "egovframework/com/sym/sym/srv/EgovServerEqpmnDetail";
		}
	}

	/**
	 * 서버장비정보 수정 화면으로 이동한다.
	 * @param serverEqpmnVO - 서버장비 Vo
	 * @return String - 리턴 Url
	 */
    @RequestMapping(value="/sym/sym/srv/updtViewServerEqpmn.do")
	public String updateViewServerEqpmn(@RequestParam("serverEqpmnId") String serverEqpmnId,
			                            @ModelAttribute("serverEqpmnVO") ServerEqpmnVO serverEqpmnVO,
			                             ModelMap model) throws Exception {

    	serverEqpmnVO.setServerEqpmnId(serverEqpmnId);
		model.addAttribute("serverEqpmn", egovServerService.selectServerEqpmn(serverEqpmnVO));
		model.addAttribute("message", egovMessageSource.getMessage("success.common.select"));
    	return "egovframework/com/sym/sym/srv/EgovServerEqpmnUpdt";
	}

	/**
	 * 기 등록된 서버장비정보를 수정한다.
	 * @param serverEqpmn - 서버장비 model
	 * @return String - 리턴 Url
	 *
	 * @param serverEqpmn
	 */
    @RequestMapping(value="/sym/sym/srv/updtServerEqpmn.do")
	public String updateServerEqpmn(@ModelAttribute("serverEqpmn") ServerEqpmn serverEqpmn,
                                     BindingResult bindingResult,
                                     SessionStatus status,
                                     ModelMap model) throws Exception {

		beanValidator.validate(serverEqpmn, bindingResult); //validation 수행

		if (bindingResult.hasErrors()) {
    		model.addAttribute("serverEqpmnVO", serverEqpmn);
    		return "egovframework/com/sym/sym/srv/EgovServerEqpmnUpdt";
		} else {
	   	    LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	   	    serverEqpmn.setLastUpdusrId(user.getId());
	   	    egovServerService.updateServerEqpmn(serverEqpmn);
	   	    status.setComplete();
			model.addAttribute("message", egovMessageSource.getMessage("success.common.update"));
			return "forward:/sym/sym/srv/getServerEqpmn.do";
		}
	}

	/**
	 * 기 등록된 서버장비정보를 삭제한다.
	 * @param serverEqpmn - 서버장비 model
	 * @return String - 리턴 Url
	 *
	 * @param serverEqpmn
	 */
    @RequestMapping(value="/sym/sym/srv/removeServerEqpmn.do")
	public String deleteServerEqpmn(@RequestParam("serverEqpmnId") String serverEqpmnId,
                                    @ModelAttribute("serverEqpmn") ServerEqpmn serverEqpmn,
                                    ModelMap model) throws Exception {
		serverEqpmn.setServerEqpmnId(serverEqpmnId);
		egovServerService.deleteServerEqpmn(serverEqpmn);
		model.addAttribute("message", egovMessageSource.getMessage("success.common.delete"));
		return "forward:/sym/sym/srv/selectServerEqpmnList.do";
	}

	/**
	 * 서버정보관리 목록화면으로 이동
	 * @return String
	 */
    @RequestMapping(value="/sym/sym/srv/selectServerListView.do")
	public String selectServerListView() throws Exception {
		return "egovframework/com/sym/sym/srv/EgovServerList";
	}

	/**
	 * 서버정보를 관리하기 위해 등록된 서버목록을 조회한다.
	 * @param serverVO - 서버 Vo
	 * @return String - 리턴 Url
	 *
	 * @param serverVO
	 */
    @IncludedInfo(name="서버(S/W)목록", order = 1171 ,gid = 60)
    @RequestMapping(value="/sym/sym/srv/selectServerList.do")
	public String selectServerList(@ModelAttribute("serverVO") ServerVO serverVO,
			                        ModelMap model) throws Exception {

    	/** paging */
    	PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(serverVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(serverVO.getPageUnit());
		paginationInfo.setPageSize(serverVO.getPageSize());

		serverVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		serverVO.setLastIndex(paginationInfo.getLastRecordIndex());
		serverVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

		serverVO.setServerList(egovServerService.selectServerList(serverVO));

		model.addAttribute("serverList", serverVO.getServerList());

        int totCnt = egovServerService.selectServerListTotCnt(serverVO);
		paginationInfo.setTotalRecordCount(totCnt);
        model.addAttribute("paginationInfo", paginationInfo);
        model.addAttribute("message", egovMessageSource.getMessage("success.common.select"));

		return "egovframework/com/sym/sym/srv/EgovServerList";
	}

	/**
	 * 등록된 서버의 상세정보를 조회한다.
	 * @param serverVO - 서버 Vo
	 * @return String - 리턴 Url
	 *
	 * @param serverVO
	 */
    @RequestMapping(value="/sym/sym/srv/getServer.do")
	public String selectServer(@RequestParam("serverId") String serverId,
			                   @ModelAttribute("serverVO") ServerVO serverVO,
			                    Model model) throws Exception {

    	serverVO.setServerId(serverId);
    	model.addAttribute("server", egovServerService.selectServer(serverVO));
		model.addAttribute("serverEqpmnRelateDetailList", egovServerService.selectServerEqpmnRelateDetail(serverVO));
		model.addAttribute("serverEqpmnRelateDetailCount", egovServerService.selectServerEqpmnRelateDetailTotCnt(serverVO));
		model.addAttribute("message", egovMessageSource.getMessage("success.common.select"));

		return "egovframework/com/sym/sym/srv/EgovServerDetail";
	}

	/**
	 * 서버정보 등록 화면으로 이동한다.
	 * @param serverVO - 서버 Vo
	 * @return String - 리턴 Url
	 */
    @RequestMapping(value="/sym/sym/srv/addViewServer.do")
	public String insertViewServer(@ModelAttribute("serverVO") ServerVO serverVO,
			                        ModelMap model) throws Exception {

    	model.addAttribute("cmmCodeDetailList", getCmmCodeDetailList(new ComDefaultCodeVO(),"COM064"));
    	model.addAttribute("server", serverVO);
    	return "egovframework/com/sym/sym/srv/EgovServerRegist";
	}

	/**
	 * 서버정보를 신규로 등록한다.
	 * @param server - 서버 model
	 * @return String - 리턴 Url
	 *
	 * @param server
	 */
    @RequestMapping(value="/sym/sym/srv/addServer.do")
	public String insertServer(@ModelAttribute("serverVO") ServerVO serverVO,
			                   @ModelAttribute("server") Server server,
			                    BindingResult bindingResult,
			                    ModelMap model) throws Exception {

    	beanValidator.validate(server, bindingResult); //validation 수행

    	if (bindingResult.hasErrors()) {
    		model.addAttribute("serverVO", serverVO);
    		return "egovframework/com/sym/sym/srv/EgovServerRegist";
    	} else {
    		LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
    		server.setFrstRegisterId(user.getId());
    		server.setLastUpdusrId(user.getId());
    		server.setServerId(egovServerIdGnrService.getNextStringId());
	   	    model.addAttribute("server", egovServerService.insertServer(server, serverVO));
			model.addAttribute("message", egovMessageSource.getMessage("success.common.insert"));
			return "egovframework/com/sym/sym/srv/EgovServerDetail";
    	}
	}

	/**
	 * 서버정보 수정 화면으로 이동한다.
	 * @param serverVO - 서버 Vo
	 * @return String - 리턴 Url
	 */
    @RequestMapping(value="/sym/sym/srv/updtViewServer.do")
	public String updateViewServer(@RequestParam("serverId") String serverId,
			                       @ModelAttribute("serverVO") ServerVO serverVO,
			                        ModelMap model) throws Exception {

    	serverVO.setServerId(serverId);
		model.addAttribute("server", egovServerService.selectServer(serverVO));
		model.addAttribute("cmmCodeDetailList", getCmmCodeDetailList(new ComDefaultCodeVO(),"COM064"));
		model.addAttribute("message", egovMessageSource.getMessage("success.common.select"));
    	return "egovframework/com/sym/sym/srv/EgovServerUpdt";
	}

	/**
	 * 기 등록된 서버정보를 수정한다.
	 * @param server - 서버 model
	 * @return String - 리턴 Url
	 *
	 * @param server
	 */
    @RequestMapping(value="/sym/sym/srv/updtServer.do")
	public String updateServer(@ModelAttribute("server") Server server,
			                    BindingResult bindingResult,
                                SessionStatus status,
                                ModelMap model) throws Exception {

		beanValidator.validate(server, bindingResult); //validation 수행

		if (bindingResult.hasErrors()) {
    		model.addAttribute("serverVO", server);
    		return "egovframework/com/sym/sym/srv/EgovServerUpdt";
		} else {
	   	    LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	   	    server.setLastUpdusrId(user.getId());
	   	    egovServerService.updateServer(server);
	   	    status.setComplete();
			model.addAttribute("message", egovMessageSource.getMessage("success.common.update"));
			return "forward:/sym/sym/srv/getServer.do";
		}
	}

	/**
	 * 기 등록된 서버정보를 삭제한다.
	 * @param server - 서버 model
	 * @return String - 리턴 Url
	 *
	 * @param server
	 */
    @RequestMapping(value="/sym/sym/srv/removeServer.do")
	public String deleteServer(@RequestParam("serverId") String serverId,
                               @ModelAttribute("server") Server server,
                                ModelMap model) throws Exception {

		server.setServerId(serverId);
		egovServerService.deleteServer(server);
		model.addAttribute("message", egovMessageSource.getMessage("success.common.delete"));
		return "forward:/sym/sym/srv/selectServerList.do";
	}

	/**
	 * 서버장비관계정보를 관리하기 위해 대상 서버장비목록을 조회한다.
	 * @param serverEqpmnRelateVO - 서버장비관계 Vo
	 * @return String - 리턴 Url
	 *
	 * @param serverEqpmnRelateVO
	 */
    @RequestMapping(value="/sym/sym/srv/selectServerEqpmnRelateList.do")
	public String selectServerEqpmnRelateList(@RequestParam("strServerId") String strServerId,
			                                  @ModelAttribute("serverVO") ServerVO serverVO,
			                                  @ModelAttribute("serverEqpmnRelateVO") ServerEqpmnRelateVO serverEqpmnRelateVO,
			                                   ModelMap model) throws Exception {

    	/** paging */
    	PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(serverEqpmnRelateVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(serverEqpmnRelateVO.getPageUnit());
		paginationInfo.setPageSize(serverEqpmnRelateVO.getPageSize());

		serverEqpmnRelateVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		serverEqpmnRelateVO.setLastIndex(paginationInfo.getLastRecordIndex());
		serverEqpmnRelateVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

		serverEqpmnRelateVO.setServerId(strServerId);
		serverVO.setServerId(strServerId);

		serverEqpmnRelateVO.setServerEqpmnRelateList(egovServerService.selectServerEqpmnRelateList(serverEqpmnRelateVO));

		model.addAttribute("serverEqpmnRelateList", serverEqpmnRelateVO.getServerEqpmnRelateList());
		model.addAttribute("server", egovServerService.selectServer(serverVO));

        int totCnt = egovServerService.selectServerEqpmnRelateListTotCnt(serverEqpmnRelateVO);
		paginationInfo.setTotalRecordCount(totCnt);
        model.addAttribute("paginationInfo", paginationInfo);
        model.addAttribute("message", egovMessageSource.getMessage("success.common.select"));

		return "egovframework/com/sym/sym/srv/EgovServerEqpmnRelateRegist";
	}

	/**
	 * 서버장비관계정보를 등록 또는 삭제처리한다.
	 * @param serverEqpmnRelate - 서버장비관계 model
	 * @return String - 리턴 Url
	 *
	 * @param serverEqpmnRelate
	 */
    @RequestMapping(value="/sym/sym/srv/saveServerEqpmnRelate.do")
	public String saveServerEqpmnRelate(@RequestParam("serverId") String serverId,
                                        @RequestParam("serverEqpmnIds") String serverEqpmnIds,
                                        @RequestParam("regYns") String regYns,
                                        @ModelAttribute("serverEqpmnRelate") ServerEqpmnRelate serverEqpmnRelate,
                                         SessionStatus status,
   			                             ModelMap model) throws Exception {

    	String [] strServerEqpmnIds = serverEqpmnIds.split(";");
    	String [] strRegYns = regYns.split(";");

    	serverEqpmnRelate.setServerId(serverId);

    	for(int i=0; i<strServerEqpmnIds.length;i++) {
    		serverEqpmnRelate.setServerId(serverId);
    		serverEqpmnRelate.setServerEqpmnId(strServerEqpmnIds[i]);
    		if(strRegYns[i].equals("Y"))
    			egovServerService.insertServerEqpmnRelate(serverEqpmnRelate);
    		else
    			egovServerService.deleteServerEqpmnRelate(serverEqpmnRelate);
    	}

        status.setComplete();
        model.addAttribute("message", egovMessageSource.getMessage("success.common.insert"));
		return "forward:/sym/sym/srv/selectServerEqpmnRelateList.do";
	}

    /**
	 * 공통코드 호출
	 * @param comDefaultCodeVO ComDefaultCodeVO
	 * @param codeId String
	 * @return List
	 * @exception Exception
	 */
    public List<?> getCmmCodeDetailList(ComDefaultCodeVO comDefaultCodeVO, String codeId)  throws Exception {
    	comDefaultCodeVO.setCodeId(codeId);
    	return EgovCmmUseService.selectCmmCodeDetail(comDefaultCodeVO);
    }
}


text:
export const assign = (base, additional) => {
  return Object.assign({}, base, additional)
}


text:
/**
 * @interface {babel.PluginPass}
 * @return {babel.PluginObj}
 */
module.exports = function () {
  return {
    name: 'remove-strict-directives',
    visitor: {
      Directive(path) {
        const {node} = path;
        if (node.value.value === 'use strict') {
          path.remove();
        }
      },
    },
  };
};


text:
function Class() {}
Class.prototype.hello = "string";

var c = new Class;
c.hello = nobodyKnows();

c.hello; //: string


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="185px"
    android:layout_height="278px">

    <ImageView
        android:id="@+id/movie_poster_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/no_movie_poster"
        android:scaleType="fitXY" />

    <TextView
        android:id="@+id/movie_title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fontFamily="Arial"
        android:gravity="center_vertical|center_horizontal"
        android:paddingBottom="42dp"
        android:textColor="@color/detail_view_text_color"
        android:textSize="@dimen/detail_text_view_title_poster_text_size"
        android:textStyle="bold" />

</RelativeLayout>


text:
Projet a effacer
Hello world!


text:
package com.maven.project.consumer.errorhandler;

// Imports--------------------------------------------------
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ErrorHandler;

public class UserInteractionMajorListenerErrorHandler implements ErrorHandler {

	// Variables--------------------------------------------------
	Logger logger = LoggerFactory.getLogger(UserInteractionMajorListenerErrorHandler.class);

	// Constructors--------------------------------------------------
	public UserInteractionMajorListenerErrorHandler() {
	}

	// Methods--------------------------------------------------
	public void handleError(Throwable t) {

		logger.error("error in UserInteractionMajorListenerErrorHandler:", t);

	}

}


text:
/**
 * Created by harttle on 12/17/14.
 */

angular.module('data')
    .service('webSocketService', ['$rootScope', 'todoWebsocketService', 'todolistWebsocketService', 'commentWebSocketService',
        'documentWebSocketService', 'discussionWebSocketService', 'uploadsWebsocketService', 'bugWebsocketService','storyWebsocketService',
        'iterationWebsocketService',
        function($rootScope, todoWebsocketService, todolistWebsocketService, commentWebSocketService, documentWebSocketService,
                 discussionWebSocketService, uploadsWebsocketService, bugWebsocketService,storyWebsocketService, iterationWebsocketService) {

            // service mapping,映射 attachType 到数据 service
            var serviceMap = {
                'todo'      : todoWebsocketService,
                'todolist'  : todolistWebsocketService,
                'comment'   : commentWebSocketService,
                'document'  : documentWebSocketService,
                'discussion': discussionWebSocketService,
                'upload'    : uploadsWebsocketService,
                'bug'       : bugWebsocketService,
                'story'     : storyWebsocketService,
                'iteration' : iterationWebsocketService
            };

            // action mapping, 映射 action 到数据 service 的方法
            var actionMap = {
                'delete' : 'delete',
                'discard': 'delete',
                'archive': 'delete',
                'create' : 'add',
                'update' : 'update',
                'reply'  : 'add',
                'default': 'update',
                'recover': 'add',
                'copy'   : 'copy'
            };

            // 处理一个 web socket
            //action
            this.activityHandler = function(activity) {

                var s = serviceMap[activity.attachType],
                    a = actionMap[activity.action] || actionMap["default"];

                if(s && s[a]) {
                    s[a](activity.attachObject, activity);
                    if (!$rootScope.$$phase) $rootScope.$apply();
                }
            }
        }]);


text:
extern crate proc_macro;
use darling::{util::Flag, FromMeta};
use proc_macro::TokenStream;
use quote::quote;
use std::{fs::File, io::Write};

#[derive(Debug, FromMeta)]
struct MacroArgs {
    #[darling(default)]
    names:             Option<String>,
    #[darling(rename = "man")]
    help:              String,
    #[darling(default)]
    authors:           Flag,
    #[darling(rename = "desc")]
    short_description: String,
}

// TODO: It would be better if Man pages could be parsed of comments
#[proc_macro_attribute]
pub fn builtin(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::ItemFn);
    let attrs = syn::parse_macro_input!(attr as syn::AttributeArgs);
    let syn::ItemFn { vis, sig, block, .. } = &input;
    let syn::Signature { ident, fn_token, inputs, output, .. } = sig;

    let args = match MacroArgs::from_list(&attrs) {
        Ok(v) => v,
        Err(e) => return e.write_errors().into(),
    };

    let name = quote::format_ident!("builtin_{}", &ident, span = ident.span());

    let help = args.help.trim();
    let names = args.names.unwrap_or_else(|| ident.to_string());

    let bugs = "BUGS
    Please report all bugs at https://gitlab.redox-os.org/redox-os/ion/issues.
    Ion is still in active development and help in finding bugs is much appreciated!";

    let extra = "

AUTHORS
    The Ion developers, under the Redox OS organisation"
        .to_string();
    let man = format!(
        "NAME\n    {names} - {short_description}\n\n{help}\n\n{bugs}{extra}",
        names = names,
        short_description = args.short_description,
        help = help,
        bugs = bugs,
        extra = if args.authors.is_none() { &extra } else { "" },
    );
    let help = format!("{} - {}\n\n```txt\n{}\n```", names, args.short_description, help);

    if cfg!(feature = "man") {
        let mut man = File::create(format!("manual/builtins/{}.1", &ident)).unwrap();
        man.write_all(help.as_bytes()).unwrap();
    }

    let result = quote! {
        #[doc = #help]
        #vis #fn_token #name(#inputs) #output {
            if ion_shell::builtins::man_pages::check_help(args, #man) {
                return ion_shell::builtins::Status::SUCCESS;
            }
            #block
        }
    };
    result.into()
}


text:
//
//  dwarf_dummy_debug_line_section.h
//  DSYMCreator
//
//  Created by oldman on 9/1/16.
//
//

#ifndef dwarf_dummy_debug_line_section_h
#define dwarf_dummy_debug_line_section_h

#include "common.h"

struct DwarfDummyDebugLineSection {
    ByteBuffer dump() const;
};

#endif /* dwarf_dummy_debug_line_section_h */


text:
=============================
LineaLeastSquares.jl Examples
=============================

This tutorial showcases LinearLeastSquares.jl through a few involved examples of linearly
constrained least squares problems. We'll refer to LinearLeastSquares.jl as "LLS"
throughout.
The plots generated by the following examples use the Gadfly package.
The documentation on how to use Gadfly can be found `here <http://gadflyjl.org/>`_,
but by no means is it necessary to read unless you would like to create plots for yourself.
To install Gadfly, run the following command in a Julia shell

.. code-block:: none

  Pkg.add("Gadfly")

Some of the examples will also use data files, which can all be found `here <https://github.com/davidlizeng/LinearLeastSquares.jl/tree/master/examples/>`_.

Regression
==========
Regression is the problem of trying to fit a function to some data.
In this example, we will frame some simple regression problems as
unconstrained least squares problems for LLS to solve.

We are given n points, represented by two n-by-1 vectors, ``x_data`` and ``y_data``. The x and y coordinates of the i-th point are given by the i-th entries of ``x_data`` and ``y_data``, respectively.

We'll start by generating and visualizing some data to get a better sense of the problem at hand:

.. code-block:: none

  # Set the random seed to get consistent data
  srand(1)

  # Number of examples to use
  n = 100

  # Specify the true value of the variable
  true_coeffs = [2; -2; 0.5]

  # Generate data
  x_data = rand(n, 1) * 5
  x_data_expanded = hcat([x_data .^ i for i in 1 : 3]...)
  y_data = x_data_expanded * true_coeffs + 0.5 * rand(n, 1)

  p = plot(
    x=x_data, y=y_data, Geom.point,
    Theme(panel_fill=color("white"))
  )

The following graph of the data will appear

.. image:: data.png

Linear Regression
-----------------
We will first try to fit a line to the data. A general function for a line is

.. math::
  f(x) = \alpha + \beta x

where :math:`\alpha` is the offset and :math:`\beta` is the slope.
We would like to pick :math:`\alpha` and :math:`\beta` so that our data points lie "close" to
our line. For a point with coordinates :math:`x` and :math:`y` the residual between the point
and our line is defined as

.. math::
  r(x, y) = f(x) - y.

One reasonable way to measure the how different line is from the data is to
sum the squares of the residuals between each point in the data and the line:

.. math::
  E(\alpha, \beta) = \sum_{i = 1}^n (r(x_i, y_i))^2 = \sum_{i = 1}^n (\alpha + \beta x_i - y_i)^2.

We would like to choose :math:`\alpha` and :math:`\beta` to minimize this error.
We can now frame this problem in Julia code and solve our problem using LLS:

.. code-block:: none

  slope = Variable()
  offset = Variable()
  line = offset + x_data * slope
  residuals = line - y_data
  fit_error = sum_squares(residuals)
  optval = minimize!(fit_error)

  # plot the data and the line
  t = [0; 5; 0.1]
  p = plot(
    layer(x=x_data, y=y_data, Geom.point),
    layer(x=t, y=evaluate(slope) * t + evaluate(offset), Geom.line),
    Theme(panel_fill=color("white"))
  )

The line of best fit on our data is shown below:

  .. image:: linear_regression.png

Quadratic Regression
--------------------
A line is probably not the best function to fit to this data. Instead, let's try
to fit a quadratic function, which has the form:

.. math::
  f(x) = \alpha + \beta x + \gamma x ^ 2

where the new coefficient :math:`\gamma` corresponds to the quadratic term
A similar residual function from the linear regression example can be used here;
we measure the error of our quadratic fit by summing the squares of the
residuals

.. math::
  E(\alpha, \beta, \gamma) = \sum_{i = 1}^n (r(x_i, y_i))^2 = \sum_{i = 1}^n (\alpha + \beta x_i + \gamma x_i^2 - y_i)^2.

Again, we pick our coefficients to minimize the error.
Here is the Julia code to solve this problem using LLS and plot the quadratic:

.. code-block:: none

  quadratic_coeff = Variable()
  slope = Variable()
  offset = Variable()
  quadratic = offset + x_data * slope + quadratic_coeff * x_data .^ 2
  residuals = quadratic - y_data
  fit_error = sum_squares(residuals)
  optval = minimize!(fit_error)

  # Create some evenly spaced points for plotting, again replicate powers
  t = reshape([0 : 0.1 : 5], length([0 : 0.1 : 5]), 1)
  t_squared = t .^ 2

  # Plot our regressed function
  p = plot(
    layer(x=x_data, y=y_data, Geom.point),
    layer(x=t, y=evaluate(offset) + t * evaluate(slope) + t_squared * evaluate(quadratic_coeff), Geom.line),
    Theme(panel_fill=color("white"))
  )

.. image:: quadratic_regression.png

A much better fit than the line!

Control
=======
A simple control problem on a system usually involves a variable :math:`x(t)`
that denotes the state of the system over time, and a variable :math:`u(t)` that
denotes the input into the system over time. Linear constraints are used to
capture the evolution of the system over time:

.. math::
  x(t) = Ax(t - 1) + Bu(t), \ \mbox{for} \ t = 1,\ldots, T,

where the numerical matrices :math:`A` and :math:`B` are called the dynamics and input matrices,
respectively.

The goal of the control problem is to find a sequence of inputs
:math:`u(t)` that will allow the state :math:`x(t)` to achieve specified values
at certain times. For example, we can specify initial and final states of the system:

.. math::
  \begin{align*}
    x(0) &= x_i \\
    x(T) &= x_f
  \end{align*}

Additional states between the initial and final states can also be specified. These
are known as waypoint constraints. Often, the input and state of the system will
have physical meaning, so we often want to find a sequence inputs that also
minimizes a least squares objective like the following:

.. math::
  \sum_{t = 0}^T \|Fx(t)\|^2_2 + \sum_{t = 1}^T\|Gu(t)\|^2_2,

where :math:`F` and :math:`G` are numerical matrices.

We'll now apply the basic format of the control problem to an example of controlling
the motion of an object in a fluid over :math:`T` intervals, each of :math:`h` seconds.
The state of the system at time interval :math:`t` will be given by the position and the velocity of the
object, denoted :math:`p(t)` and :math:`v(t)`, while the input will be forces
applied to the object, denoted by :math:`f(t)`.
By the basic laws of physics, the relationship between force, velocity, and position
must satisfy:

.. math::
  \begin{align*}
    p(t+1) &= p(t) + h v(t) \\
    v(t+1) &= v(t) + h a(t)
  \end{align*}.

Here, :math:`a(t)` denotes the acceleration at time :math:`t`, for which we we use
:math:`a(t) = f(t) / m + g - d v(t)`,
where :math:`m`, :math:`d`, :math:`g` are constants for the mass of the object, the drag
coefficient of the fluid, and the acceleration from gravity, respectively.

Additionally, we have our initial/final position/velocity conditions:

.. math::
  \begin{align*}
    p(1) &= p_i\\
    v(1) &= v_i\\
    p(T+1) &= p_f\\
    v(T+1) &= 0
  \end{align*}

One reasonable objective to minimize would be

.. math::

  \mbox{objective} = \mu \sum_{t = 1}^{T+1} (v(t))^2 + \sum_{t = 1}^T (f(t))^2

We would like to keep both the forces small to perhaps save fuel, and keep
the velocities small for safety concerns.
Here :math:`\mu` serves as a parameter to control which part of the objective we
deem more important, keeping the velocity small or keeping the force small.

The following code builds and solves our control example:

.. code-block:: none

  # Some constraints on our motion
  # The object should start from the origin, and end at rest
  initial_velocity = [-20; 100]
  final_position = [100; 100]

  T = 100 # The number of timesteps
  h = 0.1 # The time between time intervals
  mass = 1 # Mass of object
  drag = 0.1 # Drag on object
  g = [0, -9.8] # Gravity on object

  # Declare the variables we need
  position = Variable(2, T)
  velocity = Variable(2, T)
  force = Variable(2, T - 1)

  # Create a problem instance
  mu = 1
  constraints = []

  # Add constraints on our variables
  for i in 1 : T - 1
    constraints += position[:, i + 1] == position[:, i] + h * velocity[:, i]
  end

  for i in 1 : T - 1
    acceleration = force[:, i]/mass + g - drag * velocity[:, i]
    constraints += velocity[:, i + 1] == velocity[:, i] + h * acceleration
  end

  # Add position constraints
  constraints += position[:, 1] == 0
  constraints += position[:, T] == final_position

  # Add velocity constraints
  constraints += velocity[:, 1] == initial_velocity
  constraints += velocity[:, T] == 0

  # Solve the problem
  optval = minimize!(sum_squares(force), constraints)

We can plot the trajectory taken by the object. The blue point denotes the initial
position, and the green point denotes the final position.

.. code-block:: none

  pos = evaluate(position)
  p = plot(
    layer(x=[pos[1, 1]], y=[pos[2, 1]], Geom.point, Theme(default_color=color("blue"))),
    layer(x=[pos[1, T]], y=[pos[2, T]], Geom.point, Theme(default_color=color("green"))),
    layer(x=pos[1, :], y=pos[2, :], Geom.line(preserve_order=true)),
    Theme(panel_fill=color("white"))
  )

.. image:: position.png

We can also see how the magnitude of the force changes over time.

.. code-block:: none

  p = plot(x=1:T, y=sum(evaluate(force).^2, 1), Geom.line, Theme(panel_fill=color("white")))

.. image:: force.png

Image Processing
================

Tomography
----------

Tomography is the process of reconstructing a density distribution from given
integrals over sections of the distribution. In our example, we will
work with tomography on black and white images.
Suppose :math:`x` be the vector of :math:`n` pixel densities, with :math:`x_j`
denoting how white pixel :math:`j` is.
Let :math:`y` be the vector of :math:`m` line integrals over the image, with :math:`y_i`
denoting the integral for line :math:`i`.
We can define a matrix :math:`A` to describe the geometry of the lines. Entry
:math:`A_{ij}` describes how much of pixel :math:`j` is intersected by line :math:`i`.
Assuming our measurements of the line integrals are perfect, we have the relationship that

.. math::
  y = Ax

However, anytime we have measurements, there are usually small errors that occur.
Therefore it makes sense to try to minimize

.. math::
  \|y - Ax\|_2^2.

This is simply an unconstrained least squares problem; something we can
readily solve in LLS!

.. code-block:: none

  line_mat_x = readdlm("tux_sparse_x.txt")
  line_mat_y = readdlm("tux_sparse_y.txt")
  line_mat_val = readdlm("tux_sparse_val.txt")
  line_vals = readdlm("tux_sparse_lines.txt")

  # Form the sparse matrix from the data
  # Image is 50 x 50
  img_size = 50
  # The number of pixels in the image
  num_pixels = img_size * img_size

  line_mat = spzeros(3300, num_pixels)

  num_vals = length(line_mat_val)

  for i in 1:num_vals
    x = int(line_mat_x[i])
    y = int(line_mat_y[i])
    line_mat[x + 1, y + 1] = line_mat_val[i]
  end

  x = Variable(num_pixels)
  objective = sum_squares(line_mat * x - line_vals)
  optval = minimize!(objective)

  rows = zeros(img_size*img_size)
  cols = zeros(img_size*img_size)
  for i = 1:img_size
    for j = 1:img_size
      rows[(i-1)*img_size + j] = i
      cols[(i-1)*img_size + j] = img_size + 1 - j
    end
  end

  p = plot(
    x=rows, y=cols, color=reshape(evaluate(x), img_size, img_size), Geom.rectbin,
    Scale.ContinuousColorScale(Scale.lab_gradient(color("black"), color("white")))
  )

The final result of the tomography will look something like

.. image:: tomography.png

Machine Learning
================

Binary Classification
---------------------
One common problem found in machine learning is the classification of a group of objects into two subgroups.
In this example, we will try to separate sports articles from
other texts in a collection of documents.

When classifying text documents, one of the most common techniques is to build
a term-by-document frequency matrix :math:`F`, where :math:`F_{ij}`
reflects the frequency of term :math:`j` in document :math:`i`.

The documents are then split into a training and testing set. For each document
in the training example, we also label the document with a label. In this case,
sports articles are labelled with a :math:`1` and all other text documents are
labelled with a :math:`-1`.
One reasonable approach to classify the documents is to model the label
as an affine function of the term frequencies of the document:

.. math::
  \mbox{label}(i) = v + \sum_{j = 1}^n w_jF_{ij}.

The goal now is to find a scalar :math:`v` and a weight vector :math:`w`, where :math:`w_j` reflects how
important term :math:`j` is in determining the label of the document. In our context, a positive value
means that the term is often seen in sports articles, while a negative value means
the term is often seen in the other documents. One reasonable approach to
finding the best :math:`w` and :math:`v` is to minimize the following objective:

.. math::
  \sum_{i = 1}^m  \left(\mbox{label}(i) - v - \sum_{j = 1}^n w_jF_{ij}\right)^2 + \lambda \sum_{j = 1}^n w_j^2

The first part of the objective is to ensure that our linear model actually closely
reproduces the labels of our training documents. The second part of the objective
ensures that the components of :math:`w` are relatively small.
Keeping :math:`w` small allows our model to behave better on documents not in the training set.
The regularization parameter :math:`\lambda`
is used to control how much we should prioritize keeping :math:`w` small versus
how close the affine function should fit the labels.

Here is the LLS code:

.. code-block:: none

  # read in the data
  include("MatrixMarket.jl")
  using MatrixMarket
  A = full(MatrixMarket.mmread("largeCorpus.mtx"))

  # extract the classes of each document
  classes = A[:,1]
  # TODO: modify classes so that 4 5 6 are 1 2 3
  classes[classes .> 3] = classes[classes .> 3] - 3
  A = A[:, 2:end]

  # split into train/test
  numData = size(A, 1)
  data = randperm(numData)
  ind = floor(numData*0.7)
  training = data[1:ind]
  test = data[ind+1:end]
  trainDocuments = A[training,:]
  trainClasses = classes[training,:]
  testDocuments = A[test,:]
  testClasses = classes[test,:]

  # change all other than sports to -1 (sports is 1)
  holdClass = 1
  trainClasses[trainClasses .!= holdClass] = -1
  trainClasses[trainClasses .== holdClass] = 1
  testClasses[testClasses .!= holdClass] = -1
  testClasses[testClasses .== holdClass] = 1

  # build the problem and solve with LLS
  lambda = 100
  w = Variable(size(A, 2))
  v = Variable()
  objective = sum_squares(trainDocuments * w + v - trainClasses) + lambda * sum_squares(w)
  optval = minimize!(objective)

We can now sort our weight vector :math:`w` to see which words were the most
indicative of sports articles and which were most indicative of nonsports.

.. code-block:: none

  # print out the 5 words most indicative of sports and nonsports
  words = String[]
  f = open("largeCorpusfeatures.txt")
  for i = 1:length(evaluate(w))
    push!(words, readline(f))
  end
  indices = sortperm(vec(evaluate(w)))
  for i = 1:5
    print(words[indices[i]])
  end
  for i = 0:4
    print(words[indices[length(words) - i]])
  end

Each run will yield different words, but it'll be clear which words
come from sports articles.

Time Series Analysis
====================
A time series is a sequence of data points, each associated with a time.
In our example, we will work with a time series of daily
temperatures in the city of Melbourne, Australia over a period of a few years.
Let :math:`x` be the vector of the time series, and :math:`x_i` denote
the temperature in Melbourne on day :math:`i`.
Here is a picture of the time series:

.. image:: melbourne.png

We can quickly compute the mean of the time series to be :math:`11.2`. If
we were to always guess the mean as the temperature of Melbourne on a given day,
the RMS error of our guesswork would be :math:`4.1`. We'll try to lower
this RMS error by coming up with better ways to model the temperature than
guessing the mean.

A simple way to model this time series would be to find a smooth curve that
approximates the yearly ups and downs.
We can represent this model as a vector :math:`s` where :math:`s_i`
denotes the temperature on the :math:`i`-th day.
To force this trend to repeat yearly, we simply want

.. math::
  s_i = s_{i + 365}

for each applicable :math:`i`.

We also want our model to have two more properties. The first is that
the temperature on each day in our model should be relatively close to the actual temperature of that day.
The second is that our model needs to be smooth, so the change in temperature from day to
day should be relatively small. The following objective would capture both properties:

.. math::
  \sum_{i = 1}^n (s_i - x_i)^2 + \lambda \sum_{i = 2}^n(s_i - s_{i - 1})^2

where :math:`\lambda` is the smoothing parameter. The larger :math:`\lambda` is,
the smoother our model will be.

The following code uses LLS to find and plot the model:

.. code-block:: none

  temps = readdlm("melbourne_temps.txt", ',')
  n = size(temps)[1]
  p = plot(
    x=1:1500, y=temps[1:1500], Geom.line,
    Theme(panel_fill=color("white"))
  )
  # draw(PNG("melbourne.png", 16cm, 12cm), p)

  yearly = Variable(n)
  eq_constraints = []
  for i in 365 + 1 : n
    eq_constraints += yearly[i] == yearly[i - 365]
  end

  smoothing = 100
  smooth_objective = sum_squares(yearly[1 : n - 1] - yearly[2 : n])
  optval = minimize!(sum_squares(temps - yearly) + smoothing * smooth_objective, eq_constraints)
  residuals = temps - evaluate(yearly)

  # Plot smooth fit
  p = plot(
    layer(x=1:1500, y=evaluate(yearly)[1:1500], Geom.line, Theme(default_color=color("red"), line_width=2px)),
    layer(x=1:1500, y=temps[1:1500], Geom.line),
    Theme(panel_fill=color("white"))
  )

.. image:: yearly_fit.png

We can also plot the residual temperatures, :math:`r`, define as :math:`r = x - s`.

.. code-block:: none

  # Plot residuals for a few days
  p = plot(
    x=1:100, y=residuals[1:100], Geom.line,
    Theme(default_color=color("green"), panel_fill=color("white"))
  )

.. image:: residuals.png

Our smooth model has a RMS error of :math:`2.7`, a significant improvement from
just guessing the mean, but we can do better.

We now make the hypothesis that the residual temperature on a given day is
some linear combination of the previous :math:`5` days. Such a model is called
autoregressive. We are essentially trying to fit the residuals
as a function of other parts of the data itself.
We want to find a vector of coefficients :math:`a` such that

.. math::
  \mbox{r}(i) \approx \sum_{j = 1}^5 a_j \mbox{r}(i - j)

This can be done by simply minimizing the following sum of squares objective

.. math::
  \sum_{i = 6}^n \left(\mbox{r}(i) - \sum_{j = 1}^5 a_j \mbox{r}(i - j)\right)^2

The following LLS code solves this problem and plots our autoregressive model
against the actual residual temperatures:

.. code-block:: none

  # Generate the residuals matrix
  ar_len = 5
  residuals_mat = residuals[ar_len : n - 1]
  for i = 1:ar_len - 1
    residuals_mat = [residuals_mat residuals[ar_len - i : n - i - 1]]
  end

  # Solve autoregressive problem
  ar_coef = Variable(ar_len)
  optval2 = minimize!(sum_squares(residuals_mat * ar_coef - residuals[ar_len + 1 : end]))

  # plot autoregressive fit of daily fluctuations for a few days
  ar_range = 1:145
  day_range = ar_range + ar_len
  p = plot(
    layer(x=day_range, y=residuals[day_range], Geom.line, Theme(default_color=color("green"))),
    layer(x=day_range, y=residuals_mat[ar_range, :] * evaluate(ar_coef), Geom.line, Theme(default_color=color("red"))),
    Theme(panel_fill=color("white"))
  )

.. image:: ar_fit.png

Now, we can add our autoregressive model for the residual temperatures to our
smooth model to get an better fitting model for the daily temperatures in the city of
Melbourne:

.. code-block:: none

  total_estimate = evaluate(yearly)
  total_estimate[ar_len + 1 : end] += residuals_mat * evaluate(ar_coef)

  # plot final fit of data
  p = plot(
    layer(x=1:1500, y=total_estimate[1:1500], Geom.line, Theme(default_color=color("red"))),
    layer(x=1:1500, y=temps[1:1500], Geom.line),
    Theme(panel_fill=color("white"))
  )

.. image:: total_fit.png

The RMS error of this final model is :math:`2.3`.


text:
require 'faker'

User.delete_all
Question.delete_all
Answer.delete_all
Comment.delete_all

#create 10 dummy users
users = []
10.times.map do
  user = User.create!( :user_name => Faker::Internet.user_name,
                :email      => Faker::Internet.email,
                :password   => 'password' )
  users << user
end

questions_seed = ["Who goes there?", "Where'd you get the coconuts?", "In order to maintain air-speed velocity, a swallow needs to beat its wings forty-three times every second, right?", "Well, how'd you become king, then?", "How do you know she is a witch?", "A newt?", "What... is your name?", "What... is your quest?", "What... is your favourite colour?", "What... is the air-speed velocity of an unladen swallow?"]

questions = []

questions_seed.each do |question|
  description = Faker::Hipster.paragraph
  this_question = Question.new(  title: question,
                  description: description )
  this_question.user = users[rand(0..9)]
  this_question.save
  questions << this_question
end

answers = []

50.times.map do
  question = questions[rand(0..9)]
  user = users[rand(0..9)]

  text = Faker::Hipster.sentence(5)
  answer = Answer.new( text: text)

  answer.user = user
  question.answers << answer

  question.save
  user.save
  answer.save

  answers << answer
end

comments = []

25.times do
  question = questions[rand(0..9)]
  user = users[rand(0..9)]

  text = Faker::Hipster.sentence(5)
  comment = Comment.new(text: text)

  comment.user = user
  question.comments << comment

  comment.save
  user.save
  question.save

  comments << comment
end

25.times do
  answer = answers[rand(0..9)]
  user = users[rand(0..9)]

  text = Faker::Hipster.sentence(5)
  comment = Comment.new(text: text)
  comment.user = user
  answer.comments << comment

  answer.save
  comment.save
  user.save

  comments << comment
end

votes = []

100.times do
  answer = answers[rand(0..9)]
  user = users[rand(0..9)]

  vote = Vote.new()
  vote.user = user
  answer.votes << vote

  answer.save
  vote.save
  user.save

  votes << vote
end

100.times do
  question = questions[rand(0..9)]
  user = users[rand(0..9)]

  vote = Vote.new()
  vote.user = user
  question.votes << vote

  question.save
  vote.save
  user.save

  votes << vote
end


text:
.class public interface abstract Lcom/stericsson/hardware/fm/FmReceiver$OnPlayingInStereoListener;
.super Ljava/lang/Object;
.source "FmReceiver.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/stericsson/hardware/fm/FmReceiver;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "OnPlayingInStereoListener"
.end annotation

# virtual methods
.method public abstract onPlayingInStereo(Z)V
.end method


text:
<?php

namespace Symfony\Bridge\Propel1\Form\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

/**
 * Event Listener class for propel1_translation
 *
 * @author Patrick Kaufmann
 */
class TranslationFormListener implements EventSubscriberInterface
{
    private $columns;
    private $dataClass;

    public function __construct($columns, $dataClass)
    {
        $this->columns = $columns;
        $this->dataClass = $dataClass;
    }

    public static function getSubscribedEvents()
    {
        return array(
            FormEvents::PRE_SET_DATA => array('preSetData', 1),
        );
    }

    public function preSetData(FormEvent $event)
    {
        $form = $event->getForm();
        $data = $event->getData();

        if (!$data instanceof $this->dataClass) {
            return;
        }

        //loop over all columns and add the input
        foreach ($this->columns as $column => $options) {
            if (is_string($options)) {
                $column = $options;
                $options = array();
            }
            if (null === $options) {
                $options = array();
            }

            $type = 'text';
            if (array_key_exists('type', $options)) {
                $type = $options['type'];
            }
            $label = $column;
            if (array_key_exists('label', $options)) {
                $label = $options['label'];
            }

            $customOptions = array();
            if (array_key_exists('options', $options)) {
                $customOptions = $options['options'];
            }
            $options = array(
                'label' => $label.' '.strtoupper($data->getLocale())
            );

            $options = array_merge($options, $customOptions);

            $form->add($column, $type, $options);
        }
    }
}


text:
import deparam from 'can-util/js/deparam/deparam';
import can from 'can/';

deparam();
deparam = false;


text:
//
//  UIDevice+ECKit.m
//  ECKit
//
//  Created by Chris Streeter on 3/11/14.
//  Copyright (c) 2014 Educreations, Inc. All rights reserved.
//

#import "UIDevice+ECKit.h"

#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

@implementation UIDevice (ECKit)

+ (NSComparisonResult)eckit_compareToVersion:(NSString *)version
{
    return [[[self currentDevice] systemVersion] compare:version options:NSNumericSearch];
}

+ (BOOL)eckit_systemVersionIsEqual:(NSString *)version
{
    return [self eckit_compareToVersion:version] == NSOrderedSame;
}

+ (BOOL)eckit_systemVersionIsGreaterThan:(NSString *)version
{
    return [self eckit_compareToVersion:version] == NSOrderedDescending;
}

+ (BOOL)eckit_systemVersionIsGreaterThanOrEqual:(NSString *)version
{
    return [self eckit_compareToVersion:version] != NSOrderedAscending;
}

+ (BOOL)eckit_systemVersionIsLessThan:(NSString *)version
{
    return [self eckit_compareToVersion:version] == NSOrderedAscending;
}

+ (BOOL)eckit_systemVersionIsLessThanOrEqual:(NSString *)version
{
    return [self eckit_compareToVersion:version] != NSOrderedDescending;
}

//------------------------------------------------------------------------------
#pragma mark -
#pragma mark Device Family

- (UIDeviceFamily)eckit_deviceFamily
{
    switch ([self eckit_platform]) {
        case UIDeviceiPad1:
        case UIDeviceiPad2:
        case UIDeviceiPad4G:
        case UIDeviceiPad3:
        case UIDeviceiPadAir:
        case UIDeviceiPadAir2:
        case UIDeviceiPadMini:
        case UIDeviceiPadMiniRetina:
        case UIDeviceiPadMini3:
        case UIDeviceiPadSimulator:
        case UIDeviceiPadMini4:
        case UIDeviceiPadMini5:
        case UIDeviceiPadPro12inch:
        case UIDeviceiPadPro9inch:
        case UIDeviceUnknowniPad:
            return UIDeviceFamilyiPad;
        case UIDeviceiPhone1:
        case UIDeviceiPhone3G:
        case UIDeviceiPhone3GS:
        case UIDeviceiPhone4:
        case UIDeviceiPhone4S:
        case UIDeviceiPhone5:
        case UIDeviceiPhone5c:
        case UIDeviceiPhone5s:
        case UIDeviceiPhone6:
        case UIDeviceiPhone6s:
        case UIDeviceiPhone6Plus:
        case UIDeviceiPhone6sPlus:
        case UIDeviceiPhoneSimulator:
        case UIDeviceUnknowniPhone:
            return UIDeviceFamilyiPhone;
        case UIDeviceiPod1:
        case UIDeviceiPod2:
        case UIDeviceiPod3:
        case UIDeviceiPod4:
        case UIDeviceiPod5:
        case UIDeviceUnknowniPod:
            return UIDeviceFamilyiPod;
        case UIDeviceUnknown:
        default:
            return UIDeviceFamilyUnknown;
    }
}

- (BOOL)eckit_isIPadDeviceFamily
{
    return [self eckit_deviceFamily] == UIDeviceFamilyiPad;
}

- (BOOL)eckit_isIPhoneDeviceFamily
{
    return [self eckit_deviceFamily] == UIDeviceFamilyiPhone;
}

- (BOOL)eckit_isIPodDeviceFamily
{
    return [self eckit_deviceFamily] == UIDeviceFamilyiPod;
}

- (BOOL)eckit_isSimulatorDeviceFamily
{
    switch ([self eckit_platform]) {
        case UIDeviceiPadSimulator:
        case UIDeviceiPhoneSimulator:
            return YES;
        default:
            return NO;
    }
}

//------------------------------------------------------------------------------
#pragma mark -
#pragma mark Platform

- (UIDevicePlatform)eckit_platform
{
    static UIDevicePlatform p = UIDeviceUnknown;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        p = [self eckit_internalPlatform];
    });
    return p;
}

- (NSString *)eckit_platformString
{
    static NSString *platformString = @"";
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
#if !(TARGET_IPHONE_SIMULATOR)
        platformString = [self eckit_getSysInfoByName:"hw.machine"];
#else
        platformString = [[[NSProcessInfo processInfo] environment] objectForKey:@"SIMULATOR_MODEL_IDENTIFIER"] ?: @"";
#endif
    });
    return platformString;
}

- (NSString *)eckit_platformName
{
    switch ([self eckit_platform]) {
        case UIDeviceiPhoneSimulator:
            return @"iPhone Simulator";
        case UIDeviceiPhone1:
            return @"iPhone 1";
        case UIDeviceiPhone3G:
            return @"iPhone 3G";
        case UIDeviceiPhone3GS:
            return @"iPhone 3GS";
        case UIDeviceiPhone4:
            return @"iPhone 4";
        case UIDeviceiPhone4S:
            return @"iPhone 4S";
        case UIDeviceiPhone5:
            return @"iPhone 5";
        case UIDeviceiPhone5c:
            return @"iPhone 5c";
        case UIDeviceiPhone5s:
            return @"iPhone 5s";
        case UIDeviceiPhone6:
            return @"iPhone 6";
        case UIDeviceiPhone6s:
            return @"iPhone 6s";
        case UIDeviceiPhone6Plus:
            return @"iPhone 6 Plus";
        case UIDeviceiPhone6sPlus:
            return @"iPhone 6s Plus";
        case UIDeviceiPhoneSE:
            return @"iPhone SE";
        case UIDeviceUnknowniPhone:
            return @"Unknown iPhone";

        case UIDeviceiPod1:
            return @"iPod 1";
        case UIDeviceiPod2:
            return @"iPod 2";
        case UIDeviceiPod3:
            return @"iPod 3";
        case UIDeviceiPod4:
            return @"iPod 4";
        case UIDeviceiPod5:
            return @"iPod 5";
        case UIDeviceUnknowniPod:
            return @"Unknown iPod";

        case UIDeviceiPadSimulator:
            return @"iPad Simulator";
        case UIDeviceiPad1:
            return @"iPad 1";
        case UIDeviceiPad2:
            return @"iPad 2";
        case UIDeviceiPad3:
            return @"iPad 3";
        case UIDeviceiPad4G:
            return @"iPad 4G";
        case UIDeviceiPadAir:
            return @"iPad Air";
        case UIDeviceiPadAir2:
            return @"iPad Air 2";
        case UIDeviceiPadMini:
            return @"iPad Mini";
        case UIDeviceiPadMiniRetina:
            return @"iPad Mini Retina";
        case UIDeviceiPadMini3:
            return @"iPad Mini 3";
        case UIDeviceiPadMini4:
            return @"iPad Mini 4";
        case UIDeviceiPadMini5:
            return @"iPad Mini 5";
        case UIDeviceiPadPro12inch:
            return @"iPad Pro 12 inch";
        case UIDeviceiPadPro9inch:
            return @"iPad Pro 9 inch";
        case UIDeviceiPad5:
            return @"iPad 5";
        case UIDeviceiPadPro12inch2:
            return @"iPad Pro 12 inch 2";
        case UIDeviceiPadPro10inch:
            return @"iPad Pro 10.5 inch";
        case UIDeviceiPad6:
            return @"iPad 6";
        case UIDeviceiPadPro11inch:
            return @"iPad Pro 11 inch";
        case UIDeviceiPadPro12inch3:
            return @"iPad Pro 12 inch 3";
        case UIDeviceiPadAir3:
            return @"iPad Air 3";

        case UIDeviceUnknowniPad:
            return @"Unknown iPad";

        case UIDeviceUnknown:
        default:
            return @"Unknown iOS device";
    }
}

//------------------------------------------------------------------------------
#pragma mark -
#pragma mark Misc

- (BOOL)eckit_isIPad1
{
    static BOOL isIPad1;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        isIPad1 = [self eckit_platform] == UIDeviceiPad1;
    });

    return isIPad1;
}

//------------------------------------------------------------------------------
#pragma mark -
#pragma mark Private Helpers

/**
 * Find the platform string here: http://theiphonewiki.com/wiki/Models
 *
 * @return UIDevicePlatform the platform this device represents.
 */
- (UIDevicePlatform)eckit_internalPlatform
{
    NSString *platformString = [self eckit_platformString];

    // iPhone
    if ([platformString isEqualToString:@"iPhone1,1"]) {
        return UIDeviceiPhone1;
    }
    if ([platformString isEqualToString:@"iPhone1,2"]) {
        return UIDeviceiPhone3G;
    }
    if ([platformString hasPrefix:@"iPhone2,"]) {
        return UIDeviceiPhone3GS;
    }
    if ([platformString hasPrefix:@"iPhone3,"]) {
        return UIDeviceiPhone4;
    }
    if ([platformString hasPrefix:@"iPhone4,"]) {
        return UIDeviceiPhone4S;
    }
    if ([platformString hasPrefix:@"iPhone5,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        if (submodel <= 2) {
            return UIDeviceiPhone5;
        } else {
            return UIDeviceiPhone5c;
        }
    }
    if ([platformString hasPrefix:@"iPhone6,"]) {
        return UIDeviceiPhone5s;
    }
    if ([platformString hasPrefix:@"iPhone7,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        if (submodel <= 1) {
            return UIDeviceiPhone6Plus;
        } else {
            return UIDeviceiPhone6;
        }
    }
    if ([platformString hasPrefix:@"iPhone8,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        if (submodel <= 1) {
            return UIDeviceiPhone6s;
        } else if (submodel < 4) {
            return UIDeviceiPhone6sPlus;
        } else {
            return UIDeviceiPhoneSE;
        }
    }

    // iPod
    if ([platformString hasPrefix:@"iPod1,"]) {
        return UIDeviceiPod1;
    }
    if ([platformString isEqualToString:@"iPod2,2"]) {
        return UIDeviceiPod3;
    }
    if ([platformString hasPrefix:@"iPod2,"]) {
        return UIDeviceiPod2;
    }
    if ([platformString hasPrefix:@"iPod3,"]) {
        return UIDeviceiPod3;
    }
    if ([platformString hasPrefix:@"iPod4,"]) {
        return UIDeviceiPod4;
    }
    if ([platformString hasPrefix:@"iPod5,"]) {
        return UIDeviceiPod5;
    }

    // iPad
    if ([platformString hasPrefix:@"iPad1,"]) {
        return UIDeviceiPad1;
    }
    if ([platformString hasPrefix:@"iPad2,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        if (submodel <= 4) {
            return UIDeviceiPad2;
        } else {
            return UIDeviceiPadMini;
        }
    }
    if ([platformString hasPrefix:@"iPad3,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        if (submodel <= 3) {
            return UIDeviceiPad3;
        } else {
            return UIDeviceiPad4G;
        }
    }

    if ([platformString hasPrefix:@"iPad4,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        if (submodel < 4) {
            return UIDeviceiPadAir;
        } else if (submodel < 7) {
            return UIDeviceiPadMiniRetina;
        } else {
            return UIDeviceiPadMini3;
        }
    }

    if ([platformString hasPrefix:@"iPad5,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        if (submodel < 3) {
            return UIDeviceiPadMini4;
        } else {
            return UIDeviceiPadAir2;
        }
    }

    if ([platformString hasPrefix:@"iPad6,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        switch (submodel) {
            case 3:
            case 4:
                return UIDeviceiPadPro9inch;
            case 7:
            case 8:
                return UIDeviceiPadPro12inch;
            case 11:
            case 12:
                return UIDeviceiPad5;
            default:
                break;
        }
    }

    if ([platformString hasPrefix:@"iPad7,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        switch (submodel) {
            case 1:
            case 2:
                return UIDeviceiPadPro12inch2;
            case 3:
            case 4:
                return UIDeviceiPadPro10inch;
            case 5:
            case 6:
                return UIDeviceiPad6;
            default:
                break;
        }
    }

    if ([platformString hasPrefix:@"iPad8,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        switch (submodel) {
            case 1:
            case 2:
            case 3:
            case 4:
                return UIDeviceiPadPro11inch;
            case 5:
            case 6:
            case 7:
            case 8:
                return UIDeviceiPadPro12inch3;
            default:
                break;
        }
    }

    if ([platformString hasPrefix:@"iPad11,"]) {
        NSInteger submodel = [self eckit_getSubmodel:platformString];
        switch (submodel) {
            case 1:
            case 2:
                return UIDeviceiPadMini5;
            case 3:
            case 4:
                return UIDeviceiPadAir3;
            default:
                break;
        }
    }

    // Unknown device
    if ([platformString hasPrefix:@"iPhone"]) {
        return UIDeviceUnknowniPhone;
    }
    if ([platformString hasPrefix:@"iPod"]) {
        return UIDeviceUnknowniPod;
    }
    if ([platformString hasPrefix:@"iPad"]) {
        return UIDeviceUnknowniPad;
    }

    // Simulator
    if ([platformString hasSuffix:@"86"] || [platformString isEqual:@"x86_64"]) {
        BOOL smallerScreen = CGRectGetWidth([UIScreen mainScreen].bounds) < 768;
        return smallerScreen ? UIDeviceiPhoneSimulator : UIDeviceiPadSimulator;
    }

    return UIDeviceUnknown;
}

- (NSString *)eckit_getSysInfoByName:(char *)typeSpecifier
{
    size_t size;
    sysctlbyname(typeSpecifier, NULL, &size, NULL, 0);

    char *answer = malloc(size);
    sysctlbyname(typeSpecifier, answer, &size, NULL, 0);

    NSString *results = @(answer);

    free(answer);

    return results;
}

- (NSInteger)eckit_getSubmodel:(NSString *)platform
{
    NSInteger submodel = -1;

    NSArray *components = [platform componentsSeparatedByString:@","];
    if (components.count >= 2) {
        submodel = [[components objectAtIndex:1] integerValue];
    }
    return submodel;
}

@end


text:
var page = require('webpage').create(),
    system = require('system'),
    address, output, size;
page.settings.userAgent = 'HouseJs HTML Cacher/0.006';
address = system.args[1];
output = system.args[2];
page.viewportSize = { width: 1000, height: 1000 };
page.open(address, function (status) {
    if (status !== 'success') {
        console.log('error');
        console.log(address);
        console.log(status);
        phantom.exit();
    } else {
        window.setTimeout(function () {
            //page.render(output);
            //console.log('Page title: '+title);

            var checkIsLoading = function() {
                var isLoading = page.evaluate(function(){
                    if(window.$) {
                        return $('body.loading').length;
                    } else {
                        return 1;
                    }
                });
                return isLoading;
            }
            var tries = 0;
            var checkLoading = function() {
                if(tries > (4*120)) {
                    exportSrc();
                    return;
                }
                tries++;
                if(checkIsLoading()) {
                    window.setTimeout(function () {
                        checkLoading();
                    }, 250);
                } else {
                    window.setTimeout(function () {
                        exportSrc();
                    }, 1000);
                }
            }

            var exportSrc = function(){
                var title = page.evaluate(function () {
                    if($) {
                        $('script[data-requirecontext]').remove();
                        $('.post-viewer').siblings().remove();
                    }
                    return document.title;
                });
                var src = page.evaluate(function () {
                    var doctypeObj = document.doctype;
                    var docStr = '<!DOCTYPE '+doctypeObj.name+'>\n';
                    return docStr+document.documentElement.outerHTML;
                });
                console.log(src);
                phantom.exit(0);
            }

            checkLoading();
        }, 1000);
    }
});


text:
require 'test_helper'

class ActsAsHavingEffectiveDateTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, ActsAsHavingEffectiveDate
  end
end


text:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
	<head>
		<title th:remove="all">Template for HTML email (simple)</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	</head>
	<body>
		<p th:text="#{PasswordChangedNotice}">
			We wanted to let you know that your password was changed.
		</p>
		<a th:href="${loginLink}" th:text="${loginLink}">http://wallride.org/login</a>
	</body>
</html>


text:
require "tick_bond/version"

module TickBond
  require 'tick_bond/tick_bond'
end


text:
@interface addToDB : NSObject

+(void) AddDocuments:(NSMutableArray*) array;
+(void) AddBooths:(NSMutableArray*) array;
+(void) AddAttendees:(NSMutableArray*) array;
+(void) AddHelpCenter:(NSMutableArray*) array;
+(void) AddSessions:(NSMutableArray*) array;
+ (NSData *)decodeBase64WithString:(NSString*)strBase64;
@end


text:
@interface BLKControl() <NSCoding>

@property (nonatomic, strong) Class viewControllerClass;
@property (nonatomic, strong) NSMutableDictionary* controlProperties;

@end

@implementation BLKControl

+ (NSString*)propertyNameForSelector:(SEL)sel
{
    NSString* selStr = NSStringFromSelector(sel);

    if (!selStr || !selStr.length) {
        return nil;
    }

    NSString* propertyName = nil;
    if ([selStr hasPrefix:@"set"] && [selStr characterAtIndex:selStr.length-1] == ':') {
        // setter
        propertyName = [selStr substringWithRange:NSMakeRange(3, selStr.length-4)];
    } else {
        propertyName = selStr;
    }

    return propertyName;
}

- (CGRect)frame
{
    NSValue* value = [self.controlProperties valueForKey:@"frame"];
    return [value CGRectValue];
}

- (CGPoint)center
{
    NSValue* value = [self.controlProperties valueForKey:@"center"];
    return [value CGPointValue];
}

- (void)_setup
{
    self.controlProperties = [NSMutableDictionary new];
}

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

    return self;
}

- (id)initWithViewControllerClass:(Class)viewClass
{
    if ((self = [super init])) {
        [self _setup];
        self.viewControllerClass = viewClass;
    }

    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if ((self = [super init])) {
        NSString* className = [aDecoder decodeObjectForKey:@"viewControllerClassName"];
        if (className) {
            self.viewControllerClass = NSClassFromString(className);
        }
        self.controlProperties = [[aDecoder decodeObjectForKey:@"controlProperties"] mutableCopy];
        if (!self.controlProperties) {
            self.controlProperties = [NSMutableDictionary new];
        }
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    if (self.viewControllerClass) {
        [aCoder encodeObject:NSStringFromClass(self.viewControllerClass) forKey:@"viewControllerClassName"];
    }
    [aCoder encodeObject:self.controlProperties forKey:@"controlProperties"];
}

- (void)bindTo:(id)object properties:(NSArray*)properties
{
    for (NSString* property in properties) {
        [object addObserver:self forKeyPath:property options:NSKeyValueObservingOptionNew context:nil];
        id v = [object valueForKeyPath:property];
        if (v) {
            [self.controlProperties setValue:v forKey:property];
        }
    }
}

- (void)unbindProperties:(NSArray *)properties from:(id)object
{
    for (NSString* property in properties) {
        [object removeObserver:self forKeyPath:property];
    }
}

- (void)applyProperties:(NSArray*)properties to:(id)object
{
    [properties enumerateObjectsUsingBlock:^(NSString* key, NSUInteger idx, BOOL *stop) {
        @try {
            id v = [self.controlProperties valueForKey:key];
            if (v) {
                [object setValue:v forKeyPath:key];
            }
        }
        @catch (NSException *exception) {
            NSLog(@"Unable to set value '%@' to keyPath: '%@' on %@", object, key, self);
        }
    }];
}

#pragma mark - NSKeyValueObserving

- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
    NSNumber* kind = [change valueForKey:NSKeyValueChangeKindKey];
    if (kind.integerValue == NSKeyValueChangeSetting) {
        id v = [change valueForKey:NSKeyValueChangeNewKey];
        if (v) {
            [self.controlProperties setValue:v forKey:keyPath];
        }
    }
}

@end


text:
class CSDKScoreboard : public CClientScoreBoardDialog
{
private:
	DECLARE_CLASS_SIMPLE(CSDKScoreboard, CClientScoreBoardDialog);

public:
	CSDKScoreboard(IViewPort *pViewPort);
	~CSDKScoreboard();

protected:
	// scoreboard overrides
	virtual void InitScoreboardSections();
	virtual void UpdateTeamInfo();
	virtual void UpdatePlayerInfo();

	// vgui overrides for rounded corner background
	virtual void PaintBackground();
	virtual void PaintBorder();
	virtual void ApplySchemeSettings( vgui::IScheme *pScheme );

private:
	virtual void AddHeader(); // add the start header of the scoreboard
	virtual void AddSection(int teamType, int teamNumber); // add a new section header for a team

	int GetSectionFromTeamNumber( int teamNumber );

	// rounded corners
	Color					 m_bgColor;
	Color					 m_borderColor;
};

#endif // CSDK_SCOREBOARD_H


text:
package com.digiarea.closurefx.build.validation;

import com.digiarea.closurefx.build.console.ClosureStatus;

public class ClosureStatusFormatter extends BasicStatusFormatter {

	@Override
	public String format(IStatus status) {
		if (status instanceof ClosureStatus) {
			ClosureStatus closureStatus = (ClosureStatus) status;
			StringBuffer buffer = new StringBuffer(getLabel(status));
			if (closureStatus.getResource() != null) {
				buffer.append(closureStatus.getResource());
			}
			buffer.append(" line: " + closureStatus.getLine());
			buffer.append(" column: " + closureStatus.getColumn());
			if (status.getMessage() != null) {
				buffer.append("\n" + status.getMessage());
			}
			if (status.getExceptionMessage() != null) {
				buffer.append("\n" + status.getExceptionMessage());
			}
			return buffer.toString();
		} else {
			return super.format(status);
		}
	}

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bidr. Känn. Finl. Nat. Folk 37: 104 (1882)

#### Original name
Sarcodon scabrosus var. fennicus P. Karst., 1882

### Remarks
null


text:
var request = require('request');
var crawler = function () {
    request('http://localhost:3000/key?_=' + (+new Date), (err, res, body) => {
        request('http://localhost:3000/price?key='+body, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body) // Show the HTML for the Google homepage.
            }
        })
    });
}

setInterval(crawler, 1000);


text:
package javax.naming.ldap;

import java.io.Serializable;

/**
 * @author Warren Levy (warrenl@redhat.com)
 * @date June 1, 2001
 */

public interface Control extends Serializable
{
  boolean CRITICAL = true;
  boolean NONCRITICAL = false;

  String getID();
  boolean isCritical();
  byte[] getEncodedValue();
}


text:
module RImgur
  class Client
    def initialize(options, path)
      @client_id = options[:client_id]
      @album_id = options[:album_id]
      @path = path
    end

    def download_album
      url_array.each do |url|
        filename = /(\w+).(jpg|jpeg|png|apng|gif)/.match(url)[0]

        @path.each do |path|
          File.write("#{path}/#{filename}", open(url).read, {mode: "wb"})
        end
      end
    end

    private

    def imgur_data
      headers = { "Authorization" => "Client-ID #{@client_id}"}
      path    = "/3/album/#{@album_id}.json"
      uri     = URI.parse("https://api.imgur.com"+path)
      request = Net::HTTP::Get.new(path, headers)

      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true
      response = http.request(request)
      response.body
    end

    def album_json
      JSON.parse(imgur_data)
    end

    def images
      album_json["data"]["images"]
    end

    def url_array
      [].tap do |array|
        images.each do |image|
          array << image["link"]
        end
      end
    end

  end
end


text:
#ifndef WebSocketChannelClient_h
#define WebSocketChannelClient_h

#if ENABLE(WEB_SOCKETS)

#include <wtf/Forward.h>
#include <wtf/PassOwnPtr.h>
#include <wtf/Vector.h>

namespace WebCore {

    class WebSocketChannelClient {
    public:
        virtual ~WebSocketChannelClient() { }
        virtual void didConnect() { }
        virtual void didReceiveMessage(const String&) { }
        virtual void didReceiveBinaryData(PassOwnPtr<Vector<char>>) { }
        virtual void didReceiveMessageError() { }
        virtual void didUpdateBufferedAmount(unsigned long /* bufferedAmount */) { }
        virtual void didStartClosingHandshake() { }
        enum ClosingHandshakeCompletionStatus {
            ClosingHandshakeIncomplete,
            ClosingHandshakeComplete
        };
        virtual void didClose(unsigned long /* unhandledBufferedAmount */, ClosingHandshakeCompletionStatus, unsigned short /* code */, const String& /* reason */) { }

    protected:
        WebSocketChannelClient() { }
    };

} // namespace WebCore

#endif // ENABLE(WEB_SOCKETS)

#endif // WebSocketChannelClient_h