text:
package com.funnic.mvc.core.impl.view;

import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;

import java.net.URL;

/**
 * @author Per
 */
public interface ViewRepository {
	/**
	 * Resolve the supplied path and return a URL for it
	 *
	 * @param path The path to the view
	 * @return URL if found; null otherwise
	 */
	URL getView(String path);

	/**
	 * Retrieve the associated bundle for this repository
	 *
	 * @return
	 */
	Bundle getBundle();

	/**
	 *
	 * @return
	 */
	ServiceReference getServiceReference();
}


text:
layout: post
title: Mechanical Engineering students' capstone project cited in Wired.com article
categories:
- Scholarly Communications
tags:
- IRis
- open access
- research
- scholarly communication
status: publish
type: post
published: true
meta:
  _edit_last: '50'
---
On March 9, 2010, the popular website Wired.com published an article titled "Mile-High Mega Kites Could Pull Giant, Floating Power Plants," by author Alexis Madrigal.  Madrigal cited the work of six NU students, and included a link to their capstone project, which had been published in IRis, Northeastern's digital archive of scholarship.

In the past 2 months, their capstone project, "Hydroelectric Power Generator: Technical Design Report," which the students created in the course MIME1501 in May 2002, has been viewed 350 times by readers of the Wired article.  Congratulations to student authors Anthony Chesna, Tony DiBella, Tim Hutchins, Saralyn Kropf, Jeff Lesica, and Jim Mahoney!

Want to increase your citation rate? Submit your work to IRis!

redpajama_set_name: RedPajamaGithub


text:
package nl.esciencecenter.e3dchem.sstea;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class ScorerTest {
    private Scorer scorer;
    private HashMap<String, String> sequences;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Before
    public void setUp() {
        scorer = new Scorer();
        sequences = new HashMap<String, String>();
        sequences.put("seq1", "A");
        sequences.put("seq2", "A");
        sequences.put("seq3", "G");
        sequences.put("seq4", "A");
        sequences.put("seq5", "V");
        sequences.put("seq6", "L");
        sequences.put("seq7", "C");
        sequences.put("seq8", "I");
        sequences.put("seq9", "I");
    }

    @Test
    public void testDistinctAA_default() {
        assertEquals(21, scorer.getDistinctAA());
    }

    @Test
    public void tofew_sequences() {
        Map<String, String> sequences = new HashMap<String, String>();
        sequences.put("seq1", "A");
        Set<String> subfamily_members = new HashSet<String>();

        thrown.expect(IllegalArgumentException.class);

        scorer.scoreit(sequences, subfamily_members);
    }

    @Test
    public void tofew_subfamily_members() {
        Set<String> subfamily_members = new HashSet<String>();

        thrown.expect(IllegalArgumentException.class);

        scorer.scoreit(sequences, subfamily_members);
    }

    @Test
    public void subfamily_members_notin_sequences() {
        Set<String> subfamily_members = new HashSet<String>();
        subfamily_members.add("seq99");

        thrown.expect(IllegalArgumentException.class);

        scorer.scoreit(sequences, subfamily_members);
    }

    @Test
    public void conserved_subfamily() {
        Set<String> subfamily_members = new HashSet<String>();
        subfamily_members.add("seq1");
        subfamily_members.add("seq2");
        subfamily_members.add("seq3");
        subfamily_members.add("seq4");

        List<Score> scores = scorer.scoreit(sequences, subfamily_members);

        ArrayList<Score> expected = new ArrayList<Score>();
        expected.add(new Score(1, 1.80231537913897, 0.5623351446188083, 1.3321790402101223, 2, 4));
        assertEquals(expected, scores);
    }

    @Test
    public void conserved_outsidesubfamily() {
        Set<String> subfamily_members = new HashSet<String>();
        subfamily_members.add("seq5");
        subfamily_members.add("seq6");
        subfamily_members.add("seq7");
        subfamily_members.add("seq8");

        List<Score> scores = scorer.scoreit(sequences, subfamily_members);

        ArrayList<Score> expected = new ArrayList<Score>();
        expected.add(new Score(1, 2.511514099104873, 1.3862943611198906, 0.9502705392332347, 4, 3));
        assertEquals(expected, scores);
    }

    @Test
    public void halfconserved_subfamily() {
        Set<String> subfamily_members = new HashSet<String>();
        subfamily_members.add("seq1");
        subfamily_members.add("seq2");

        List<Score> scores = scorer.scoreit(sequences, subfamily_members);

        ArrayList<Score> expected = new ArrayList<Score>();
        expected.add(new Score(1, 1.2966543402566657, 0.0, 1.7478680974667573, 1, 6));
        assertEquals(expected, scores);
    }

    @Test
    public void halfconserved_outsidesubfamily() {
        Set<String> subfamily_members = new HashSet<String>();
        subfamily_members.add("seq3");
        subfamily_members.add("seq4");
        subfamily_members.add("seq5");
        subfamily_members.add("seq6");

        List<Score> scores = scorer.scoreit(sequences, subfamily_members);

        ArrayList<Score> expected = new ArrayList<Score>();
        expected.add(new Score(1, 2.424939019319153, 1.3862943611198906, 1.0549201679861442, 4, 3));
        assertEquals(expected, scores);
    }

    @Test
    public void conserved75_subfamily() {
        Set<String> subfamily_members = new HashSet<String>();
        subfamily_members.add("seq1");
        subfamily_members.add("seq2");
        subfamily_members.add("seq3");
        subfamily_members.add("seq5");

        List<Score> scores = scorer.scoreit(sequences, subfamily_members);

        ArrayList<Score> expected = new ArrayList<Score>();
        expected.add(new Score(1, 2.0032821050274836, 1.0397207708399179, 1.3321790402101223, 3, 4));
        assertEquals(expected, scores);
    }

    @Test
    public void jaggedSequence() {
        sequences.put("seq10", "ICK");
        Set<String> subfamily_members = new HashSet<String>();
        subfamily_members.add("seq1");
        List<Score> scores = scorer.scoreit(sequences, subfamily_members);
        assertEquals(scores.size(), 1);
    }

    @Test
    public void emptySequence() {
        sequences.put("seq10", "");
        Set<String> subfamily_members = new HashSet<String>();
        subfamily_members.add("seq1");

        thrown.expect(IllegalArgumentException.class);

        scorer.scoreit(sequences, subfamily_members);
    }

}


text:
<?php

namespace Phlexible\Bundle\TreeBundle\Model;

/**
 * Tree node interface
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
interface TreeNodeInterface
{
    /**
     * @return TreeInterface
     */
    public function getTree();

    /**
     * @param TreeInterface $tree
     *
     * @return $this
     */
    public function setTree(TreeInterface $tree);

    /**
     * @return int
     */
    public function getId();

    /**
     * @param int $id
     *
     * @return $this
     */
    public function setId($id);

    /**
     * @return TreeNodeInterface
     */
    public function getParentNode();

    /**
     * @param TreeNodeInterface $parentNode
     *
     * @return $this
     */
    public function setParentNode($parentNode);

    /**
     * @return bool
     */
    public function isRoot();

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

    /**
     * @param string $type
     *
     * @return $this
     */
    public function setType($type);

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

    /**
     * @param string $typeId
     *
     * @return $this
     */
    public function setTypeId($typeId);

    /**
     * @return array
     */
    public function getAttributes();

    /**
     * @param array $attributes
     *
     * @return $this
     */
    public function setAttributes(array $attributes);

    /**
     * @param string $key
     * @param mixed  $default
     *
     * @return array
     */
    public function getAttribute($key, $default = null);

    /**
     * @param string $key
     * @param string $value
     *
     * @return $this
     */
    public function setAttribute($key, $value);

    /**
     * @param string $key
     *
     * @return $this
     */
    public function removeAttribute($key);

    /**
     * @return int
     */
    public function getSort();

    /**
     * @param int $sort
     *
     * @return $this
     */
    public function setSort($sort);

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

    /**
     * @param string $sortMode
     *
     * @return $this
     */
    public function setSortMode($sortMode);

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

    /**
     * @param string $sortDir
     *
     * @return $this
     */
    public function setSortDir($sortDir);

    /**
     * @return \DateTime
     */
    public function getCreatedAt();

    /**
     * @param \DateTime $createdAt
     *
     * @return $this
     */
    public function setCreatedAt(\DateTime $createdAt);

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

    /**
     * @param string $createUid
     *
     * @return $this
     */
    public function setCreateUserId($createUid);

    /**
     * @return boolean
     */
    public function getInNavigation();

    /**
     * @param boolean $inNavigation
     *
     * @return $this
     */
    public function setInNavigation($inNavigation);

    /**
     * @return array
     */
    public function getCache();

    /**
     * @param array $cache
     *
     * @return $this
     */
    public function setCache($cache);

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

    /**
     * @param string $controller
     *
     * @return $this
     */
    public function setController($controller);

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

    /**
     * @param string $template
     *
     * @return $this
     */
    public function setTemplate($template);

    /**
     * @return array
     */
    public function getRoutes();

    /**
     * @param array $routes
     *
     * @return $this
     */
    public function setRoutes(array $routes);

    /**
     * @return boolean
     */
    public function getNeedAuthentication();

    /**
     * @param boolean $needsAuthentication
     *
     * @return $this
     */
    public function setNeedAuthentication($needsAuthentication);

    /**
     * @return string
     */
    public function getSecurityExpression();
}


text:
currently-color-changer
=======================

This is a script that adds a really neat color changing effect to the Currently Chrome Extension

Copy and paste this code into the developer console when you are on the Currently page.

```javascript
(function () {
    'use strict';
    var h = Math.floor(Math.random() * 361);
    var s = 50;
    var l = 80;
    var delay = 100;
    function loopBackground() {
    	//background and content are opposite on the color wheel always
    	//Comment out either to turn off color changing on any one of them
        jQuery('#main')[0].style.backgroundColor = "hsl(" + h + "," + s + "%," + l + "%)";
        jQuery('#main-content')[0].style.color = "hsl(" + ((h+180) % 360) + "," + s + "%," + (l/2) + "%)"
        h = (h - 1 + 360) % 360;
    }
    var id = setInterval(loopBackground, delay);
})();

```

How to make this change permanent
=================================
First, locate where the Chrome extensions are located on you computer
* Mac (confirmed): ```~/Library/Application\ Support/Google/Chrome/Default/Extensions/```
* Windows (confirmed): ```%USERPROFILE%\AppData\Local\Google\Chrome\User Data\Default\Extensions\```
* Linux (*unconfirmed*): ```~/.config/google-chrome/Default/Extensions/```
* Linux Chromium (*unconfirmed*): ```~/.config/chromium/Default/Extensions/```

Next, look for the folder named ```ojhmphdkpgbibohbnpbfiefkgieacjmh```
#####If you do not see this folder:
* Open the Currently tab
* Open the dev console (Mac: cmd+alt+i Windows/Linux: F12)
* Hit esc or click on the console tab
* Type ```document.URL```
* The long string of characters between "chrome-extension://" and "/index.html" is the name of the folder that Currently is located in

Finally,
* Navigate into that folder and locate ```index.html```.
* Edit this file and paste ```<script type="text/javascript" src="js/custom.js"></script>``` above the ```</html>``` tag at the bottom.
* Create a file named ```custom.js``` inside of the js folder.
* Copy and paste the contents of ```currently-color-changer.js``` into custom.js, save, and you're done!
  * Alternatively, you can add the code inside of index.html like so, ```<script> insert code here </script>```

**Note:** If currently is updated you may have to repeat this process.


text:
.inorifeedback	{background-image: url(inori-background-3s.jpg);
			background-repeat: no-repeat;
			background-position: 50% 0;
			background-color:  #F0B6F0;
			text-align: center;
			padding-top: 420px;
			padding-bottom: 80px}

.type3		{color: #ffffff;
			font-size: 60px;
			font-family: "Cutive Mono",monospace;
			text-shadow:  0 5px 5px #000000}


text:
PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin

# This is useful to configure EC2 instances to allow SSHD to authenticate users
# via password.  It changes the SSH daemon config to allow password-based
# authentication and specifically denies root login.

echo "********************************************************************************"
echo "*** $(basename "$0")"
echo "********************************************************************************"
echo "Configuring PasswordAuthentication SSH access..."
DATE=$(date '+%Y%m%d%H%M%S')
cp -p /etc/ssh/sshd_config /etc/ssh/sshd_config."${DATE}"
sed -e '/^PasswordAuthentication/d' \
    -e '/^#PasswordAuthentication/a\PasswordAuthentication yes' \
    -e '/^PermitRootLogin/d' \
    -e '/^#PermitRootLogin/a\PermitRootLogin no' \
    -i /etc/ssh/sshd_config
service sshd restart


text:
/// <referecne path="../references.ts" />
/// <reference path="../interfaces.ts" />
/// <reference path="../compiler/Compiler.ts" />
/// <reference path="../modules/IModule.ts" />
/// <reference path="../modules/Module.ts" />
/// <reference path="../schema/JsonSchema.ts" />
/// <reference path="../templates/Engine.ts" />
/// <reference path="routing/IRouter.ts" />
/// <reference path="routing/ModuleRouter.ts" />
/// <reference path="sitemap/Sitemap.ts" />
/// <reference path="media/Mime.ts" />
/// <reference path="IContext.ts" />
/// <reference path="Context.ts" />
/// <reference path="IServer.ts" />
/// <reference path="ServerOptions.ts" />
/// <reference path="Waiter.ts" />

module appex.web {

    /** a appex server. JIT once and watch it fly. */
    export class Server implements appex.web.IServer {

        private server    : http.Server;

        private compiler  : appex.compiler.Compiler;

        private module    : appex.modules.IModule;

        private schema    : appex.schema.JsonSchema;

        private router    : appex.web.routing.IRouter;

        private sitemap   : appex.web.sitemap.Sitemap;

        private template  : appex.templates.Engine;

        private mime      : appex.web.media.Mime;

        private waiters   : appex.web.Waiter[];

        private compiled  : boolean;

        private compiling : boolean;

        /** arguments:
        *    options - server start options.
        */
        constructor(public options: appex.web.IServerOptions) {

            this.compiler  = new appex.compiler.Compiler();

            this.mime      = new appex.web.media.Mime();

            this.module    = null;

            this.schema    = null;

            this.router    = null;

            this.sitemap   = null;

            this.template  = new appex.templates.Engine({ devmode: false });

            this.waiters   = [];

            this.compiling = false;

            this.compiled  = false;

            this.options.stdout.write('appex \033[32m- server\033[0m\n');
        }

        /** creates a nodejs http server based on the server options protocol.
         *
         *  arguments:
         *      port - the port to listen on.
         */
        public listen(port: number): void {

            var protocol: any = this.options.protocol=="http" ? node.http:node.https;

            var that = this;

            this.server = protocol.createServer(function(request: http.ServerRequest,response: http.ServerResponse,next: Function): void {

                that.handler(request, response, null);
            });

            this.server.listen(port);
        }

        /** the http request handler.
        *
        *   arguments:
        *       request  - the nodejs http request.
        *       response - the nodejs http response.
        *       next     - (optional) the next callback used for express / connect middleware.
        */
        public handler(request: http.ServerRequest,response: http.ServerResponse,next?: Function): void {

            this.waiters.push(new appex.web.Waiter(request, response, next));

            var that=this;

            this.compile(function(diagnostics) {

                if(diagnostics) {

                    that.errors(diagnostics);

                    return;
                }

                while(that.waiters.length>0) {

                    var waiter  = that.waiters.pop();

                    var context = that.load_context(waiter.request,waiter.response,waiter.next);

                    var handled = that.router.handler(context);

                    if(handled) {

                        if(that.options.logging) {

                            var message=[];

                            message.push('\033[32m[', waiter.stopwatch.elapsed(), 'ms]\033[0m ')

                            message.push(context.request.method, ' ');

                            message.push(context.request.url, '\n');

                            that.options.stdout.write(message.join(''));
                        }
                    }
                    else {

                        if(context.next) {

                            context.next();
                        }
                    }
                }
            });
        }

        /** loads the context.
        *
        *   arguments:
        *       request  - the nodejs http request
        *       response - the nodejs http response
        *       next     - the next function
        *       returns  - the context
        */
        private load_context(request: http.ServerRequest,response: http.ServerResponse,next?: Function): appex.web.IContext {

            var context = new appex.web.Context();

            // bind in user objects.
            if(this.options.context) {

                for(var n in this.options.context) {

                    context[n]=this.options.context[n];
                }
            }

            // bind in context objects.
            context.request  = appex.web.BindRequest(request);

            context.response = appex.web.BindResponse(response, context.request.cookies);

            context.next     = function() { };

            context.module   = this.module;

            context.schema   = this.schema;

            context.router   = this.router;

            context.sitemap  = this.sitemap;

            context.template = this.template;

            context.mime     = this.mime;

            if(next) {

                context.next = next;
            }

            // initialize the attribute.
            context.attribute = {};

            return context;
        }

        /** compiles options.program once and loads the module and router.
        *
        *   arguments:
        *       callback - a callback containing any diagnostics.
        */
        private compile(callback: (diagnostics: typescript.api.Diagnostic[]) => void): void {

            if(!this.compiled) {

                if(!this.compiling) {

                    this.compiling = true;

                    var that = this;

                    this.compiler.compile(this.options.program,function(result) {

                        that.compiling=false;

                        if(result.diagnostics.length>0) {

                            callback(result.diagnostics);

                            return;
                        }

                        that.module   = new appex.modules.Module(result);

                        that.router   = new appex.web.routing.ModuleRouter(that.module);

                        that.schema   = new appex.schema.JsonSchema(that.module);

                        that.sitemap  = new appex.web.sitemap.Sitemap(that.router);

                        that.compiled = true;

                        that.compiler.dispose();

                        callback(null);
                    });
                }
            }
            else {

                callback(null);
            }
        }
        /** emits compilation errors to options.stdout and a 500 'internal server error' message to http buffer.
        *
        *   arguments:
        *       diagnostics - the diagnostics to emit.
        */
        private errors(diagnostics: typescript.api.Diagnostic[]): void {

            while(this.waiters.length > 0) {

                var request = this.waiters.pop();

                request.response.writeHead(500, { 'content-type': 'text/plain' });

                request.response.write('internal server error.');

                request.response.end();

                for(var n in diagnostics) {

                    var diagnostic = diagnostics[n];

                    var message    = [];

                    message.push(diagnostic.path)

                    message.push(" [", (diagnostic.line_index+1).toString(), ":", (diagnostic.char_index+1).toString(),"] ");

                    message.push(diagnostic.message,'\n');

                    if(this.options.logging) {

                        this.options.stderr.write(message.join(''));
                    }
                }
            }
        }

        /** disposes of this server */
        public dispose(): void {

            this.compiler.dispose();

            if(this.module) {

                this.module.dispose();
            }
        }
    }
}


text:
/*    ____  U _____ u __  __    _____      _
 *   |  _"\ \| ___"|/ \ \/"/   |_ " _| U  /"\  u
 *   | | | | |  _|"   /\  /\     | |    \/ _ \/
 *  U| |_| |\| |___  U /  \ u   /| |\   / ___ \
 *   |____/ u|_____|  /_/\_\   u |_|U  /_/   \_\
 *    |||_   <<   >>,-,>> \\_  _// \\_  \\    >>
 *   (__)_) (__) (__)\_)  (__)(__) (__)(__)  (__)
 *     ____    U  ___ u   ____     U  ___ u _____                ____  ____
 *  U |  _"\ u  \/"_ \/U | __")u    \/"_ \/|_ " _|     ___    U /"___|/ __"| u
 *   \| |_) |/  | | | | \|  _ \/    | | | |  | |      |_"_|   \| | u <\___ \/
 *    |  _ <.-,_| |_| |  | |_) |.-,_| |_| | /| |\      | |     | |/__ u___) |
 *    |_| \_\\_)-\___/   |____/  \_)-\___/ u |_|U    U/| |\u    \____||____/>>
 *    //   \\_    \\    _|| \\_       \\   _// \\_.-,_|___|_,-._// \\  )(  (__)
 *   (__)  (__)  (__)  (__) (__)     (__) (__) (__)\_)-' '-(_/(__)(__)(__)
 *
 *   This file contains functions for serial port protocol communication.
 *
 *   Created: Dec. 1, 2015    zhoudada
 *
 */

#include "ProtocolMacros.h"
#include "Protocol.h"
#include "usart_simplified.h"

static void     init(Protocol *protocol);
static void     initPacket(Protocol *protocol, Packet * packet);
static void     writePacket(Packet * packet);
static uint8_t 	verifyIndex(Protocol *protocol, uint8_t	index);
static uint8_t 	verifyChecksum(Protocol *protocol,
                               uint8_t checksum, uint16_t length);
static void     readPacket(Protocol *protocol, Packet * packet);

ProtocolStruct PROTOCOL = {
    init,
    initPacket,
    writePacket,
    readPacket,
#if USE_INDEX
    verifyIndex,
#endif
    verifyChecksum
};

static void init(Protocol *protocol){
#if USE_INDEX
    protocol->_rxIndex = 0;
    protocol->_txIndex = 0;
#endif

    protocol->_bufferPos = 0;

    protocol->_specsFound = 0;
    protocol->_headerFound = 0;
}

static void initPacket(Protocol *protocol, Packet * packet){
#if USE_INDEX
    PACKET.init(packet, protocol->_txIndex ++);
#else
    PACKET.init(packet);
#endif
}

static void writePacket(Packet * packet){
    PACKET.writeNonBlocking(packet);
}

#if USE_INDEX
static uint8_t verifyIndex(Protocol *protocol, uint8_t index){
    if (index == protocol->_rxIndex++){
        return 1;
    }
    // otherwise update index
    protocol->_rxIndex = index + 1;
    return 0;
}
#endif

static uint8_t verifyChecksum(Protocol *protocol,
                                uint8_t checksum,uint16_t length){
    uint8_t c = 0;
    uint16_t i;
    for (i = PAYLOAD_OFFSET; i < PAYLOAD_OFFSET + length; i++){
        c += protocol->_buffer[i];
    }
    if (c == checksum){
        return 1;
    }
    return 0;
}

static void readPacket(Protocol *protocol, Packet * packet){
    if ((!protocol->_headerFound) &&
            (QUEUE.dataAvailable(USARTBuf.Rxq) >=
            (PACKET_HEADER_LENGTH - protocol->_bufferPos))) {
        // header not found & we have enough bytes for a header
        uint8_t remaining = PACKET_HEADER_LENGTH - protocol->_bufferPos;
        uint8_t i;
        for (i = 0; i < remaining; i++) {
            // read byte by byte
            uint8_t incoming;
            if (USART.readByte(&incoming)) {
                if (incoming == PACKET_HEADER[protocol->_bufferPos]){
                    // valid for a header
                    protocol->_buffer[protocol->_bufferPos] = incoming;
                    protocol->_bufferPos ++;
                    protocol->_headerFound = 1;
                } else {
                    // incorrect, reset protocol->_bufferPos back to front;
                    protocol->_bufferPos = 0;
                    protocol->_headerFound = 0;
                    break;
                }
            }
            else {
                // There is no data in USART Rx buffer, which should not
                // happen here.
            }
        }
    }

    if (protocol->_headerFound && (!protocol->_specsFound) &&
            (QUEUE.dataAvailable(USARTBuf.Rxq) >=
            (MIN_PACKET_LENGTH - protocol->_bufferPos))){
        // header found & saved, packet specs not found, enough for specs
        uint8_t remaining = MIN_PACKET_LENGTH - protocol->_bufferPos;
        uint8_t i;
        for (i = 0; i < remaining; i++){
            // read byte by byte
            uint8_t incoming;
            if (USART.readByte(&incoming)) {
                protocol->_buffer[protocol->_bufferPos ++] = incoming;
            }
            else {
                // There is no data in USART Rx buffer, which should not
                // happen here.
            }
        }
        protocol->_specsFound = 1;
    }

    if (protocol->_headerFound && protocol->_specsFound){
        if (QUEUE.dataAvailable(USARTBuf.Rxq) >=
                protocol->_buffer[LENGTH_OFFSET]){
            // read!
            uint8_t remaining =
                MIN_PACKET_LENGTH + protocol->_buffer[LENGTH_OFFSET] -
                protocol->_bufferPos;
            uint8_t i;
            for (i = 0; i < remaining; i++){
                uint8_t incoming;
                if (USART.readByte(&incoming)) {
                    protocol->_buffer[protocol->_bufferPos ++] = incoming;
                }
                else {
                    // There is no data in USART Rx buffer, which should not
                    // happen here.
                }
            }
            // do checking & save the packet
            if (PROTOCOL.verifyChecksum(protocol,
                    protocol->_buffer[CHECKSUM_OFFSET],
                    protocol->_buffer[LENGTH_OFFSET])){
            // correct checksum
#if USE_INDEX
                if (PROTOCOL.verifyIndex(protocol,
                            protocol->_buffer[INDEX_OFFSET])){
                    // correct index
                    // all cleared, we got a valid packet

                    // successfully copied
                    PACKET.init(packet, protocol->_buffer[INDEX_OFFSET]);
#else
                    PACKET.init(packet);
#endif
                    uint8_t rtnval =
                        PAYLOAD.copyFrom(&packet->payload,
                                protocol->_buffer + PAYLOAD_OFFSET,
                                protocol->_buffer[LENGTH_OFFSET]);
                    if (rtnval != 0){
                        PACKET.clear(packet);
                    }
#if USE_INDEX
                }
#endif
            }
            // RESET EVERYTHING HERE
            protocol->_bufferPos = 0;
            protocol->_headerFound = 0;
            protocol->_specsFound = 0;
        }
        // wait until next round
    }
}


text:
module Nanoc3

  # The current nanoc version.
  VERSION = '3.2.0a3'

end

# Load requirements
require 'yaml'
require 'fileutils'

# Load nanoc
require 'nanoc3/base'
require 'nanoc3/extra'
require 'nanoc3/data_sources'
require 'nanoc3/filters'
require 'nanoc3/helpers'


text:
package com.schappet.inv.controller;

import com.schappet.inv.domain.*;
import com.schappet.inv.dao.*;

import edu.uiowa.icts.spring.*;
import edu.uiowa.icts.util.PasswordTools;
import edu.uiowa.icts.util.SortColumn;
import edu.uiowa.icts.spring.GenericDaoListOptions;

import java.io.IOException;
import java.io.StringReader;

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

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * Generated by Protogen
 * @date 07/03/2014 12:45:24 CDT
 */
@Controller
@RequestMapping( "/inv/person/*" )
public class PersonController extends AbstractInvController {

    private static final Log log = LogFactory.getLog( PersonController.class );

    @RequestMapping(value = "list_alt.html", method = RequestMethod.GET)
    public ModelAndView listNoScript() {
        ModelMap model = new ModelMap();
        model.addAttribute("personList",invDaoService.getPersonService().list());
        return new ModelAndView("inv/person/list_alt", model);
    }

    @RequestMapping(value = "list.html", method = RequestMethod.GET)
    public ModelAndView list() {
        return new ModelAndView("inv/person/list");
    }

    @RequestMapping(value = "datatable.html", method = RequestMethod.GET)
    public void datatable( HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value="iDisplayLength") Integer limit,
        @RequestParam(value="iDisplayStart") Integer start,
        @RequestParam(value="iColumns") Integer numberColumns,
        @RequestParam(value="iColumns") Integer columnCount,
        @RequestParam(value="sColumns") String columns,
        @RequestParam(value="sEcho") String echo,
        @RequestParam(value="bFilter") String bFilter,
        @RequestParam(value="iSortingCols", required=false) Integer sortingColsCount,
        @RequestParam(value="sSearch", required=false) String search,
        @RequestParam(value="display", required=false, defaultValue="list") String display ) {

        ArrayList<SortColumn> sorts = new ArrayList<SortColumn>();
        try {

            response.setContentType( "application/json" );

            String[] colArr = columns.split(",");

            if( sortingColsCount != null ){
                for( int i = 0; i < sortingColsCount; i++){
                    if( i < colArr.length ){
                        Integer colnum = null;
                        String col = request.getParameter( "iSortCol_" + i );
                        if ( col != null ) {
                            try {
                                colnum = Integer.parseInt( col );
                            } catch ( NumberFormatException e ) {
                                continue;
                            }
                            if( colnum != null ){
                                sorts.add( new SortColumn( colArr[ colnum ], request.getParameter( "sSortDir_" + i ) ) );
                            }
                        }
                    }
                }
            }

            GenericDaoListOptions options = new GenericDaoListOptions();

            if( Boolean.valueOf( bFilter ) ){
                ArrayList<String> searchColumns = new ArrayList<String>();
                for( int i = 0; i < numberColumns; i++ ){
                    if( Boolean.valueOf( request.getParameter( "bSearchable_"+i ) ) ){
                        searchColumns.add( colArr[i] );
                    }
                }
                options.setSearch( search );
                options.setSearchColumns( searchColumns );
            } else {
                HashMap<String,Object> likes = new HashMap<String, Object>();
                for( String column : colArr ){
                    String columnValue = request.getParameter( column );
                    if( columnValue != null ){
                        for ( String splitColumnValue : StringUtils.split( columnValue, ' ' ) ) {
                            likes.put( column, splitColumnValue );
                        }
                    }
                }
                options.setIndividualLikes(likes);
            }

            Integer count = invDaoService.getPersonService().count( options );

            options.setLimit(limit);
            options.setStart(start);
            options.setSorts(sorts);

            List<Person> personList = invDaoService.getPersonService().list( options );

            JSONObject ob = new JSONObject();
            ob.put( "sEcho", echo );
            ob.put( "iTotalDisplayRecords", count );
            ob.put( "iTotalRecords", count );
            JSONArray jsonArray = new JSONArray();
            for( Person person : personList ){
                JSONArray tmp = new JSONArray();
                for( String column : colArr ){
                    if( "personId".equals(column) ){
                        tmp.put(person.getPersonId());
                    } else if( "firstName".equals(column) ){
                        tmp.put(person.getFirstName());
                    } else if( "lastName".equals(column) ){
                        tmp.put(person.getLastName());
                    } else if( "username".equals(column) ){
                        tmp.put(person.getUsername());
                    } else if( "consent".equals(column) ){
                        tmp.put(person.getConsent());
                    } else if( "deleted".equals(column) ){
                        tmp.put(person.getDeleted());
                    } else if( "languageId".equals(column) ){
                        tmp.put(person.getLanguageId());
                    } else if( "urls".equals(column)) {
                        String urls = "";
                        if( "list".equals( display ) ){
                            urls += "[view]";
                            urls += "[edit]";
                            urls += "[delete]";
                        } else {

                        }
                        tmp.put( urls );
                    } else {
                        tmp.put( "[error column "+column+" not supported]" );
                    }
                }
                jsonArray.put( tmp );
            }
            ob.put( "aaData", jsonArray );

            StringReader reader = new StringReader( ob.toString() );
            try {
                IOUtils.copy( reader, response.getWriter() );
            } finally {
                reader.close();
            }
        } catch ( Exception e ) {
            try {
                log.error( "error builing datatable json object", e );
                String stackTrace = e.getMessage() + "
";
                for( StackTraceElement ste : e.getStackTrace() ){
                    stackTrace += ste.toString()+"
";
                }
                JSONObject ob = new JSONObject();
                ob.put("sEcho", echo);
                ob.put("iTotalDisplayRecords", 0);
                ob.put("iTotalRecords", 0);
                ob.put("error", e.getMessage());
                ob.put("stackTrace", stackTrace);
                StringReader reader = new StringReader(ob.toString());
                try {
                    IOUtils.copy( reader, response.getWriter() );
                } finally {
                    reader.close();
                }
            } catch ( JSONException je ) {
                log.error( "error writing json error to page", je );
            } catch (IOException ioe) {
                log.error("error writing json error to page", ioe);
            }
        }
    }

    @RequestMapping(value = "add.html", method = RequestMethod.GET)
    public ModelAndView add() {
        ModelMap model = new ModelMap();
        Person person = new Person();
        model.addAttribute("person",person);
        return new ModelAndView("inv/person/edit",model);
    }

    @RequestMapping(value = "edit.html", method = RequestMethod.GET)
    public ModelAndView edit(@RequestParam("personId") Integer personId) {
        ModelMap model = new ModelMap();
        Person person = invDaoService.getPersonService().findById(personId);
        model.addAttribute("person",person);
        return new ModelAndView("inv/person/edit",model);
    }

    @RequestMapping(value = "show.html", method = RequestMethod.GET)
    public ModelAndView show(@RequestParam("personId") Integer personId) {
        ModelMap model = new ModelMap();
        Person person = invDaoService.getPersonService().findById(personId);
        model.addAttribute("person",person);
        return new ModelAndView("inv/person/show",model);
    }

    @RequestMapping(value = "save.html", method = RequestMethod.POST)
    public String save(@ModelAttribute("person") Person person) {
		PasswordTools ptools = new PasswordTools();
		person.setPassword(ptools.hashPassword(person.getPassword()));

        invDaoService.getPersonService().saveOrUpdate(person);
        return "redirect:/inv/person/list.html";
    }

    @RequestMapping( value = "delete.html", method = RequestMethod.GET )
    public ModelAndView confirmDelete( @RequestParam("personId") Integer personId ) {
        ModelMap model = new ModelMap();
        Person person = invDaoService.getPersonService().findById(personId);
        model.addAttribute( "person", person );
        return new ModelAndView( "inv/person/delete", model );
    }

    @RequestMapping(value = "changePassword.html", method = RequestMethod.GET)
	public ModelAndView changePassword(
			@RequestParam("personId") int personId,
			@RequestParam(value= "status",required=false) String status,
			HttpServletRequest req,ModelMap model)
	{
		if(status != null && status.equalsIgnoreCase("error"))
			model.addAttribute("redBoxMessage", "Error Changing Password");
		model.addAttribute("personId", personId);
		model.addAttribute("templatepagename","changePassword");
		String template="";
		template="Default";
		return new ModelAndView(template,model);

	}
	@RequestMapping(value = "saveChangePassword.html", method = RequestMethod.POST)
	public ModelAndView saveChangePassword(
			@RequestParam("personId") int personId,
			@RequestParam("password") String password,
			HttpServletRequest req,ModelMap model
	)
	{
		PasswordTools ptools = new PasswordTools();

		Person person = invDaoService.getPersonService().findById(personId);
		person.setPassword(ptools.hashPassword(password));

		invDaoService.getPersonService().save(person);

		return new ModelAndView("redirect:list.html",model);

	}

    @RequestMapping( value = "delete.html", method = RequestMethod.POST )
    public String doDelete( @RequestParam( value = "submit" ) String submitButtonValue, @RequestParam( "personId" ) Integer personId  ) {
        if ( StringUtils.equalsIgnoreCase( submitButtonValue, "yes" ) ) {
            Person person = invDaoService.getPersonService().findById( personId );
            invDaoService.getPersonService().delete( person );
        }
        return "redirect:/inv/person/list.html";
    }
}


text:
using BrightData;

namespace BrightWire.ExecutionGraph.WeightInitialisation
{
    /// <summary>
    /// Initalises all weights to a constant
    /// </summary>
    internal class Constant : IWeightInitialisation
    {
        readonly ILinearAlgebraProvider _lap;
        readonly float _biasValue, _weightValue;

        public Constant(ILinearAlgebraProvider lap, float biasValue = 0f, float weightValue = 1f)
        {
            _lap = lap;
            _biasValue = biasValue;
            _weightValue = weightValue;
        }

        public IFloatVector CreateBias(uint size)
        {
            return _lap.CreateVector(size, _biasValue);
        }

        public IFloatMatrix CreateWeight(uint rows, uint columns)
        {
            return _lap.CreateMatrix(rows, columns, _weightValue);
        }
    }
}


text:
require 'rails'
require 'rails/all'
require 'action_view/testing/resolvers'

require 'rails-push-notifications'

module RailsPushNotificationsApp
  class Application < Rails::Application
    config.root = File.expand_path("../../..", __FILE__)
    config.cache_classes = true

    config.eager_load = false
    config.static_cache_control = "public, max-age=3600"

    config.consider_all_requests_local       = true
    config.action_controller.perform_caching = false

    config.action_dispatch.show_exceptions = false

    config.action_controller.allow_forgery_protection = false

    config.active_support.deprecation = :stderr

    config.middleware.delete "Rack::Lock"
    config.middleware.delete "ActionDispatch::Flash"
    config.middleware.delete "ActionDispatch::BestStandardsSupport"
    config.secret_key_base = '49837489qkuweoiuoqwehisuakshdjksadhaisdy78o34y138974xyqp9rmye8yrpiokeuioqwzyoiuxftoyqiuxrhm3iou1hrzmjk'
    routes.append do
      get "/" => "application#index"
    end
  end
end

class ApplicationController < ActionController::Base
  include Rails.application.routes.url_helpers
  layout 'application'
  self.view_paths = [ActionView::FixtureResolver.new(
    "layouts/application.html.erb" => '<%= yield %>',
    "welcome/index.html.erb"=> 'Hello from index.html.erb',
  )]

  def index
  end

end

RailsPushNotificationsApp::Application.initialize!


text:
package edu.gemini.jstl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

public class GroupSystem {

    private Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/st_student";
        Connection con = DriverManager.getConnection(url, "root", "root");
        return con;
    }

    public List<Group> findGroup() {
        List<Group> groupList = new LinkedList<Group>();

        try {
            Connection con = getConnection();
            try {
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * FROM st_group ORDER BY groupName");
                while (rs.next()) {
                    Group g = new Group(rs);
                    groupList.add(g);
                }
                rs.close();
                stmt.close();
            } finally {
                con.close();
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return groupList;

    }
}


text:
export default class TimelineController {

  constructor(UsersService, TObjectsService, $window) {

    'ngInject';

    this.users = UsersService.all();
    this.tObjs = TObjectsService.all();

  }

  ontObjUpdate(tObj) {
    console.log(tObj);
  }

  onPost(tObjRaw) {
    console.log(this.tObjs);
    this.tObjs.push(tObjRaw);
  }

  delete(tObj) {
    this.tObjs.forEach((tEl, index) => {
      if(tEl.id === tObj.id) {
        this.tObjs.splice(index, 1);
      }
    });
  }

  createTObj() {

  }

}


text:
namespace handinput {
#define ABS_ERROR 0.1

  class HMMTest : public ::testing::Test {

  protected:
    static const int kFeatureLen = 35;
    static const std::string kModelFile;
    mxArray* model_;

    virtual void SetUp() {
      char full[_MAX_PATH];
      _fullpath(full, kModelFile.c_str(), _MAX_PATH);
      // Only takes absolute path.
      MATFile* file = matOpen(full, "r");
      model_ = matGetVariable(file, "model");
    }

    virtual void TearDown() {
      mxDestroyArray(model_);
    }
  };

  const std::string HMMTest::kModelFile = "../../../data/model.mat";

  TEST_F(HMMTest, Fwdback) {
    using Eigen::VectorXf;
    std::unique_ptr<HMM> hmm(HMM::CreateFromMxArray(mxGetField(model_, 0, "infModel"), 0));
    ASSERT_EQ(kFeatureLen, hmm->feature_len());

    hmm->Fwdback(VectorXf::Zero(kFeatureLen));
    ASSERT_EQ(8, hmm->MostLikelyState());

    hmm->Fwdback(VectorXf::Ones(kFeatureLen));
    ASSERT_EQ(8, hmm->MostLikelyState());

    const std::vector<int>& map = hmm->state_to_label_map();
    ASSERT_EQ(1, map[0]);
    ASSERT_EQ(4, map[map.size() - 1]);

    const std::vector<std::string> stage_map = hmm->stage_map();
    EXPECT_EQ("PreStroke", stage_map[0]);
    EXPECT_EQ("Gesture", stage_map[stage_map.size() - 1]);
  }

  TEST_F(HMMTest, FwdbackWithLag) {
    using Eigen::VectorXf;
    std::unique_ptr<HMM> hmm(HMM::CreateFromMxArray(mxGetField(model_, 0, "infModel"), 3));
    hmm->Fwdback(VectorXf::Zero(kFeatureLen));
    ASSERT_EQ(8, hmm->MostLikelyState());

    hmm->Fwdback(VectorXf::Ones(kFeatureLen) * 0.1f);
    ASSERT_EQ(8, hmm->MostLikelyState());

    hmm->Fwdback(VectorXf::Ones(kFeatureLen) * 0.3f);
    ASSERT_EQ(8, hmm->MostLikelyState());

    hmm->Fwdback(VectorXf::Ones(kFeatureLen) * -0.1f);
    ASSERT_EQ(8, hmm->MostLikelyState());
  }

}


text:
/**
 * Pison: Tour Guide (NPC 1081001)
 * Florina Road: Florina Beach (Map 110000000)
 *
 * Teleports player from Florina Beach back to Lith Harbor.
 *
 * @author GoldenKevin (content from Vana r3171)
 */

let [returnMap, spawnPoint] = npc.getRememberedMap("FLORINA");
npc.askMenu("So you want to leave #b#m110000000##k? If you want, I can take you back to #b#m" + returnMap + "##k.\r\n#b"
		+ "#L0# #b I would like to go back now.");

let selection = npc.askYesNo("Are you sure you want to return to #b#m" + returnMap + "##k? Alright, we'll have to get going fast. Do you want to head back to #m" + returnMap + "# now?");
if (selection == 1) {
	player.changeMap(returnMap, spawnPoint);
	npc.resetRememberedMap("FLORINA");
} else if (selection == 0) {
	npc.sayNext("You must have some business to take care of here. It's not a bad idea to take some rest at #m" + returnMap + "#. Look at me; I love it here so much that I wound up living here. Hahaha! Anyway, talk to me when you feel like going back.");
}


text:
using System;
using Microsoft.SPOT;
using Robotics.Micro.SpecializedBlocks;

namespace Robotics.Micro.Motors
{
    public class AdafruitMotorShield : I2CBlock
    {
        public const byte DefaultAddress = 0x60;

        const byte PCA9685_MODE1 = 0x0;
        const byte PCA9685_PRESCALE = 0xFE;

        public AdafruitMotorShield (uint pwmFrequency = DefaultPwmFrequency, byte address = DefaultAddress, int clockRateKhz = DefaultClockRate)
            : base (address, clockRateKhz)
        {
            Reset ();
            SetPwmFrequency (pwmFrequency);
            for (byte i = 0; i < NumPins; i++) {
                SetPwm (i, 0, 0);
            }
        }

        public void Reset ()
        {
            // Debug.Print ("AdafruitMotorShield.Reset ()");
            WriteByte (PCA9685_MODE1, 0);
        }

        const ushort MaxPwmValue = 4095; // Inclusive
        const ushort ConstantPwmValue = 4096;

        const byte NumPins = 16;

        public void SetPin (byte pin, bool value)
        {
            if (value) {
                SetPwm (pin, ConstantPwmValue, 0);
            }
            else {
                SetPwm (pin, 0, 0);
            }
        }

        public void SetPwm (byte pin, ushort value)
        {
            if (value > MaxPwmValue) {
                SetPwm (pin, ConstantPwmValue, 0);
            }
            else {
                SetPwm (pin, 0, value);
            }
        }

        AdafruitDCMotor[] motors = new AdafruitDCMotor[4];

        public AdafruitDCMotor GetMotor (int num)
        {
            var index = num - 1;
            if (index < 0 || index >= motors.Length)
                throw new ArgumentException ("Only motors 1-" + motors.Length + " are available.");

            var m = motors[index];
            if (m == null) {
                byte pwm, in1, in2;
                switch (index) {
                    case 0:
                        pwm = 8;
                        in2 = 9;
                        in1 = 10;
                        break;
                    case 1:
                        pwm = 13;
                        in2 = 12;
                        in1 = 11;
                        break;
                    case 2:
                        pwm = 2;
                        in2 = 3;
                        in1 = 4;
                        break;
                    default:
                        pwm = 7;
                        in2 = 6;
                        in1 = 5;
                        break;
                }
                m = new AdafruitDCMotor (this, pwm, in1, in2);
                motors[index] = m;
            }
            return m;
        }

        const uint DefaultPwmFrequency = 1600;

        void SetPwmFrequency (uint freqHz)
        {
            // Debug.Print ("Set PWM Frequency to " + freqHz + " hz");

            float prescaleval = 25000000;
            prescaleval /= 4096;
            prescaleval /= freqHz;
            prescaleval -= 1;
            byte prescale = (byte)System.Math.Floor (prescaleval + 0.5);

            var oldmode = ReadByte (PCA9685_MODE1);
            var newmode = (byte)((oldmode & 0x7F) | 0x10); // sleep
            WriteByte (PCA9685_MODE1, newmode); // go to sleep
            WriteByte (PCA9685_PRESCALE, prescale); // set the prescaler
            WriteByte (PCA9685_MODE1, oldmode);
            System.Threading.Thread.Sleep (5); // OMG
            WriteByte (PCA9685_MODE1, (byte)(oldmode | 0xA1));
        }

        const byte LED0_ON_L = 0x6;

        byte[] setPwmBuffer = new byte[4];

        void SetPwm (byte pin, ushort on, ushort off)
        {
            // Debug.Print ("Set PWM #" + pin + ": " + on + " / " + off);

            setPwmBuffer[0] = (byte)on;
            setPwmBuffer[1] = (byte)(on >> 8);
            setPwmBuffer[2] = (byte)off;
            setPwmBuffer[3] = (byte)(off >> 8);

            WriteBytes ((byte)(LED0_ON_L + 4 * pin), setPwmBuffer);
        }
    }

    public class AdafruitDCMotor : Block, IDCMotor
    {
        readonly AdafruitMotorShield shield;

        readonly byte pwmPin;
        readonly byte in1Pin;
        readonly byte in2Pin;

        /// <summary>
        /// Remember if we're reversed to minimize state changes
        /// </summary>
        bool isReversed = false;

        /// <summary>
        /// The speed of the motor from -1 to 1.
        /// </summary>
        public InputPort SpeedInput { get; private set; }

        /// <summary>
        /// When true, the wheels spin "freely"
        /// </summary>
        public InputPort IsNeutralInput { get; private set; }

        public AdafruitDCMotor (AdafruitMotorShield shield, byte pwmPin, byte in1Pin, byte in2Pin)
        {
            this.shield = shield;
            this.pwmPin = pwmPin;
            this.in1Pin = in1Pin;
            this.in2Pin = in2Pin;

            SpeedInput = AddInput ("SpeedInput", Units.Ratio);
            IsNeutralInput = AddInput ("IsNeutralInput", Units.Boolean);

            SetDirection ();
            SetSpeed ();

            SpeedInput.ValueChanged += (s, e) => {

                var newlyReversed = SpeedInput.Value < 0;
                if (newlyReversed != isReversed) {
                    SetDirection ();
                }

                SetSpeed ();
            };
        }

        void SetSpeed ()
        {
            var speed = System.Math.Min (System.Math.Abs (SpeedInput.Value), 1);
            shield.SetPwm (pwmPin, (ushort)(4095 * speed));
        }

        void SetDirection ()
        {
            if (IsNeutralInput.Value >= 0.5) {
                shield.SetPin (in1Pin, false);
                shield.SetPin (in2Pin, false);
            }
            else {
                var d = SpeedInput.Value;

                // Note, always switch low (false) first to avoid glitches

                if (d < 0) {
                    // Reverse
                    shield.SetPin (in1Pin, false);
                    shield.SetPin (in2Pin, true);
                    isReversed = true;
                }
                else {
                    // Forward
                    shield.SetPin (in2Pin, false);
                    shield.SetPin (in1Pin, true);
                    isReversed = false;
                }
            }
        }
    }
}


text:
//
//  MJRefreshAutoStateFooter.m
//  MJRefreshExample
//
//  Created by MJ Lee on 15/6/13.
//  Copyright © 2015年 小码哥. All rights reserved.
//

#import "MJRefreshAutoStateFooter.h"

@interface MJRefreshAutoStateFooter()
{
    /** 显示刷新状态的label */
    __unsafe_unretained UILabel *_stateLabel;
}
/** 所有状态对应的文字 */
@property (strong, nonatomic) NSMutableDictionary *stateTitles;
@end

@implementation MJRefreshAutoStateFooter
#pragma mark - 懒加载
- (NSMutableDictionary *)stateTitles
{
    if (!_stateTitles) {
        self.stateTitles = [NSMutableDictionary dictionary];
    }
    return _stateTitles;
}

- (UILabel *)stateLabel
{
    if (!_stateLabel) {

        [self addSubview:_stateLabel = [UILabel label]];
    }
    return _stateLabel;
}

#pragma mark - 公共方法
- (void)setTitle:(NSString *)title forState:(MJRefreshState)state
{
    if (title == nil) return;
    self.stateTitles[@(state)] = title;
    self.stateLabel.text = self.stateTitles[@(self.state)];
}

#pragma mark - 私有方法
- (void)stateLabelClick
{
    if (self.state == MJRefreshStateIdle) {
        [self beginRefreshing];
    }
}

#pragma mark - 重写父类的方法
- (void)prepare
{
    [super prepare];

    // 初始化文字
    [self setTitle:MJRefreshAutoFooterIdleText forState:MJRefreshStateIdle];
    [self setTitle:MJRefreshAutoFooterRefreshingText forState:MJRefreshStateRefreshing];
    [self setTitle:MJRefreshAutoFooterNoMoreDataText forState:MJRefreshStateNoMoreData];

    // 监听label
    self.stateLabel.userInteractionEnabled = YES;
    [self.stateLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(stateLabelClick)]];
}

- (void)placeSubviews
{
    [super placeSubviews];

    if (self.stateLabel.constraints.count) return;

    // 状态标签
    self.stateLabel.frame = self.bounds;
}

- (void)setState:(MJRefreshState)state
{
    MJRefreshCheckState

    if (self.isRefreshingTitleHidden && state == MJRefreshStateRefreshing) {
        self.stateLabel.text = nil;
    } else {
        self.stateLabel.text = self.stateTitles[@(state)];
    }
}
@end


text:
<!--
  ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<resource path="/repository/dashboards" isCollection="true">
	<mediaType />
	<description />
	<children>
		<resource path="/repository/dashboards/governance"
			isCollection="true">
			<mediaType />
			<description />
			<children>
				<resource path="/repository/dashboards/governance/gadgets"
					isCollection="true">
					<mediaType />
					<description />
					<children>
						<resource path="/repository/dashboards/governance/gadgets/10"
							isCollection="true">
							<mediaType />
							<description />
							<properties>
								<property key="gadgetUrl">
									/registry/resource/_system/config/repository/dashboards/gadgets/impact-analysis.xml
								</property>
							</properties>
							<children>
								<resource
									path="/repository/dashboards/governance/gadgets/10/gadgetprefs"
									isCollection="true">
									<mediaType />
									<description />
									<properties>
										<property key="gadgetUserPrefs-10" />
									</properties>
									<children />
								</resource>
							</children>
						</resource>
						<resource path="/repository/dashboards/governance/gadgets/20"
							isCollection="true">
							<mediaType />
							<description />
							<properties>
								<property key="gadgetUrl">/carbon/impactAnalysis/impact.xml</property>
							</properties>
							<children>
								<resource
									path="/repository/dashboards/governance/gadgets/20/gadgetprefs"
									isCollection="true">
									<mediaType />
									<description />
									<properties>
										<property key="gadgetUserPrefs-20" />
									</properties>
									<children />
								</resource>
							</children>
						</resource>
						<resource path="/repository/dashboards/governance/gadgets/30"
							isCollection="true">
							<mediaType />
							<description />
							<properties>
								<property key="gadgetUrl">
									/registry/resource/_system/config/repository/dashboards/gadgets/life-cycle-info.xml
								</property>
							</properties>
							<children>
								<resource
									path="/repository/dashboards/governance/gadgets/30/gadgetprefs"
									isCollection="true">
									<mediaType />
									<description />
									<properties>
										<property key="gadgetUserPrefs-30" />
									</properties>
									<children />
								</resource>
							</children>
						</resource>
					</children>
				</resource>
				<resource path="/repository/dashboards/governance/nextGadgetId"
					isCollection="true">
					<mediaType />
					<description />
					<properties>
						<property key="nextGadgetId">200</property>
					</properties>
					<children />
				</resource>
				<resource path="/repository/dashboards/governance/tabs"
					isCollection="true">
					<mediaType />
					<description />
					<properties>
						<property key="nextTabId">200</property>
						<property key="currentTabLayout">0,3</property>
					</properties>
					<children>
						<resource path="/repository/dashboards/governance/tabs/0"
							isCollection="true">
							<mediaType />
							<description />
							<properties>
								<property key="tabTitle">Impact Data</property>
							</properties>
							<children>
								<resource
									path="/repository/dashboards/governance/tabs/0/currentGadgetLayout"
									isCollection="true">
									<mediaType />
									<description />
									<properties>
										<property key="currentGadgetLayout">{"layout":[{"id":"","width":"50%","layout":[{"id":"10","type":"gadget"}],"type":"columnContainer"},{"id":"","width":"50%","layout":[{"id":"20","type":"gadget"}],"type":"columnContainer"}]}</property>
									</properties>
									<children />
								</resource>
							</children>
						</resource>
						<resource path="/repository/dashboards/governance/tabs/3"
							isCollection="true">
							<mediaType />
							<description />
							<properties>
								<property key="tabTitle">Lifecycle Data</property>
							</properties>
							<children>
								<resource
									path="/repository/dashboards/governance/tabs/3/currentGadgetLayout"
									isCollection="true">
									<mediaType />
									<description />
									<properties>
										<property key="currentGadgetLayout">G1#30</property>
									</properties>
									<children />
								</resource>
							</children>
						</resource>
					</children>
				</resource>
			</children>
		</resource>
	</children>
</resource>


text:
namespace Benchmarks
{
    internal static class BenchmarkResourcePublicNames
    {
        public const string NameAttr = "full-name";
        public const string Type = "simple-types";
    }
}


text:
/**
 * @file mip-carousel 轮播组件
 *
 * @author fengchuantao
 * @modify wangpei07 2016-11-30
 */
define(function (require) {
    var customElem = require('customElement').create();
    var viewer = require('viewer');
    var carouselParas = {
        boxClass: 'mip-carousel-container',
        wrapBoxClass: 'mip-carousel-wrapper',
        slideBox: 'mip-carousel-slideBox',
        activeitem: 'mip-carousel-activeitem',
        threshold: 0.2
    };
    // 按tagName创建一个固定class的tag
    function createTagWithClass(className, tagName) {
        tagName = tagName || 'div';
        var tag = document.createElement(tagName);
        tag.className = className || '';
        return tag;
    }
    // 获取carouse标签下所有非mip layout引入的元素
    function getChildNodes(element) {
        var allChildNodes = element.children;
        var arrNode = Array.prototype.slice.call(allChildNodes);
        var childList = [];

        arrNode.map(function (ele, i) {
            if (ele.tagName.toLowerCase() !== 'mip-i-space') {
                // 如果是 autoplay,则不允许有 popup 功能
                if (element.hasAttribute('autoplay')) {
                    if (ele.hasAttribute('popup')) {
                        ele.removeAttribute('popup');
                    }
                }
                childList.push(ele);
                element.removeChild(ele);
            }

        });
        if (childList.length > 0) {
            // 拷贝第一个和最后一个节点拼接dom
            var firstCard = childList[0].cloneNode(true);
            var endCard = childList[childList.length - 1].cloneNode(true);
            childList.unshift(endCard);
            childList.push(firstCard);
        }
        return childList;
    }

    // 移动函数
    function translateFn(value, time, wrapBox) {
        wrapBox.style.webkitTransform = 'translate3d(' + value + 'px, 0px, 0px)';
        wrapBox.style.transitionDuration = time;
    }

    // 移出class
    function removeClass(dom, className) {
        if (!dom) {
            return;
        }
        var curClassName = dom.className;
        dom.className = curClassName.replace(className, '').replace(/(^\s*)|(\s*$)/g, '');
    }

    // 追加class
    function addClass(dom, className) {
        if (!dom) {
            return;
        }
        var curClassName = dom.className;
        if (!curClassName) {
            dom.className = className;
        }
        else {
            dom.className = curClassName + ' ' + className;
        }
    }

    /**
     * 计算滚动之后需要到达的坐标 resetPosAndIdx
     * @param {int} curIndex
     * @param {int} totalNum
     * @param {int} deviceWidth
     * @param {int} endPosition
     * @return {Object}
     */

    function resetPosAndIdx(curIndex, totalNum, deviceWidth, endPos) {
        var endInfo = {
            endPos: 0,
            endIndex: curIndex
        };
        if (curIndex === totalNum - 1) {
            endInfo.endPos = -deviceWidth;
            endInfo.endIndex = 1;
        }
        else if (curIndex === 0) {
            // if it is last one
            endInfo.endPos = -(totalNum - 2) * deviceWidth;
            endInfo.endIndex = totalNum - 2;
        }
        else {
            endInfo.endPos = endPos;
        }
        return endInfo;
    }

    // changeIndicatorStyle
    function changeIndicatorStyle(startDot, endDot, className) {
        removeClass(startDot, className);
        addClass(endDot, className);
    }
    customElem.prototype.build = function () {
        var ele = this.element;
        var self = this;
        var eleWidth = ele.clientWidth;

        var dotItems = [];

        // 获取用户填写属性
        // 是否自动播放
        var isAutoPlay = ele.hasAttribute('autoplay');

        // 图片间隔时长默认为4000
        var isDefer = ele.getAttribute('defer');

        var isDeferNum = (!!isDefer) ? isDefer : 4000;

        // 分页显示器
        var showPageNum = ele.hasAttribute('indicator');

        // 翻页按钮
        var showBtn = ele.hasAttribute('buttonController');

        // 翻页按钮
        var indicatorId = ele.getAttribute('indicatorId');

        // Gesture锁
        var slideLock = {
            stop: 1
        };

        // btn按钮手势锁
        var btnLock = {
            stop: 1
        };

        // 缓存上一次手势位置
        var prvGestureClientx = 0;

        // 缓存当前值轮播位置
        var curGestureClientx = -eleWidth;

        // 当前图片显示索引
        var imgIndex = 1;

        // 定时器时间hold
        var moveInterval;

        // 禁止左右滑动配置
        var startPos = {};
        var endPos = {};
        var isScrolling = 0;

        // 获取carousel下的所有节点
        var childNodes = getChildNodes(ele);

        // 图片显示个数
        // 其实图片个数应该为实际个数+2.copy了头和尾的两部分
        var childNum = childNodes.length;

        // length 等于0时,不做任何处理
        if (childNum === 0) {
            return;
        }
        // 将getChildNodes获取的元素拼装轮播dom
        var carouselBox = createTagWithClass(carouselParas.boxClass);

        var wrapBox = createTagWithClass(carouselParas.wrapBoxClass);

        childNodes.map(function (ele, i) {
            var slideBox = createTagWithClass(carouselParas.slideBox);
            slideBox.appendChild(ele);
            slideBox.style.width = (100 / childNum) + '%';
            wrapBox.appendChild(slideBox);

            // 遍历mip-img计算布局
            self.applyFillContent(ele, true);
            // inview callback  bug, TODO
            var MIP = window.MIP || {};
            MIP.prerenderElement(ele);
            var allImgs = ele.querySelectorAll('mip-img');
            var len = allImgs.length;
            for (var idx = 0; idx < len; idx++) {
                self.applyFillContent(allImgs[idx], true);
                MIP.prerenderElement(allImgs[idx]);
            }
        });

        wrapBox.style.width = childNum * 100 + '%';
        carouselBox.appendChild(wrapBox);
        ele.appendChild(carouselBox);

        var transitionend = ((onwebkittransitionend in window) && 'webkittransitionend') || 'transitionend';
        wrapBox.addEventListener(transitionend, function (event) {
            viewer.eventAction.execute('slideChange', event.target, event);
        });

        // 初始渲染时应该改变位置到第一张图
        var initPostion = -eleWidth;
        wrapBox.style.webkitTransform = 'translate3d(' + initPostion + 'px, 0, 0)';

        // 绑定wrapBox的手势事件
        // 手势移动的距离
        var diffNum = 0;

        // 绑定手势点击事件
        wrapBox.addEventListener('touchstart', function (event) {
            // 以下兼容横屏时禁止左右滑动
            var touch = event.targetTouches[0];
            startPos = {
                x: touch.pageX,
                y: touch.pageY,
                time: (+new Date)
            };
            isScrolling = 0; // 这个参数判断是垂直滚动还是水平滚动

            // 获取手势点击位置
            prvGestureClientx = touch.pageX;
            clearInterval(moveInterval);
        }, false);

        wrapBox.addEventListener('touchmove', function (event) {
            // 阻止触摸事件的默认行为,即阻止滚屏
            var touch = event.targetTouches[0];
            endPos = {
                x: touch.pageX - startPos.x,
                y: touch.pageY - startPos.y
            };
            isScrolling = Math.abs(endPos.x) < Math.abs(endPos.y) ? 1 : 0; // isScrolling为1时,表示纵向滑动,0为横向滑动
            if (isScrolling === 0) {
                event.preventDefault();
            }

            // 获取手指移动的距离
            diffNum = event.targetTouches[0].pageX - prvGestureClientx;

            // 外框同步运动
            translateFn(diffNum + curGestureClientx, '0ms', wrapBox);

            // 滚动手势锁 正在滑动
            slideLock.stop = 0;

        }, false);

        wrapBox.addEventListener('touchend', function (event) {
            //  只有滑动之后才会触发
            if (!slideLock.stop) {
                var startIdx = imgIndex;
                var endIdx = startIdx;
                // 如果大于设定阈值
                if (Math.abs(diffNum) > eleWidth * carouselParas.threshold) {
                    endIdx = (diffNum > 0) ? imgIndex - 1 : imgIndex + 1;
                }
                move(wrapBox, startIdx, endIdx);
                slideLock.stop = 1;
            }

            // 如果存在自动则调用自动轮播
            if (isAutoPlay) {
                clearInterval(moveInterval);
                autoPlay();
            }

        }, false);

        // 自动轮播
        if (!!isAutoPlay) {
            autoPlay();
        }

        // 指示器
        if (!!showPageNum) {
            indicator();
        }

        // 控制按钮
        if (!!showBtn) {
            cratebutton();
        }

        // 是否关联indicator
        if (!!indicatorId) {
            indicatorDot(indicatorId);
        }

        // 自动轮播
        function autoPlay() {
            moveInterval = setInterval(function () {
                move(wrapBox, imgIndex, imgIndex + 1);
            }, isDeferNum);
        }

        // 创建指示器
        function indicator() {
            var indicatorBox = createTagWithClass('mip-carousel-indicatorbox');
            var indicatorBoxWrap = createTagWithClass('mip-carousel-indicatorBoxwrap', 'p');
            var indicatorNow = createTagWithClass('mip-carousel-indicatornow', 'span');
            var indicatorAllNum = createTagWithClass('', 'span');
            indicatorAllNum.innerHTML = '/' + (childNum - 2);
            indicatorNow.innerHTML = imgIndex;
            indicatorBoxWrap.appendChild(indicatorNow);
            indicatorBoxWrap.appendChild(indicatorAllNum);
            indicatorBox.appendChild(indicatorBoxWrap);
            ele.appendChild(indicatorBox);
        }

        // 指示器数字变化
        function indicatorChange(idx) {
            if (!showPageNum) {
                return;
            }
            var indicatorNow = ele.querySelector('.mip-carousel-indicatornow');
            indicatorNow.innerHTML = idx;
        }

        // 创建左右轮播切换btn
        function cratebutton() {
            var preBtn = document.createElement('p');
            preBtn.className = 'mip-carousel-preBtn';
            var nextBtn = document.createElement('p');
            nextBtn.className = 'mip-carousel-nextBtn';

            ele.appendChild(preBtn);
            ele.appendChild(nextBtn);
            bindBtn();
        }

        // 绑定按钮切换事件
        function bindBtn() {
            ele.querySelector('.mip-carousel-preBtn').addEventListener('click', function (event) {
                if (!btnLock.stop) {
                    return;
                }

                btnLock.stop = 0;

                imgIndex = imgIndex - 1;

                clearInterval(moveInterval);
                move(wrapBox, imgIndex + 1, imgIndex);
                if (isAutoPlay) {
                    autoPlay();
                }

            }, false);

            ele.querySelector('.mip-carousel-nextBtn').addEventListener('click', function (event) {
                if (!btnLock.stop) {
                    return;
                }

                btnLock.stop = 0;

                imgIndex = imgIndex + 1;
                clearInterval(moveInterval);
                move(wrapBox, imgIndex - 1, imgIndex);
                if (isAutoPlay) {
                    autoPlay();
                }

            }, false);
        }

        // 图片滑动处理与手势滑动函数endPosition为最终距离,Duration变换时间
        function move(wrapBox, startIdx, endIdx, Duration) {
            if (!wrapBox) {
                return;
            }
            // 双保险,确认位移的是 ele 的 width
            if (eleWidth !== ele.clientWidth) {
                eleWidth = ele.clientWidth;
            }
            imgIndex = endIdx;
            var endPosition = -eleWidth * endIdx;
            if (Duration) {
                translateFn(endPosition, '0ms', wrapBox);
                wrapBox.style.transitionDuration = '0ms';
            }
            else {
                translateFn(endPosition, '300ms', wrapBox);
                wrapBox.style.transitionDuration = '300ms';
            }
            // resetPosAndIdx
            var posIdxObj = resetPosAndIdx(imgIndex, childNum, eleWidth, endPosition);
            curGestureClientx = posIdxObj.endPos;
            endIdx = posIdxObj.endIndex;
            imgIndex = endIdx;

            // 如果有指示器,需更新选中位置的样式
            if (dotItems.length > 0) {
                changeIndicatorStyle(dotItems[startIdx - 1], dotItems[endIdx - 1], carouselParas.activeitem);
            }
            // 如果切换了坐标,需要在动画结束后重置translatex位置
            if (curGestureClientx !== endPosition) {
                setTimeout(function () {
                    translateFn(curGestureClientx, '0ms', wrapBox);
                    btnLock.stop = 1;
                }, 300);
            }
            btnLock.stop = 1;
            indicatorChange(imgIndex);
        }

        // 处理圆点型指示器
        function indicatorDot(domId) {
            var indicDom = document.getElementById(domId);
            if (!indicDom) {
                return;
            }
            dotItems = indicDom.children;
            var dotLen = dotItems.length;

            if (dotLen === childNum - 2) {
                for (var i = 0; i < dotLen; i++) {
                    dotItems[i].count = i;
                    dotItems[i].addEventListener('click', function (event) {
                        var count = this.count;
                        clearInterval(moveInterval);
                        move(wrapBox, imgIndex, count + 1);
                        if (isAutoPlay) {
                            autoPlay();
                        }
                    });
                }
            }
            else {
                // 若个数不匹配,则隐藏掉indicator
                indicDom.style.display = 'none';
                dotItems = [];
            }
        }
        // 横竖屏兼容处理
        window.addEventListener('resize', function () {
            eleWidth = ele.clientWidth;
            move(wrapBox, imgIndex, imgIndex, '0ms');
        }, false);

    };

    return customElem;
});


text:
\textbf{Question 3:}

\begin{enumerate}[a)]
\item \emph{Intelligence: } The ability to effectively use previously acquired knowledge.
\item \emph{artificial: } A thing which has been reproduced or created by man; not of natural origin.
\item \emph{Intelligence: } Listed twice; see above.
\item \emph{Agent: } A entity which is active (as opposed to passive) in it's environment.
\item \emph{Cognitive Science: } The study of the brain which focuses on the the workings of thought, as opposed to Neuroscience which focuses on the workings of the brain itself, and psychology which focuses on the behaviour of the agent.
\item \emph{Cognitive Robotics: } The field of robotics which focuses on embedding cognitive models and finding from Cognitive Science into robotic agents.
\end{enumerate}


text:
<?xml version="1.0"?>
<config>
    <modules>
        <ES_PageSpeedCacheFlush>
            <active>true</active>
            <codePool>local</codePool>
        </ES_PageSpeedCacheFlush>
    </modules>
</config>


text:
package org.keycloak.models.cache.infinispan.entities;

import org.keycloak.models.FederatedIdentityModel;
import org.keycloak.models.RealmModel;

import java.util.HashSet;
import java.util.Set;

/**
 * The cache entry, which contains list of all identityProvider links for particular user. It needs to be updated every time when any
 * federation link is added, removed or updated for the user
 *
 * @author Marek Posolda
 */
public class CachedFederatedIdentityLinks extends AbstractRevisioned implements InRealm {

    private final String realmId;
    private final Set<FederatedIdentityModel> federatedIdentities = new HashSet<>();

    public CachedFederatedIdentityLinks(Long revision, String id, RealmModel realm, Set<FederatedIdentityModel> federatedIdentities) {
        super(revision, id);
        this.realmId = realm.getId();
        this.federatedIdentities.addAll(federatedIdentities);
    }

    @Override
    public String getRealm() {
        return realmId;
    }

    public Set<FederatedIdentityModel> getFederatedIdentities() {
        return federatedIdentities;
    }
}


text:
const express = require('express')
const ms = require('ms')
const apn = require('apn')
const router = express.Router()
const joi = require('joi')
const { validate } = require('../helpers')

// const apnProvider = new apn.Provider({
//    token: {
//     key: process.env.IOS_PATH_TO_P8_FILE,
//     keyId: process.env.IOS_KEY_ID,
//     teamId: process.env.IOS_TEAM_ID
//   },
//   production: false
// })
//
// const sendNotification = ({ deviceToken }) => {
//   const notification = new apn.Notification()
//   notification.topic = process.env.IOS_BUNDLE_ID
//   notification.expiry = ms('1h')
//   notification.badge = 1
//   notification.sound = 'ping.aiff'
//   notification.alert = 'Hello World \u270C'
//   notification.payload = { id: 123 }
//   apnProvider.send(notification, deviceToken)
//     .then(result => {
//       console.log(result)
//       return result
//     })
// }
//
// router.post('/send/:deviceToken', async (req, res) => {
//   const { deviceToken } = res.params
//   const deviceToken = '5311839E985FA01B56E7AD74444C0157F7F71A2745D0FB50DED665E0E882'
//   sendNotification(deviceToken)
// })

module.exports = router


text:
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" media="all" href="ars.min.css">

Ex-Ashley Madison blah blah

Raja Bhatia's lawyer says that he merely "noticed" an "inadequacy" but did not exploit it.

    Read more stories


text:
<?php

/**
 * Convert profile edit tab
 *
 * @category    Mage
 * @package     Mage_Connect
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    /**
     * Initialize Grid block
     *
     */
    public function __construct()
    {
        parent::__construct();
        $this->_defaultLimit = 200;
        $this->setId('extension_custom_edit_grid');
        $this->setUseAjax(true);
    }

    /**
     * Creates extension collection if it has not been created yet
     *
     * @return Mage_Connect_Model_Extension_Collection
     */
    public function getCollection()
    {
        if (!$this->_collection) {
            $this->_collection = Mage::getModel('connect/extension_collection');
        }
        return $this->_collection;
    }

    /**
     * Prepare Local Package Collection for Grid
     *
     * @return Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Grid
     */
    protected function _prepareCollection()
    {
        $this->setCollection($this->getCollection());
        return parent::_prepareCollection();
    }

    /**
     * Prepare grid columns
     *
     * @return Mage_Adminhtml_Block_Extension_Custom_Edit_Tab_Grid
     */
    protected function _prepareColumns()
    {
        $this->addColumn('folder', array(
            'header'  => Mage::helper('connect')->__('Folder'),
            'index'   => 'folder',
            'width'   => 100,
            'type'    => 'options',
            'options' => $this->getCollection()->collectFolders()
        ));

        $this->addColumn('package', array(
            'header' => Mage::helper('connect')->__('Package'),
            'index'  => 'package',
        ));

        return parent::_prepareColumns();
    }

    /**
     * Self URL getter
     *
     * @return string
     */
    public function getCurrentUrl($params = array())
    {
        if (!isset($params['_current'])) {
            $params['_current'] = true;
        }
        return $this->getUrl('*/*/grid', $params);
    }

    /**
     * Row URL getter
     *
     * @return string
     */
    public function getRowUrl($row)
    {
        return $this->getUrl('*/*/load', array('id' => strtr(base64_encode($row->getFilenameId()), '+/=', '-_,')));
    }
}


text:
import time
import simple_queue

from xlog import getLogger
xlog = getLogger("heroku_front")

class GAE_Exception(Exception):
    def __init__(self, error_code, message):
        xlog.debug("GAE_Exception %r %r", error_code, message)
        self.error_code = error_code
        self.message = "%r:%s" % (error_code, message)

    def __str__(self):
        # for %s
        return repr(self.message)

    def __repr__(self):
        # for %r
        return repr(self.message)

class BaseResponse(object):
    def __init__(self, status=601, reason="", headers={}, body=""):
        self.status = status
        self.reason = reason
        self.headers = headers

class Task(object):
    def __init__(self, method, host, path, headers, body, queue, url, timeout):
        self.method = method
        self.host = host
        self.path = path
        self.headers = headers
        self.body = body
        self.queue = queue
        self.url = url
        self.timeout = timeout
        self.start_time = time.time()
        self.unique_id = "%s:%f" % (url, self.start_time)
        self.trace_time = []
        self.body_queue = simple_queue.Queue()
        self.body_len = 0
        self.body_readed = 0
        self.content_length = None
        self.read_buffer = ""
        self.responsed = False
        self.finished = False
        self.retry_count = 0

    def to_string(self):
        out_str = " Task:%s\r\n" % self.url
        out_str += "   responsed:%d" % self.responsed
        out_str += "   retry_count:%d" % self.retry_count
        out_str += "   start_time:%d" % (time.time() - self.start_time)
        out_str += "   body_readed:%d\r\n" % self.body_readed
        out_str += "   Trace:%s" % self.get_trace()
        out_str += "\r\n"
        return out_str

    def put_data(self, data):
        self.body_queue.put(data)
        self.body_len += len(data)

    def read(self, size=None):
        # fail or cloe if return ""
        if self.body_readed == self.content_length:
            return ""

        if size:
            while len(self.read_buffer) < size:
                data = self.body_queue.get(self.timeout)
                if not data:
                    return ""

                self.read_buffer += data

            data = self.read_buffer[:size]
            self.read_buffer = self.read_buffer[size:]
        else:
            if len(self.read_buffer):
                data = self.read_buffer
                self.read_buffer = ""
            else:
                data = self.body_queue.get(self.timeout)
                if not data:
                    return ""

        self.body_readed += len(data)
        return data

    def read_all(self):
        out_list = [self.read_buffer]
        while True:
            data = self.body_queue.get(self.timeout)
            if not data:
                break
            out_list.append(data)

        return "".join(out_list)

    def set_state(self, stat):
        # for debug trace
        time_now = time.time()
        self.trace_time.append((time_now, stat))
        # xlog.debug("%s stat:%s", self.unique_id, stat)
        return time_now

    def get_trace(self):
        out_list = []
        last_time = self.start_time
        for t, stat in self.trace_time:
            time_diff = int((t - last_time) * 1000)
            last_time = t
            out_list.append("%d:%s" % (time_diff, stat))
        out_list.append(":%d" % ((time.time()-last_time)*1000))
        return ",".join(out_list)

    def response_fail(self, reason=""):
        if self.responsed:
            xlog.error("http_common responsed_fail but responed.%s", self.url)
            self.put_data("")
            return

        self.responsed = True
        err_text = "response_fail:%s" % reason
        xlog.debug("%s %s", self.url, err_text)
        res = BaseResponse(body=err_text)
        self.queue.put(res)
        self.finish()

    def finish(self):
        self.put_data("")
        self.finished = True

class HTTP_worker(object):
    def __init__(self, ssl_sock, close_cb, retry_task_cb, idle_cb, log_debug_data):
        self.ssl_sock = ssl_sock
        self.last_active_time = self.ssl_sock.create_time
        self.last_request_time = self.ssl_sock.create_time
        self.init_rtt = ssl_sock.handshake_time / 2
        self.rtt = self.init_rtt
        self.speed = 1
        self.ip = ssl_sock.ip
        self.close_cb = close_cb
        self.retry_task_cb = retry_task_cb
        self.idle_cb = idle_cb
        self.log_debug_data = log_debug_data
        self.accept_task = True
        self.keep_running = True
        self.processed_tasks = 0
        self.speed_history = []

    def update_debug_data(self, rtt, sent, received, speed):
        self.rtt = rtt
        self.log_debug_data(rtt, sent, received)
        self.speed = speed
        self.speed_history.append(speed)

    def close(self, reason):
        self.accept_task = False
        self.keep_running = False
        self.ssl_sock.close()
        xlog.debug("%s worker close:%s", self.ip, reason)
        self.close_cb(self)

    def get_score(self):
        now = time.time()
        inactive_time = now - self.last_active_time

        rtt = self.rtt
        if inactive_time > 30:
            if rtt > 1000:
                rtt = 1000

        if self.version == "1.1":
            rtt += 100
        else:
            rtt += len(self.streams) * 100

        if inactive_time > 10:
            score = rtt
        elif inactive_time < 0.001:
            score = rtt + 50000
        else:
            # inactive_time < 2
            score = rtt + (10/inactive_time)*1000

        return score


text:
'use strict';

angular.module('mean.students')
    .controller('StudentController', [
        '$scope',
        'Global',
        '$state',
        '$stateParams',
        'Students',
        'Restangular',
        'StudentsLocal',
        'Professors',
    function($scope, Global, $state, $stateParams, Students, Restangular, StudentsLocal, Professors) {

        $scope.global = Global;

        $scope.create = function() {
           Students.post($scope.student).then(function (student) {
               $state.go('all students');
           })
        };

        $scope.find = function() {
            Students.getList().then(function(students) {
                // Add all categories into the factory StudentsLocal.
              StudentsLocal.set(students);
              $scope.students = StudentsLocal.all();
            });
        };

        $scope.findOne = function  () {
            var studentId = $stateParams.studentId;
            Students.one(studentId).get().then(function (student) {
                $scope.student = student;
            });
        };

        $scope.update = function () {
            $scope.student.customPUT($scope.student, $scope.student._id);
            $state.go('all students');
        };

        $scope.remove = function(id) {

            var student = StudentsLocal.get(id);
            student.customDELETE(id).then(function () {
              StudentsLocal.remove(id);
            });

        };
          $scope.getProfessors = function(id) {
            Professors.getList().then(function (professors) {
                $scope.data = professors;
            })

        };

        // Filters

        $scope.orderByValue = function (val) {
            $scope.filterSelected = val;
        }

        $scope.predicate = '-code';
    }
]);