text:
<?php
namespace Payum\Core\Tests\Bridge\Symfony\Action\Http;

use Payum\Core\Bridge\Symfony\Action\GetHttpRequestAction;
use Payum\Core\Request\GetHttpRequest;
use Symfony\Component\HttpFoundation\Request;

class GetHttpRequestActionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldImplementActionInterface()
    {
        $rc = new \ReflectionClass('Payum\Core\Bridge\Symfony\Action\GetHttpRequestAction');

        $this->assertTrue($rc->implementsInterface('Payum\Core\Action\ActionInterface'));
    }

    /**
     * @test
     */
    public function couldBeConstructedWithoutAnyArguments()
    {
        new GetHttpRequestAction();
    }

    /**
     * @test
     */
    public function shouldAllowSetHttpReqeust()
    {
        $expectedRequest = new Request();

        $action = new GetHttpRequestAction();
        $action->setHttpRequest($expectedRequest);

        $this->assertAttributeSame($expectedRequest, 'httpRequest', $action);
    }

    /**
     * @test
     */
    public function shouldSupportGetHttpRequest()
    {
        $action = new GetHttpRequestAction();

        $this->assertTrue($action->supports(new GetHttpRequest()));
    }

    /**
     * @test
     */
    public function shouldNotSupportAnythingNotGetHttpRequest()
    {
        $action = new GetHttpRequestAction();

        $this->assertFalse($action->supports('foo'));
    }

    /**
     * @test
     *
     * @expectedException \Payum\Core\Exception\RequestNotSupportedException
     * @expectedExceptionMessage Action GetHttpRequestAction is not supported the request string.
     */
    public function throwIfNotSupportedRequestPassedToExecute()
    {
        $action = new GetHttpRequestAction();

        $action->execute('foo');
    }

    /**
     * @test
     */
    public function shouldDoNothingIfHttpRequestNotSet()
    {
        $action = new GetHttpRequestAction();

        $request = new \Payum\Core\Request\GetHttpRequest();
        $action->execute($request);

        $this->assertSame(array(), $request->query);
        $this->assertSame(array(), $request->request);
        $this->assertSame('', $request->method);
        $this->assertSame('', $request->uri);
    }

    /**
     * @test
     */
    public function shouldPopulateFromGetHttpRequest()
    {
        $action = new GetHttpRequestAction();
        $action->setHttpRequest(Request::create(
            'http://request.uri',
            'GET',
            array('foo' => 'fooVal')
        ));

        $request = new GetHttpRequest();
        $action->execute($request);

        $this->assertSame(array('foo' => 'fooVal'), $request->query);
        $this->assertSame(array(), $request->request);
        $this->assertSame('GET', $request->method);
        $this->assertSame('http://request.uri/?foo=fooVal', $request->uri);
        $this->assertSame('Symfony/2.X', $request->userAgent);
        $this->assertSame('127.0.0.1', $request->clientIp);
    }

    /**
     * @test
     */
    public function shouldPopulateFromPostHttpRequest()
    {
        $action = new GetHttpRequestAction();
        $action->setHttpRequest(Request::create(
            'http://request.uri',
            'POST',
            array('foo' => 'fooVal')
        ));

        $request = new \Payum\Core\Request\GetHttpRequest();
        $action->execute($request);

        $this->assertSame(array(), $request->query);
        $this->assertSame(array('foo' => 'fooVal'), $request->request);
        $this->assertSame('POST', $request->method);
        $this->assertSame('http://request.uri/', $request->uri);
        $this->assertSame('Symfony/2.X', $request->userAgent);
        $this->assertSame('127.0.0.1', $request->clientIp);
    }
}


text:
<form action="" method="POST" class="add_entry">

        Title
        <input type="test" size="30" name="title" id="title"/>

        Text
        <textarea name="text" id="text" rows="5" cols="80"></textarea>

        <input type="submit" value="Edit" name="Share"/>
        Cancel

</form>

redpajama_set_name: RedPajamaGithub


text:
const Discord = require("discord.js")
exports.run = (bot, message, args) => {
	message.channel.sendMessage(':alarm_clock: | Calculando...').then(message => {
		message.edit(':alarm_clock: | O ping é de ' + (Date.now() - message.createdTimestamp) + 'ms.')
	})
}


text:
<!--
  Test Description:
  Tests for amp-video-docking tag with amp-video player.
-->
<!doctype html>
<html ⚡ lang="en">
<head>
  <meta charset="utf-8">
  <link rel="canonical" href="./regular-html-version.html">
  <meta name="viewport" content="width=device-width,minimum-scale=1">
  <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
  <script async src="https://cdn.ampproject.org/v0.js"></script>
  <script async custom-element="amp-brid-player" src="https://cdn.ampproject.org/v0/amp-brid-player-latest.js"></script>
  <script async custom-element="amp-video-docking" src="https://cdn.ampproject.org/v0/amp-video-docking-latest.js"></script>
</head>
<body>
  <!-- Valid: dock with `amp-brid-player` and `amp-video-docking` extensions-->
  <amp-brid-player
      dock
      data-partner="264"
      data-player="4144"
      data-video="13663"
      layout="responsive"
      width="480" height="270">
  </amp-brid-player>
</body>
</html>


text:
package org.qinshuihepan.bbs.ui;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ListView;

import org.jsoup.Connection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.qinshuihepan.bbs.R;
import org.qinshuihepan.bbs.api.Api;
import org.qinshuihepan.bbs.data.Request;
import org.qinshuihepan.bbs.model.BasePost;
import org.qinshuihepan.bbs.model.Post;
import org.qinshuihepan.bbs.ui.adapter.MyPostsAdapter;
import org.qinshuihepan.bbs.util.TaskUtils;
import org.qinshuihepan.bbs.util.sharedpreference.Athority;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

public class MyPostsActivity extends Activity {

    ListView mListView;
    Context mContext;
    ArrayList<BasePost> posts = new ArrayList<BasePost>();
    MyPostsAdapter myPostsAdapter;
    int page = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("我的帖子");
        mContext = this;
        getActionBar().setDisplayHomeAsUpEnabled(true);
        setContentView(R.layout.activity_myposts);
        final String uid = Athority.getSharedPreference().getString("uid","");
        mListView = ( ListView) findViewById(R.id.listView);
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断滚动到底部
                        if (mListView.getLastVisiblePosition() == (mListView.getCount() - 1)) {
                            TaskUtils.executeAsyncTask(new AsyncTask<String, Void, ArrayList<BasePost>>() {
                                @Override
                                protected ArrayList<BasePost> doInBackground(String... params) {
                                    Document doc = null;
                                    String post_url = String.format(Api.MY_POSTS, uid) + "&page=" +String.valueOf(page);
                                    Connection.Response response = Request.execute(post_url, Api.USER_AGENT, (Map<String, String>) Athority.getSharedPreference().getAll(), Connection.Method.GET);
                                    try {
                                        doc = response.parse();
                                        Elements bm_cs = doc.getElementsByClass("bm_c");
                                        if (!bm_cs.text().equals("还没有相关的帖子")) {
                                            String str_tid = "";
                                            String title = "";
                                            String time = "";
                                            String comment_count = "";
                                            int haveimg = 0;
                                            int tid = 0;
                                            String author = Athority.getSharedPreference().getString("username","");
                                            BasePost post;
                                            for (Element bm_c : bm_cs) {
                                                Elements as = bm_c.getElementsByTag("a");
                                                for (Element a : as) {
                                                    String start = "forum.php?mod=viewthread  tid=";
                                                    String len = "  mobile=1";
                                                    String url = a.attr("href");
                                                    str_tid = url.substring(start.length() - 1 , url.length() - len.length() + 1);
                                                    tid = Integer.valueOf(str_tid);
                                                    title = a.text();
                                                }
                                                Elements xg1s = bm_c.getElementsByClass("xg1");
                                                comment_count = xg1s.text().substring("回".length());
                                                post = new Post(0, tid, 0, title, "", time, haveimg, Integer.valueOf(comment_count), author, null);
                                                posts.add(post);
                                            }
                                            page++;
                                        }
                                    } catch (IOException e ) {
                                        e.printStackTrace();
                                    }
                                    return posts;
                                }

                                @Override
                                protected void onPostExecute(ArrayList<BasePost> posts) {
                                    super.onPostExecute(posts);
                                    myPostsAdapter.refresh(posts);
                                }
                            });
                        }
                        // 判断滚动到顶部
                        if(mListView.getFirstVisiblePosition() == 0){
                        }
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {

            }
        });

        TaskUtils.executeAsyncTask(new AsyncTask<String, Void, ArrayList<BasePost>>() {
            @Override
            protected ArrayList<BasePost> doInBackground(String... params) {
                ArrayList<BasePost> posts = new ArrayList<BasePost>();
                Document doc = null;
                Connection.Response response = Request.execute(String.format(Api.MY_POSTS, uid), Api.USER_AGENT, (Map<String, String>) Athority.getSharedPreference().getAll(), Connection.Method.GET);
                try {
                    doc = response.parse();
                    Elements bm_cs = doc.getElementsByClass("bm_c");
                    String str_tid = "";
                    String title = "";
                    String time = "";
                    String comment_count = "";
                    int haveimg = 0;
                    int tid = 0;
                    String author = Athority.getSharedPreference().getString("username","");
                    BasePost post;
                    for (Element bm_c : bm_cs) {
                        Elements as = bm_c.getElementsByTag("a");
                        for (Element a : as) {
                            String start = "forum.php?mod=viewthread  tid=";
                            String len = "  mobile=1";
                            String url = a.attr("href");
                            str_tid = url.substring(start.length() - 1 , url.length() - len.length() + 1);
                            tid = Integer.valueOf(str_tid);
                            title = a.text();
                        }
                        Elements xg1s = bm_c.getElementsByClass("xg1");
                        if(xg1s.text().length() != 0) {
                            comment_count = xg1s.text().substring("回".length());
                        } else {
                            comment_count = "0";
                        }
                        post = new Post(0, tid, 0, title, "", time, haveimg, Integer.valueOf(comment_count), author, null);
                        posts.add(post);
                    }
                } catch (IOException e ) {
                    e.printStackTrace();
                }
                return posts;
            }

            @Override
            protected void onPostExecute(ArrayList<BasePost> posts) {
                super.onPostExecute(posts);
                if(posts.size() == 1) {
                    posts.clear();
                }
                myPostsAdapter = new MyPostsAdapter(mContext, posts, mListView);
                mListView.setAdapter(myPostsAdapter);
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

}


text:
package main

import (
	"flag"
	"fmt"
	"net/http"
	"path"
	"strings"
	"time"

	"golang.org/x/net/context"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/acl"
	"github.com/youtube/vitess/go/timer"
	"github.com/youtube/vitess/go/vt/schemamanager"
	"github.com/youtube/vitess/go/vt/servenv"
	"github.com/youtube/vitess/go/vt/tabletmanager/tmclient"
	"github.com/youtube/vitess/go/vt/topo"
	"github.com/youtube/vitess/go/vt/topotools"
	"github.com/youtube/vitess/go/vt/wrangler"
)

var (
	webDir                    = flag.String("web_dir", "", "directory from which to serve vtctld web interface resources")
	templateDir               = flag.String("templates", "", "directory containing templates")
	debug                     = flag.Bool("debug", false, "recompile templates for every request")
	schemaChangeDir           = flag.String("schema_change_dir", "", "directory contains schema changes for all keyspaces. Each keyspace has its own directory and schema changes are expected to live in '$KEYSPACE/input' dir. e.g. test_keyspace/input/*sql, each sql file represents a schema change")
	schemaChangeController    = flag.String("schema_change_controller", "", "schema change controller is responsible for finding schema changes and responsing schema change events")
	schemaChangeCheckInterval = flag.Int("schema_change_check_interval", 60, "this value decides how often we check schema change dir, in seconds")
	schemaChangeUser          = flag.String("schema_change_user", "", "The user who submits this schema change.")
)

func init() {
	servenv.RegisterDefaultFlags()
	servenv.InitServiceMapForBsonRpcService("vtctl")
}

func httpErrorf(w http.ResponseWriter, r *http.Request, format string, args ...interface{}) {
	errMsg := fmt.Sprintf(format, args...)
	log.Errorf("HTTP error on %v: %v, request: %#v", r.URL.Path, errMsg, r)
	http.Error(w, errMsg, http.StatusInternalServerError)
}

// DbTopologyResult encapsulates a topotools.Topology and the possible error
type DbTopologyResult struct {
	Topology *topotools.Topology
	Error    string
}

// IndexContent has the list of toplevel links
type IndexContent struct {
	// maps a name to a linked URL
	ToplevelLinks map[string]string
}

// used at runtime by plug-ins
var templateLoader *TemplateLoader
var actionRepo *ActionRepository
var indexContent = IndexContent{
	ToplevelLinks: map[string]string{},
}

var ts topo.Server

func main() {
	flag.Parse()
	servenv.Init()
	defer servenv.Close()
	templateLoader = NewTemplateLoader(*templateDir, *debug)

	ts = topo.GetServer()
	defer topo.CloseServers()

	actionRepo = NewActionRepository(ts)

	// keyspace actions
	actionRepo.RegisterKeyspaceAction("ValidateKeyspace",
		func(ctx context.Context, wr *wrangler.Wrangler, keyspace string, r *http.Request) (string, error) {
			return "", wr.ValidateKeyspace(ctx, keyspace, false)
		})

	actionRepo.RegisterKeyspaceAction("ValidateSchemaKeyspace",
		func(ctx context.Context, wr *wrangler.Wrangler, keyspace string, r *http.Request) (string, error) {
			return "", wr.ValidateSchemaKeyspace(ctx, keyspace, nil, false)
		})

	actionRepo.RegisterKeyspaceAction("ValidateVersionKeyspace",
		func(ctx context.Context, wr *wrangler.Wrangler, keyspace string, r *http.Request) (string, error) {
			return "", wr.ValidateVersionKeyspace(ctx, keyspace)
		})

	actionRepo.RegisterKeyspaceAction("ValidatePermissionsKeyspace",
		func(ctx context.Context, wr *wrangler.Wrangler, keyspace string, r *http.Request) (string, error) {
			return "", wr.ValidatePermissionsKeyspace(ctx, keyspace)
		})

	// shard actions
	actionRepo.RegisterShardAction("ValidateShard",
		func(ctx context.Context, wr *wrangler.Wrangler, keyspace, shard string, r *http.Request) (string, error) {
			return "", wr.ValidateShard(ctx, keyspace, shard, false)
		})

	actionRepo.RegisterShardAction("ValidateSchemaShard",
		func(ctx context.Context, wr *wrangler.Wrangler, keyspace, shard string, r *http.Request) (string, error) {
			return "", wr.ValidateSchemaShard(ctx, keyspace, shard, nil, false)
		})

	actionRepo.RegisterShardAction("ValidateVersionShard",
		func(ctx context.Context, wr *wrangler.Wrangler, keyspace, shard string, r *http.Request) (string, error) {
			return "", wr.ValidateVersionShard(ctx, keyspace, shard)
		})

	actionRepo.RegisterShardAction("ValidatePermissionsShard",
		func(ctx context.Context, wr *wrangler.Wrangler, keyspace, shard string, r *http.Request) (string, error) {
			return "", wr.ValidatePermissionsShard(ctx, keyspace, shard)
		})

	// tablet actions
	actionRepo.RegisterTabletAction("Ping", "",
		func(ctx context.Context, wr *wrangler.Wrangler, tabletAlias topo.TabletAlias, r *http.Request) (string, error) {
			ti, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
			if err != nil {
				return "", err
			}
			return "", wr.TabletManagerClient().Ping(ctx, ti)
		})

	actionRepo.RegisterTabletAction("RefreshState", acl.ADMIN,
		func(ctx context.Context, wr *wrangler.Wrangler, tabletAlias topo.TabletAlias, r *http.Request) (string, error) {
			ti, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
			if err != nil {
				return "", err
			}
			return "", wr.TabletManagerClient().RefreshState(ctx, ti)
		})

	actionRepo.RegisterTabletAction("ScrapTablet", acl.ADMIN,
		func(ctx context.Context, wr *wrangler.Wrangler, tabletAlias topo.TabletAlias, r *http.Request) (string, error) {
			// refuse to scrap tablets that are not spare
			ti, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
			if err != nil {
				return "", err
			}
			if ti.Type != topo.TYPE_SPARE {
				return "", fmt.Errorf("Can only scrap spare tablets")
			}
			return "", wr.Scrap(ctx, tabletAlias, false, false)
		})

	actionRepo.RegisterTabletAction("ScrapTabletForce", acl.ADMIN,
		func(ctx context.Context, wr *wrangler.Wrangler, tabletAlias topo.TabletAlias, r *http.Request) (string, error) {
			// refuse to scrap tablets that are not spare
			ti, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
			if err != nil {
				return "", err
			}
			if ti.Type != topo.TYPE_SPARE {
				return "", fmt.Errorf("Can only scrap spare tablets")
			}
			return "", wr.Scrap(ctx, tabletAlias, true, false)
		})

	actionRepo.RegisterTabletAction("DeleteTablet", acl.ADMIN,
		func(ctx context.Context, wr *wrangler.Wrangler, tabletAlias topo.TabletAlias, r *http.Request) (string, error) {
			return "", wr.DeleteTablet(ctx, tabletAlias)
		})

	actionRepo.RegisterTabletAction("ReloadSchema", acl.ADMIN,
		func(ctx context.Context, wr *wrangler.Wrangler, tabletAlias topo.TabletAlias, r *http.Request) (string, error) {
			return "", wr.ReloadSchema(ctx, tabletAlias)
		})

	// keyspace actions
	http.HandleFunc("/keyspace_actions", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}
		action := r.FormValue("action")
		if action == "" {
			http.Error(w, "no action provided", http.StatusBadRequest)
			return
		}

		keyspace := r.FormValue("keyspace")
		if keyspace == "" {
			http.Error(w, "no keyspace provided", http.StatusBadRequest)
			return
		}
		ctx := context.Background()
		result := actionRepo.ApplyKeyspaceAction(ctx, action, keyspace, r)

		templateLoader.ServeTemplate("action.html", result, w, r)
	})

	// shard actions
	http.HandleFunc("/shard_actions", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}
		action := r.FormValue("action")
		if action == "" {
			http.Error(w, "no action provided", http.StatusBadRequest)
			return
		}

		keyspace := r.FormValue("keyspace")
		if keyspace == "" {
			http.Error(w, "no keyspace provided", http.StatusBadRequest)
			return
		}
		shard := r.FormValue("shard")
		if shard == "" {
			http.Error(w, "no shard provided", http.StatusBadRequest)
			return
		}
		ctx := context.Background()
		result := actionRepo.ApplyShardAction(ctx, action, keyspace, shard, r)

		templateLoader.ServeTemplate("action.html", result, w, r)
	})

	// tablet actions
	http.HandleFunc("/tablet_actions", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}
		action := r.FormValue("action")
		if action == "" {
			http.Error(w, "no action provided", http.StatusBadRequest)
			return
		}

		alias := r.FormValue("alias")
		if alias == "" {
			http.Error(w, "no alias provided", http.StatusBadRequest)
			return
		}
		tabletAlias, err := topo.ParseTabletAliasString(alias)
		if err != nil {
			http.Error(w, "bad alias provided", http.StatusBadRequest)
			return
		}
		ctx := context.Background()
		result := actionRepo.ApplyTabletAction(ctx, action, tabletAlias, r)

		templateLoader.ServeTemplate("action.html", result, w, r)
	})

	// topology server
	http.HandleFunc("/dbtopo", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}
		result := DbTopologyResult{}
		ctx := context.TODO()
		topology, err := topotools.DbTopology(ctx, ts)
		if err == nil && modifyDbTopology != nil {
			err = modifyDbTopology(ctx, ts, topology)
		}
		if err != nil {
			result.Error = err.Error()
		} else {
			result.Topology = topology
		}
		templateLoader.ServeTemplate("dbtopo.html", result, w, r)
	})

	// serving graph
	http.HandleFunc("/serving_graph/", func(w http.ResponseWriter, r *http.Request) {
		ctx := context.Background()
		parts := strings.Split(r.URL.Path, "/")

		cell := parts[len(parts)-1]
		if cell == "" {
			cells, err := ts.GetKnownCells(ctx)
			if err != nil {
				httpErrorf(w, r, "cannot get known cells: %v", err)
				return
			}
			templateLoader.ServeTemplate("serving_graph_cells.html", cells, w, r)
			return
		}

		servingGraph := topotools.DbServingGraph(ctx, ts, cell)
		if modifyDbServingGraph != nil {
			modifyDbServingGraph(ctx, ts, servingGraph)
		}
		templateLoader.ServeTemplate("serving_graph.html", servingGraph, w, r)
	})

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		templateLoader.ServeTemplate("index.html", indexContent, w, r)
	})

	http.HandleFunc("/content/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, *templateDir+r.URL.Path[8:])
	})

	// Serve the static files for the vtctld web app.
	if *webDir != "" {
		http.HandleFunc("/app/", func(w http.ResponseWriter, r *http.Request) {
			// Strip the prefix.
			parts := strings.SplitN(r.URL.Path, "/", 3)
			if len(parts) != 3 {
				http.NotFound(w, r)
				return
			}
			rest := parts[2]
			if rest == "" {
				rest = "index.html"
			}
			http.ServeFile(w, r, path.Join(*webDir, rest))
		})
	}

	// Serve the REST API for the vtctld web app.
	initAPI(context.Background(), ts, actionRepo)

	// vschema viewer
	http.HandleFunc("/vschema", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}
		schemafier, ok := ts.(topo.Schemafier)
		if !ok {
			httpErrorf(w, r, "%s", fmt.Errorf("%T doesn't support schemafier API", ts))
		}
		var data struct {
			Error         error
			Input, Output string
		}
		ctx := context.Background()
		switch r.Method {
		case "POST":
			data.Input = r.FormValue("vschema")
			data.Error = schemafier.SaveVSchema(ctx, data.Input)
		}
		vschema, err := schemafier.GetVSchema(ctx)
		if err != nil {
			if data.Error == nil {
				data.Error = fmt.Errorf("Error fetching schema: %s", err)
			}
		}
		data.Output = vschema
		templateLoader.ServeTemplate("vschema.html", data, w, r)
	})

	// redirects for explorers
	http.HandleFunc("/explorers/redirect", func(w http.ResponseWriter, r *http.Request) {
		if explorer == nil {
			http.Error(w, "no explorer configured", http.StatusInternalServerError)
			return
		}
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}

		target, err := handleExplorerRedirect(r)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		http.Redirect(w, r, target, http.StatusFound)
	})

	// serve some data
	knownCellsCache := newKnownCellsCache(ts)
	http.HandleFunc("/json/KnownCells", func(w http.ResponseWriter, r *http.Request) {
		ctx := context.Background()
		result, err := knownCellsCache.Get(ctx)
		if err != nil {
			httpErrorf(w, r, "error getting known cells: %v", err)
			return
		}
		w.Write(result)
	})

	keyspacesCache := newKeyspacesCache(ts)
	http.HandleFunc("/json/Keyspaces", func(w http.ResponseWriter, r *http.Request) {
		ctx := context.Background()
		result, err := keyspacesCache.Get(ctx)
		if err != nil {
			httpErrorf(w, r, "error getting keyspaces: %v", err)
			return
		}
		w.Write(result)
	})

	keyspaceCache := newKeyspaceCache(ts)
	http.HandleFunc("/json/Keyspace", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}
		keyspace := r.FormValue("keyspace")
		if keyspace == "" {
			http.Error(w, "no keyspace provided", http.StatusBadRequest)
			return
		}
		ctx := context.Background()
		result, err := keyspaceCache.Get(ctx, keyspace)
		if err != nil {
			httpErrorf(w, r, "error getting keyspace: %v", err)
			return
		}
		w.Write(result)
	})

	shardNamesCache := newShardNamesCache(ts)
	http.HandleFunc("/json/ShardNames", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}
		keyspace := r.FormValue("keyspace")
		if keyspace == "" {
			http.Error(w, "no keyspace provided", http.StatusBadRequest)
			return
		}
		ctx := context.Background()
		result, err := shardNamesCache.Get(ctx, keyspace)
		if err != nil {
			httpErrorf(w, r, "error getting shardNames: %v", err)
			return
		}
		w.Write(result)
	})

	shardCache := newShardCache(ts)
	http.HandleFunc("/json/Shard", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}
		keyspace := r.FormValue("keyspace")
		if keyspace == "" {
			http.Error(w, "no keyspace provided", http.StatusBadRequest)
			return
		}
		shard := r.FormValue("shard")
		if shard == "" {
			http.Error(w, "no shard provided", http.StatusBadRequest)
			return
		}
		ctx := context.Background()
		result, err := shardCache.Get(ctx, keyspace+"/"+shard)
		if err != nil {
			httpErrorf(w, r, "error getting shard: %v", err)
			return
		}
		w.Write(result)
	})

	cellShardTabletsCache := newCellShardTabletsCache(ts)
	http.HandleFunc("/json/CellShardTablets", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}
		cell := r.FormValue("cell")
		if cell == "" {
			http.Error(w, "no cell provided", http.StatusBadRequest)
			return
		}
		keyspace := r.FormValue("keyspace")
		if keyspace == "" {
			http.Error(w, "no keyspace provided", http.StatusBadRequest)
			return
		}
		shard := r.FormValue("shard")
		if shard == "" {
			http.Error(w, "no shard provided", http.StatusBadRequest)
			return
		}
		ctx := context.Background()
		result, err := cellShardTabletsCache.Get(ctx, cell+"/"+keyspace+"/"+shard)
		if err != nil {
			httpErrorf(w, r, "error getting shard: %v", err)
			return
		}
		w.Write(result)
	})

	// flush all data and will force a full client reload
	http.HandleFunc("/json/flush", func(w http.ResponseWriter, r *http.Request) {
		knownCellsCache.Flush()
		keyspacesCache.Flush()
		keyspaceCache.Flush()
		shardNamesCache.Flush()
		shardCache.Flush()
		cellShardTabletsCache.Flush()
	})

	http.HandleFunc("/json/schema-manager", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			httpErrorf(w, r, "cannot parse form: %s", err)
			return
		}
		sqlStr := r.FormValue("data")
		keyspace := r.FormValue("keyspace")
		executor := schemamanager.NewTabletExecutor(
			tmclient.NewTabletManagerClient(),
			ts)

		ctx := context.Background()
		schemamanager.Run(
			ctx,
			schemamanager.NewUIController(sqlStr, keyspace, w),
			executor,
		)
	})
	if *schemaChangeDir != "" {
		interval := 60
		if *schemaChangeCheckInterval > 0 {
			interval = *schemaChangeCheckInterval
		}
		timer := timer.NewTimer(time.Duration(interval) * time.Second)
		controllerFactory, err :=
			schemamanager.GetControllerFactory(*schemaChangeController)
		if err != nil {
			log.Fatalf("unable to get a controller factory, error: %v", err)
		}

		timer.Start(func() {
			controller, err := controllerFactory(map[string]string{
				schemamanager.SchemaChangeDirName: *schemaChangeDir,
				schemamanager.SchemaChangeUser:    *schemaChangeUser,
			})
			if err != nil {
				log.Errorf("failed to get controller, error: %v", err)
				return
			}
			ctx := context.Background()
			err = schemamanager.Run(
				ctx,
				controller,
				schemamanager.NewTabletExecutor(
					tmclient.NewTabletManagerClient(), ts),
			)
			if err != nil {
				log.Errorf("Schema change failed, error: %v", err)
			}
		})
		servenv.OnClose(func() { timer.Stop() })
	}
	servenv.RunDefault()
}


text:
//=======================================================================
//
// SAMPLE SOURCE CODE - SUBJECT TO THE TERMS OF END-USER LICENSE AGREEMENT FOR
// INTEL(R) PARALLEL ADVISOR 2011.
//
// Copyright 2009-2010 Intel Corporation
//
// THIS FILE IS PROVIDED "AS IS" WITH NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE, NON-INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS.
//
// ========================================================================

// [DESCRIPTION]
// Solve the nqueens problem  - how many positions of queens can fit on a chess board
// of a given size without attacking each other.
// This is the serial version used to find a candidate hotspot function to parallelize.
//
// [BUILD]
// Use a Release configuration to ensure you find a hotspot representative of a final production build.
//
// [RUN]
// To set the board size in Visual Studio, right click on the project,
// select Properies > Configuration Properties > General > Debugging.  Set
// Command Arguments to the desired value.  13 has been set as the default.
//
// [EXPECTED OUTPUT]
//
// Board Size   Number of Solutions
//     4                2
//     5               10
//     6                4
//     7               40
//     8               92
//     9              352
//    10              724
//    11             2680
//    12            14200
//    13            73712
//    14           365596
//    15          2279184

#include <iostream>
#include <windows.h>
#include <mmsystem.h>
#include "tbb/task_scheduler_init.h"
#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
#include "tbb/spin_mutex.h"

using namespace tbb;
using namespace std;

int nrOfSolutions=0;  //keeps track of the number of solutions
int size=0;  // the board-size read from command-line
int correctSolution[16]; //array of the number of correct solutions for each board size

// define tbb mutexes
spin_mutex NrOfSolutionsMutex;

/*
Recursive function to find all solutions on a board
represented by the argument "queens", placing the next queen
at location (row, col)

On Return: nrOfSolutions has been increased to add solutions for this board

*/
void setQueen(int queens[], int row, int col) {
    //check all previously placed rows for attacks
    for(int i=0; i<row; i++) {
        // vertical attacks
        if (queens[i]==col) {
            return;
        }
        // diagonal attacks
        if (abs(queens[i]-col) == (row-i)) {
            return;
        }
    }
    // column is ok, set the queen
    queens[row]=col;

    if(row==size-1) {
        {
            // increment is not atomic, so setting a lock is required here
            spin_mutex::scoped_lock mylock(NrOfSolutionsMutex);
            nrOfSolutions++;  //Placed final queen, found a solution!
        } // closing block invokes scoped_lock destructor which releases the lock

    }
    else {
        // try to fill next row
        for(int i=0; i<size; i++) {
            setQueen(queens, row+1, i);
        }
    }
}

class SetQueens {
public:
    void operator()( const blocked_range<size_t>& r ) const {
        for( size_t i=r.begin(); i!=r.end(); ++i ) {
            // try all positions in first row
            // create separate array for each recursion
            // started here
            int* queens = new int[size];
            setQueen(queens, 0, (int)i);
        }
    }
};

/*
Function to find all solutions for nQueens problem on size x size chessboard.

On Return: nrOfSoultions = number of solutions for size x size chessboard.
*/

void solve() {
    // Do a parallel for over the n positions in the first row.
    // Let the scheduler decide how the n tasks are distrubuted
    // on the different threads
    parallel_for(blocked_range<size_t>(0, size, 1), SetQueens());
}

int main(int argc, char* argv[]) {
    if(argc !=2) {
        cerr << "Usage: nqueens_tbb boardSize [default is 13].\n";
        size = 13;
    } else {
        size = atoi(argv[1]);
        if (size < 4 || size > 15) {
            cerr << "Boardsize should be between 4 and 15; setting it to 13. \n" << endl;
            size = 13;
        }
    }
    // Set the expected number of solutions for each board-size for later checking.
    correctSolution[0] = 0;
    correctSolution[1] = 0;
    correctSolution[2] = 0;
    correctSolution[3] = 0;
    correctSolution[4] = 2;
    correctSolution[5] = 10;
    correctSolution[6] = 4;
    correctSolution[7] = 40;
    correctSolution[8] = 92;
    correctSolution[9] = 352;
    correctSolution[10] = 724;
    correctSolution[11] = 2680;
    correctSolution[12] = 14200;
    correctSolution[13] = 73712;
    correctSolution[14] = 365596;
    correctSolution[15] = 2279184;

    cout << "Starting 3_nqueens_tbb solver for size " << size << "...\n";
    DWORD startTime=timeGetTime();
    // initialize tbb scheduler
    task_scheduler_init init;
    solve();
    DWORD endTime=timeGetTime();
    cout << "Number of solutions: " << nrOfSolutions << endl;
    if (nrOfSolutions != correctSolution[size])
        cout << "!!Incorrect result!! Number of solutions should be " << correctSolution[size] << endl << endl;
    else
        cout << "Correct result!" << endl;

    cout << endl << "Calculations took " << endTime-startTime << "ms.\n";

    return 0;
}


text:
package handler

import (
	"github.com/evolsnow/httprouter"
	"github.com/evolsnow/samaritan/common/base"
	"github.com/evolsnow/samaritan/common/dbms"
	"github.com/evolsnow/samaritan/common/log"
	"github.com/evolsnow/samaritan/model"
	"net/http"
)

const (
	LengthErr  = "长度应为4-8位"
	CharsetErr = "仅支持a-z, A-Z, 0-9 以及 _"
	ExistErr   = "已经被注册"

	UnknownTypeErr = "未知类型"

	ProjectNotExistErr  = "项目不存在"
	MissionNotExistErr  = "任务不存在"
	TodoNotExistErr     = "Todo不存在"
	ChatNotExistErr     = "消息不存在"
	NotProjectMemberErr = "不是本项目成员,无法查看项目"
)

// SamIdStatus tests whether a sam id is available
func SamIdStatus(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	samId := ps.Get("samId")
	resp := new(samIdStatusResp)
	if len(samId) > 8 || len(samId) < 4 {
		resp.Code = 1
		resp.Msg = LengthErr
		log.DebugJson(resp)
		makeResp(w, r, resp)
		return
	}
	if !base.ValidSamId(samId) {
		resp.Code = 2
		resp.Msg = CharsetErr
		log.DebugJson(resp)
		makeResp(w, r, resp)
		return
	}
	if dbms.ReadIfSamIdExist(samId) {
		resp.Code = 3
		resp.Msg = ExistErr
		log.DebugJson(resp)
		makeResp(w, r, resp)
		return
	}
	log.DebugJson(resp)
	makeResp(w, r, resp)
}

// UserProjectList return projects a user joined/created
func UserProjectList(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	uid := ps.GetInt("authId")
	pjType := r.URL.Query().Get("type")
	us := &model.User{Id: uid}
	resp := new(userProjectsResp)
	var pjs []model.Project
	switch pjType {
	case "joined":
		pjs = us.GetJoinedProjects()
	case "created":
		pjs = us.GetCreatedProjects()
	case "":
		pjs = us.GetAllProjects()
	default:
		base.BadReqErr(w, UnknownTypeErr)
		return
	}
	nps := make([]NestedProject, len(pjs))
	var createdOrJoined string
	for i, p := range pjs {
		if p.CreatorId == uid {
			createdOrJoined = "created"
		} else {
			createdOrJoined = "joined"
		}
		np := NestedProject{
			Id:           p.Pid,
			Name:         p.Name,
			Desc:         p.Desc,
			CreatorId:    base.HashedUserId(p.CreatorId),
			CreatorName:  p.GetCreator().Name,
			Private:      p.Private,
			Type:         createdOrJoined,
			MembersCount: len(p.GetMembersName()),
		}
		nps[i] = np
	}
	resp.Np = nps
	log.DebugJson(resp)
	makeResp(w, r, resp)
}

// SearchUser searches the user by mail
func SearchUser(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	userMail := ps.Get("user")
	uid := dbms.ReadUserIdWithIndex(userMail, "mail")
	if uid == 0 {
		base.NotFoundErr(w, UserNotExistErr)
		return
	}
	u := model.InitedUser(uid)
	resp := userSearchResp{
		Name:   u.Name,
		Id:     u.Pid,
		Avatar: u.Avatar,
	}
	log.DebugJson(resp)
	makeResp(w, r, resp)
}

// ProjectDetail returns a project detail information
func ProjectDetail(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	pid := dbms.ReadProjectId(ps.Get("project"))
	p := model.InitedProject(pid)
	if p == nil {
		base.NotFoundErr(w, ProjectNotExistErr)
		return
	}
	uid := ps.GetInt("authId")
	u := model.InitedUser(uid)
	if u == nil {
		base.NotFoundErr(w, UserNotExistErr)
		return
	}
	members := p.GetMembers()
	allMembers := make([]userModel, len(members))
	for i, mem := range members {
		allMembers[i] = userModel{
			Id:     base.HashedUserId(mem.Id),
			Name:   mem.Name,
			Avatar: mem.FullAvatarUrl(),
		}
	}
	resp := &projectDetailResp{
		Id:          ps.Get("project"),
		CreateTime:  p.CreateTime,
		Name:        p.Name,
		Desc:        p.Desc,
		CreatorId:   base.HashedUserId(p.CreatorId),
		CreatorName: p.GetCreator().Name,
		Private:     p.Private,
		Members:     allMembers,
	}
	log.DebugJson(resp)
	makeResp(w, r, resp)
}

// ProjectMissionList returns a project's all missions
func ProjectMissionList(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	pid := dbms.ReadProjectId(ps.Get("project"))
	resp := new(projectMissionsResp)
	p := model.InitedProject(pid)
	if p == nil {
		base.NotFoundErr(w, ProjectNotExistErr)
		return
	}
	owner := model.InitedUser(p.CreatorId)
	if owner == nil {
		base.NotFoundErr(w, UserNotExistErr)
		return
	}
	ms := p.GetMissions()
	uid := ps.GetInt("authId")
	u := model.InitedUser(uid)
	if u == nil {
		base.NotFoundErr(w, UserNotExistErr)
		return
	}
	userAcceptedMissions := u.GetAllAcceptedMissionsId()
	if !base.InIntSlice(uid, p.MembersId) {
		base.ForbidErr(w, NotProjectMemberErr)
		return
	}
	nms := make([]NestedMission, len(ms))
	for i, v := range ms {
		//if !base.InIntSlice(v.Id, userAcceptedMissions) {
		//	continue
		//}
		v.Sync()
		publisher := model.InitedUser(v.PublisherId)
		nm := NestedMission{
			Id:            v.Pid,
			Name:          v.Name,
			Desc:          v.Desc,
			Deadline:      v.Deadline,
			Pictures:      v.Pictures,
			Accepted:      base.InIntSlice(v.Id, userAcceptedMissions),
			ReceiversName: v.GetReceiversName(),
			CreatorName:   publisher.Name,
			CreatorId:     publisher.Pid,
			CreatorAvatar: publisher.Avatar,
			CreateTime:    v.CreateTime,
			CompletionNum: v.CompletionNum,
		}
		nms[i] = nm
	}
	resp.Nm = nms
	log.DebugJson(resp)
	makeResp(w, r, resp)
}

// MissionCommentList returns a mission's all comments
func MissionCommentList(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	mid := dbms.ReadProjectId(ps.Get("mission"))
	m := model.InitedMission(mid)
	if m == nil {
		base.NotFoundErr(w, MissionNotExistErr)
		return
	}
	cms := m.Comments
	resp := new(missionCommentResp)
	ncs := make([]NestedComment, len(cms))
	for i, v := range cms {
		nc := NestedComment{
			Id:         v.Pid,
			CreateTime: v.CreateTime,
			CriticPid:  v.CriticPid,
			CriticName: v.CriticName,
		}
		ncs[i] = nc
	}
	resp.Nm = ncs
	log.DebugJson(resp)
	makeResp(w, r, resp)
}

// MissionDetail returns a mission's detail information
func MissionDetail(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	mid := dbms.ReadMissionId(ps.Get("mission"))
	m := model.InitedMission(mid)
	if m == nil {
		base.NotFoundErr(w, MissionNotExistErr)
		return
	}
	uid := ps.GetInt("authId")
	u := model.InitedUser(uid)
	if u == nil {
		base.NotFoundErr(w, UserNotExistErr)
		return
	}
	userAcceptedMissions := u.GetAllAcceptedMissionsId()
	resp := &missionDetailResp{
		Id:            ps.Get("mission"),
		CreateTime:    m.CreateTime,
		Name:          m.Name,
		Desc:          m.Desc,
		Deadline:      m.Deadline,
		Accepted:      base.InIntSlice(m.Id, userAcceptedMissions),
		Pictures:      m.Pictures,
		PublisherId:   base.HashedUserId(m.PublisherId),
		ReceiversName: m.GetReceiversName(),
		CompletionNum: m.CompletionNum,
		CompletedTime: m.CompletedTime,
		ProjectId:     base.HashedProjectId(m.ProjectId),
	}
	log.DebugJson(resp)
	makeResp(w, r, resp)
}

// MakeUploadToken returns a qi niu upload token
func MakeUploadToken(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	resp := &QiNiuUpTokenResp{
		Token:  base.QiNiuUploadToken(),
		Expire: base.QiNiuExpire,
	}
	log.DebugJson(resp)
	makeResp(w, r, resp)
}

// OfflineMsgs returns user's all msgs
func OfflineMsgs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	uid := ps.GetInt("authId")
	u := model.InitedUser(uid)
	if u == nil {
		base.NotFoundErr(w, UserNotExistErr)
		return
	}
	resp := new(getOfflineMsgResp)
	msgs := u.GetAllOfflineMsg()
	nms := make([]NestedMsg, len(msgs))
	for i, v := range msgs {
		nc := NestedMsg{
			Id:        v.Pid,
			Time:      v.Timestamp,
			Msg:       v.Msg,
			Dealt:     v.Dealt,
			Type:      v.Type,
			ExtraInfo: v.ExtraInfo,
		}
		nms[i] = nc
	}
	resp.Msgs = nms
	log.DebugJson(resp)
	makeResp(w, r, resp)
}

// UserInfo returns user's detail information
func UserInfo(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	uid := ps.GetInt("authId")
	user := model.InitedUser(uid)
	if user == nil {
		base.NotFoundErr(w, UserNotExistErr)
		return
	}
	resp := &personalInfoResp{
		Id:     user.Pid,
		Avatar: user.Avatar,
		Name:   user.Name,
		Alias:  user.Alias,
		Mail:   user.Email,
		StuNum: user.StudentNum,
	}
	log.DebugJson(resp)
	makeResp(w, r, resp)
}


text:
var xmlrpc = require('xmlrpc');

var parts = ['Common', 'Auth'];

parts.forEach(function (k) {
  exports[k] = require('./services/' + k.toLowerCase())[k];
});

module.exports.createClient = function (options) {
  var client = {};

  var xmlrpcClient = xmlrpc.createClient({
      host: options.host,
      port: options.port || 80,
      path: '/'
    });

  client.xmlrpcClient = xmlrpcClient;
  client.auth = new exports['Auth'](xmlrpcClient, options);

  client.auth.login(function (err, userId) {
    if (err) {
      throw err;
    }
    options.userId = userId;

    parts.forEach(function (k) {
      client[k.toLowerCase()] = new exports[k](xmlrpcClient, options);
    });
  });

  return client;
};


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//Tigris//DTD XHTML 1.0 Transitional//EN"
"http://style.tigris.org/tigris_transitional.dtd">

<link rel="stylesheet" type="text/css" href="css/print.css" media="print" />
 <title>Interview Checklist</title>

User Needs >
Interview Notes > Interview Checklist

  Process impact:
  This checklist will help you plan customer interviews.

Pre-Interview Checklist

Decide what goals you want to accomplish

Prepare a list of questions

Ask about things you know you need to find out, based on
      your current understanding of the requirements

Keep questions simple.  Don't use multi-part questions,
      break complex topics into individual questions.

Confirm key assumptions.  E.g., "You are the one who
      actually would use this software, right?"  "The total needs to
      be displayed and updated as each item is scanned, right?"

Avoid leading or multiple-choice questions because the right
      answer might be one that you don't know about yet.  E.g., WRONG:
      "Would you log in to the system from your desk here or from
      home?"  RIGHT: "Where are some of the places you would be
      sitting when you log in?" "Here in my office, but also when I
      work with others sometimes I log in from their office or from a
      machine in the lab or conference room... so, I don't want a cookie
      saved there."

Try to find out the priority of each requirement: essential,
      expected, desired, or optional.

Write some more open-ended questions to see if new important
      requirements come up.

Don't ask too many questions that seem out of scope, you
      could accidentally change the scope or set incorrect expectations.
      E.g., "Would you like the system to also do ten other cool
      things?" "Sure!"

Select interviewees that represent all important stakeholders

Review your questions.  Do you think they can be answered?
    Will they help achieve your goals?  If not, go back and revise.

Decide whether you want to do this interview via email,
    telephone, or in person

Schedule an interview a time and place for the interviewee's
    convenience.  Plan on the interview lasting one hour.

Interview Checklist

Be prompt, courteous, and business-like

Introduce yourself and explain why you are there

Make sure that you are interviewing the person you think you
    are.  Get their contact information (e.g., email address) if you
    don't already have it.

Ask permission to take notes.  Don't record or video tape.

Confirm the amount of time you and the interviewee have for this session.

Give a quick indication of the type and number of questions that you have

Work through the questions.

Listen.  That is why you are there.

If the interviewee refers to existing documents, systems,
    equipment, or people, make sure that you understand what he or she
    is talking about.  If it is important, ask if you may have a copy
    or screenshot (but, don't ask for anything containing proprietary
    information), or make a note of the important aspects of the items
    referred to.  Note the URLs of any existing public websites
    discussed.

Try not to answer the questions yourself, or to react to
    interviewee requests by making promises to solve problems.
    Interviews are for understanding the problems, not solving
    them or setting schedules or deliverables.

Write down action items to follow up on finding more
    information.  E.g., if the interviewee starts explaining at length
    something that you know you can learn on your own, or if they don't
    know the answer and start speculating at length, you should try to
    move on the next question.

If you find that you have prepared the wrong questions, focus
    on getting information that will help you prepare the right
    follow-up questions.

Finish on time.  If you need more time, continue via email or
    another meeting.

Summarize action items that you will follow up on

Ask if the interviewee has any questions for you, or if there
    was something more that they wanted you to ask.

Make sure to leave contact information

Thank the interviewee for their time

Post-Interview Checklist

Within 24 hours, read your notes and fill in any important
    details that were said but not written down

Type up your notes so that they can be shared with the team
    and archived

Formulate any important follow-up questions

Within 2-3 days, send a follow-up email message to

Thank the interviewee again

Confirm that you have their correct email address, and make
      it easier for them to reply to you

Ask any important follow-up questions

Give status on your action items, if any.  E.g., "I searched
      Google for that product you mentioned and I couldn't find a
      users manual, but I did find a magazine review of it."  Or,
      "After I interviewed you, I spoke with Bob, and he confirmed
      that some current products do cost $0.00."

  TODO:  Check for words
  of wisdom and discuss ways to improve this template.
  Or, evaluate the ReadySET Pro professional interview checklist template.

Company Proprietary

 Copyright © 2003-2004 Jason Robbins.  All rights reserved. License terms.
 Retain this copyright statement whenever this file is used as a
 template.


text:
/**
 * @file msgpack-decode
 * @private
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

/**
 * msgpack decode module.
 * @module MsgpackDecode
 */

/**
 * decode binary encoded MessagePack v5 (http://msgpack.org/) data
 * @static
 * @param  {Uint8Array} buffer - binary encoded MessagePack data
 * @return {Object|Array|String|Number|Boolean|null} decoded Messagepack data
 */
function decodeMsgpack(buffer) {
  // Loosely based on
  // The MIT License (MIT)
  // Copyright (c) 2013 Tim Caswell <tim@creationix.com>
  // https://github.com/creationix/msgpack-js
  var offset = 0;
  var dataView = new DataView(buffer.buffer);

  /**
   * decode all key-value pairs of a map into an object
   * @param  {Integer} length - number of key-value pairs
   * @return {Object} decoded map
   */
  function map(length) {
    var value = {};
    for (var i = 0; i < length; i++) {
      var key = parse();
      value[key] = parse();
    }
    return value;
  }

  /**
   * decode binary array
   * @param  {Integer} length - number of elements in the array
   * @return {Uint8Array} decoded array
   */
  function bin(length) {
    var value = buffer.subarray(offset, offset + length);
    offset += length;
    return value;
  }

  /**
   * decode string
   * @param  {Integer} length - number string characters
   * @return {String} decoded string
   */
  function str(length) {
    var array = buffer.subarray(offset, offset + length);
    offset += length;
    // limit number of arguments to String.fromCharCode to something
    // browsers can handle, see http://stackoverflow.com/a/22747272
    var chunkSize = 0xffff;
    if(length > chunkSize){
      var c = [];
      for(var i = 0; i < array.length; i += chunkSize) {
        c.push(String.fromCharCode.apply(
          null, array.subarray(i, i + chunkSize)
        ));
      }
      return c.join("");
    }else{
      return String.fromCharCode.apply(null, array);
    }
  }

  /**
   * decode array
   * @param  {Integer} length - number of array elements
   * @return {Array} decoded array
   */
  function array(length) {
    var value = new Array(length);
    for (var i = 0; i < length; i++) {
      value[i] = parse();
    }
    return value;
  }

  /**
   * recursively parse the MessagePack data
   * @return {Object|Array|String|Number|Boolean|null} decoded MessagePack data
   */
  function parse() {
    var type = buffer[offset];
    var value, length, extType;
    // Positive FixInt
    if ((type & 0x80) === 0x00) {
      offset++;
      return type;
    }
    // FixMap
    if ((type & 0xf0) === 0x80) {
      length = type & 0x0f;
      offset++;
      return map(length);
    }
    // FixArray
    if ((type & 0xf0) === 0x90) {
      length = type & 0x0f;
      offset++;
      return array(length);
    }
    // FixStr
    if ((type & 0xe0) === 0xa0) {
      length = type & 0x1f;
      offset++;
      return str(length);
    }
    // Negative FixInt
    if ((type & 0xe0) === 0xe0) {
      value = dataView.getInt8(offset);
      offset++;
      return value;
    }
    switch (type) {
    // nil
    case 0xc0:
      offset++;
      return null;
    // 0xc1: (never used, could be employed for padding)
    // false
    case 0xc2:
      offset++;
      return false;
    // true
    case 0xc3:
      offset++;
      return true;
    // bin 8
    case 0xc4:
      length = dataView.getUint8(offset + 1);
      offset += 2;
      return bin(length);
    // bin 16
    case 0xc5:
      length = dataView.getUint16(offset + 1);
      offset += 3;
      return bin(length);
    // bin 32
    case 0xc6:
      length = dataView.getUint32(offset + 1);
      offset += 5;
      return bin(length);
    // // ext 8
    // case 0xc7:
    //   length = dataView.getUint8(offset + 1);
    //   extType = dataView.getUint8(offset + 2);
    //   offset += 3;
    //   return [extType, bin(length)];
    // // ext 16
    // case 0xc8:
    //   length = dataView.getUint16(offset + 1);
    //   extType = dataView.getUint8(offset + 3);
    //   offset += 4;
    //   return [extType, bin(length)];
    // // ext 32
    // case 0xc9:
    //   length = dataView.getUint32(offset + 1);
    //   extType = dataView.getUint8(offset + 5);
    //   offset += 6;
    //   return [extType, bin(length)];
    // float 32
    case 0xca:
      value = dataView.getFloat32(offset + 1);
      offset += 5;
      return value;
    // float 64
    case 0xcb:
      value = dataView.getFloat64(offset + 1);
      offset += 9;
      return value;
    // uint8
    case 0xcc:
      value = buffer[offset + 1];
      offset += 2;
      return value;
    // uint 16
    case 0xcd:
      value = dataView.getUint16(offset + 1);
      offset += 3;
      return value;
    // uint 32
    case 0xce:
      value = dataView.getUint32(offset + 1);
      offset += 5;
      return value;
    // // uint64
    // case 0xcf:
    //   // FIXME not available/representable in JS
    //   // largest possible int in JS is 2^53
    //   // value = dataView.getUint64(offset + 1);
    //   offset += 9;
    //   return 0;
    // int 8
    case 0xd0:
      value = dataView.getInt8(offset + 1);
      offset += 2;
      return value;
    // int 16
    case 0xd1:
      value = dataView.getInt16(offset + 1);
      offset += 3;
      return value;
    // int 32
    case 0xd2:
      value = dataView.getInt32(offset + 1);
      offset += 5;
      return value;
    // // int 64
    // case 0xd3:
    //   // FIXME not available/representable in JS
    //   // largest possible int in JS is 2^53
    //   // value = dataView.getInt64(offset + 1);
    //   offset += 9;
    //   return 0;

    // // fixext 1
    // case 0xd4:
    //   extType = dataView.getUint8(offset + 1);
    //   offset += 2;
    //   return [extType, bin(1)];
    // // fixext 2
    // case 0xd5:
    //   extType = dataView.getUint8(offset + 1);
    //   offset += 2;
    //   return [extType, bin(2)];
    // // fixext 4
    // case 0xd6:
    //   extType = dataView.getUint8(offset + 1);
    //   offset += 2;
    //   return [extType, bin(4)];
    // // fixext 8
    // case 0xd7:
    //   extType = dataView.getUint8(offset + 1);
    //   offset += 2;
    //   return [extType, bin(8)];
    // // fixext 16
    // case 0xd8:
    //   extType = dataView.getUint8(offset + 1);
    //   offset += 2;
    //   return [extType, bin(16)];
    // str 8
    case 0xd9:
      length = dataView.getUint8(offset + 1);
      offset += 2;
      return str(length);
    // str 16
    case 0xda:
      length = dataView.getUint16(offset + 1);
      offset += 3;
      return str(length);
    // str 32
    case 0xdb:
      length = dataView.getUint32(offset + 1);
      offset += 5;
      return str(length);
    // array 16
    case 0xdc:
      length = dataView.getUint16(offset + 1);
      offset += 3;
      return array(length);
    // array 32
    case 0xdd:
      length = dataView.getUint32(offset + 1);
      offset += 5;
      return array(length);
    // map 16:
    case 0xde:
      length = dataView.getUint16(offset + 1);
      offset += 3;
      return map(length);
    // map 32
    case 0xdf:
      length = dataView.getUint32(offset + 1);
      offset += 5;
      return map(length);
    }

    throw new Error("Unknown type 0x" + type.toString(16));
  }

  // start the recursive parsing
  return parse();
}

export default decodeMsgpack;


text:
package com.baidu.disconf.web.tools;

import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LDAPUtil {

    private static final Log logger = LogFactory.getLog(LDAPUtil.class);

    private enum USER_TYPE {BEST_BG,BEST_BL, HT}

    private enum LDAP_TYPE {BEST, HT}

    public static final String INITIAL_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";

    public static final String SECURITY_AUTHENTICATION = "simple";

    public static final String SEARCH_FILTER = "(&(objectClass=user)(sAMAccountName=*))";

    //BEST
    public static final String PROVIDER_URL_BEST = "ldap://800best.net:389";

    public static final String SEARCH_BASE_BEST = "DC=800best,DC=net";

    public static final String USER_DN_BEST = "sm";

    public static final String PASSWORD_BEST = "sm800best";

    public static final String DOMAIN_BEST = "800best";

    //HT
    public static final String PROVIDER_URL_HT = "ldap://hzhtdc1.ht.800best.net:389";

    public static final String SEARCH_BASE_HT = "DC=ht,DC=800best,DC=net";

    public static final String USER_DN_HT = "htjs";

    public static final String PASSWORD_HT = "ht1234js";

    public static final String DOMAIN_HT = "ht.800best.net";

    /**
     * 用户域验证
     *
     * @param userName
     * @param passwd
     * @return
     */
    public static boolean validateByLdap(String userName, String passwd) {
        if (StringUtils.isBlank(passwd)) {
            return false;
        }
        LdapContext ctx = null;
        if(getUserType(userName) == USER_TYPE.HT) {
             ctx = initLdap(userName, passwd, LDAP_TYPE.HT);
        }
        if(getUserType(userName) == USER_TYPE.BEST_BL) {
             ctx = initLdap(userName, passwd, LDAP_TYPE.BEST);
        }
        if(getUserType(userName) == USER_TYPE.BEST_BG) {
             ctx = initLdap(userName, passwd, LDAP_TYPE.BEST);
            if(ctx == null) {
                ctx = initLdap(userName, passwd, LDAP_TYPE.HT);
            }
        }
        return ctx != null;
    }

    /**
     * 检查域用户是否存在
     *
     * @param userName
     * @return
     */
    public static boolean searchByLdap(String userName) {
        if (StringUtils.isBlank(userName)) {
            return false;
        }
        if (getUserType(userName) == USER_TYPE.HT) {
            return searchLdap(userName, LDAP_TYPE.HT);
        }
        if (getUserType(userName) == USER_TYPE.BEST_BL) {
            return searchLdap(userName, LDAP_TYPE.BEST);
        }
        if (getUserType(userName) == USER_TYPE.BEST_BG) {
            if (!searchLdap(userName, LDAP_TYPE.BEST)) {
                return searchLdap(userName, LDAP_TYPE.HT);
            }
            return true;
        }
        return false;
    }

    private static boolean searchLdap(String userName, LDAP_TYPE ldapType) {
        LdapContext ctx = initLdap(getUserDn(ldapType), getPassword(ldapType), ldapType);
        if (ctx != null) {
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            try {
                NamingEnumeration<SearchResult> results = ctx
                        .search(getSearchBase(ldapType), SEARCH_FILTER.replace("*", userName),
                                searchControls);
                if (results.hasMoreElements()) {
                    results.nextElement();
                    if (!results.hasMoreElements()) {
                        return true;
                    }
                }
            } catch (Exception e) {
                logger.info(e);
            }
        }
        return false;
    }

    private static LdapContext initLdap(String userName, String passwd, LDAP_TYPE ldapType) {
        String domain = getDomain(ldapType);
        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
        env.put(Context.PROVIDER_URL, getProviderUrl(ldapType));
        env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
        env.put(Context.SECURITY_PRINCIPAL, userName + "@" + domain);
        env.put(Context.SECURITY_CREDENTIALS, passwd);
        try {
            return new InitialLdapContext(env, null);
        } catch (Exception e) {
            logger.info(e);
            return null;
        }
    }

    /**
     * 根据用户名选择员工类型
     *
     * @param userName
     * @return
     */
    public static USER_TYPE getUserType(String userName) {
        if (StringUtils.containsIgnoreCase(userName, "H")) {
            // 百世快递员工
            return USER_TYPE.HT;
        }
        if(StringUtils.containsIgnoreCase(userName, "BG")) {
            return USER_TYPE.BEST_BG;
        }
        else {
            // best员工
            return USER_TYPE.BEST_BL;
        }
    }

    private static String getDomain(LDAP_TYPE ldapType) {
        return ldapType == LDAP_TYPE.HT ? DOMAIN_HT : DOMAIN_BEST;
    }

    private static String getUserDn(LDAP_TYPE ldapType) {
        return ldapType == LDAP_TYPE.HT ? USER_DN_HT : USER_DN_BEST;
    }

    private static String getPassword(LDAP_TYPE ldapType) {
        return ldapType == LDAP_TYPE.HT ? PASSWORD_HT : PASSWORD_BEST;
    }

    private static String getProviderUrl(LDAP_TYPE ldapType) {
        return ldapType == LDAP_TYPE.HT ? PROVIDER_URL_HT : PROVIDER_URL_BEST;
    }

    private static String getSearchBase(LDAP_TYPE ldapType) {
        return ldapType == LDAP_TYPE.HT ? SEARCH_BASE_HT : SEARCH_BASE_BEST;
    }

}


text:
struct AP_API ap2DRectangle : public osTransferableObject
{
public:
    ap2DRectangle();
    ap2DRectangle(const ap2DRectangle& other);
    ap2DRectangle(float xPos, float yPos, float width, float height);
    ap2DRectangle(const float* rectangleAsFloatArray);
    ap2DRectangle& operator=(const ap2DRectangle& other);

    // Overrides osTransferableObject:
    virtual osTransferableObjectType type() const;
    virtual bool writeSelfIntoChannel(osChannel& ipcChannel) const;
    virtual bool readSelfFromChannel(osChannel& ipcChannel);

public:
    // The rectangle position and size:
    float _xPos;
    float _yPos;
    float _width;
    float _height;
};

#endif //__AP2DRECTANGLE_H


text:
'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
  controller('AppCtrl', function ($scope, socket, serverState) {
    $scope.name = serverState.roomName;

    $scope.currentFile = "no file";
    $scope.files = [];
    $scope.bodyStore = {};//muahahahaha
    $scope.messages = [];
    $scope.users = [];
    $scope.readOnly = true;
    $scope.warning = "";

    $scope.newMessage = "";
    $scope.newUserId = "";
    $scope.newChange = null;

    socket.emit('joinRoom', {room: serverState.roomName});

    //***************************
    //***** Socket recievers ****
    //***************************

    //server --> client (notification that the active file has changed, data comes later)
    socket.on('changeCurrentFile', function (file, mimeType) {
      if(file!='no file'){
        if(!$scope.bodyStore[file])
          $scope.bodyStore[file] = {fileName: file, body:"", isDirty:false};

        $scope.currentFile = file;
        $scope.editorOptions.mode = mimeType;
      }
    });

    socket.on('closeFile', function (file) {
      if($scope.bodyStore[file])
        delete $scope.bodyStore[file];
    });

    socket.on('roomReadOnly', function (readOnly) {
      $scope.readOnly = readOnly;
    });

    socket.on('roomAuthMap', function (authMap) {
      $scope.authMap = authMap;
    });

    socket.on('fileAdded', function(file) {
      $scope.files.push(file);
    });

    socket.on('fileDeleted', function(file){
      $scope.files.splice($scope.files.indexOf(file), 1);
    });

    socket.on('fileChanged', function(file){
      //TODO - maybe do something with times... mebe push the last updated time from host and use on UI to 'red' the recently altered.. or order.. not sure
    });

    //server --> client (server sends fresh data for active file)
    socket.on('refreshData', function (body) {
      $scope.bodyStore[$scope.currentFile].body = body;
      $scope.bodyStore[$scope.currentFile].isDirty = false;
    });

    socket.on('syncOpenFile', function (openFile) {
      $scope.bodyStore[openFile.fileName] = openFile;
    });

    socket.on('saveCurrentFile', function (data) {
      $scope.bodyStore[data.file].body = data.body; //if all has gone well, this should do nothing, but it is a point of synchronisation
      $scope.bodyStore[data.file].isDirty = false;
    });

    //server --> client (recieve an incremental operation from the active editor via the server)
    socket.on('changeData', function (data) {
      $scope.bodyStore[$scope.currentFile].isDirty = true;
      $scope.newChange = data;
    });

    socket.on('resetHostData', function(){
      $scope.currentFile = "no file";
      $scope.files = [];
      $scope.bodyStore = {};
      $scope.warning = "";
    });

    socket.on('newChatMessage', function (message, userId) {
      $scope.messages.push({message:message, userId:userId, date:new Date()});
    });

    socket.on('newUser', function(data){
      $scope.users.push(data);
      if(data.isYou==true){
        $scope.currentUser = data;
        checkCurrentUserReadOnly();
      }
    });

    socket.on('exitingUser', function(userId){
      var user = findUser(userId);
      $scope.users.splice($scope.users.indexOf(user), 1);
    });

    socket.on('userIdChanged', function(oldUserId, newUserId){
      var user = findUser(oldUserId);
      if(user)
        user.userId = newUserId;
    });

    socket.on('userRoleChanged', function(userId, newRole){
      var user = findUser(userId);
      if(user){
        user.role = newRole;
        if(user.isYou)
          checkCurrentUserReadOnly();
      }
    });

    socket.on('requestedRole', function(userId, newRole){
      var user = findUser(userId);
      if(user){
        user.requestedRole = newRole;
      }
    });

    var findUser = function(userId){
      var foundUser = null;
      $scope.users.forEach(function(user){
        if(user.userId===userId){
          foundUser = user;
        }
      });
      return foundUser;
    };

    //***************************
    //**** make stuff happen ****
    //***************************

    $scope.requestChangeCurrentFile = function(file){
      socket.emit('changeCurrentFile', file);
    };

    $scope.requestCloseFile = function(file){
      socket.emit('closeFile', file)
    };

    $scope.requestSaveCurrentFile = function(){
      socket.emit('saveCurrentFile');
    };

    $scope.requestReloadCurrentFile = function(){
      socket.emit('reloadCurrentFile');
    };

    $scope.newChatMessage = function(){
      socket.emit('newChatMessage', $scope.newMessage);
      $scope.newMessage = "";
    };

    $scope.changeUserId = function(){
      socket.emit('changeUserId', $scope.newUserId);
      $scope.newUserId = "";
    };

    $scope.grantChangeRole = function(userId, newRole){
      socket.emit('grantChangeRole', {userId:userId, newRole:newRole});
    };

    $scope.grantRequestedRole = function(userId){
      var user = findUser(userId);
      if(user && user.requestedRole && user.requestedRole!=""){
        socket.emit('grantChangeRole', {userId:userId, newRole:user.requestedRole});
      }
    };

    $scope.requestChangeRole = function(userId, newRole, pass){
      socket.emit('requestChangeRole', {userId:userId, newRole:newRole, pass:pass});
    };

    var checkCurrentUserReadOnly = function(){
      if($scope.currentUser){
        $scope.editorOptions.readOnly = ($scope.readOnly || !$scope.authMap[$scope.currentUser.role].editData===true);
      }else{
        $scope.editorOptions.readOnly = true;
      }
    };

    //***************************
    //**set up the code editor***
    //***************************

    $scope.onEditorChange = function(i, op){
      if(op.origin && op.origin!=='setValue'){
        if($scope.readOnly){
          $scope.warning = "Your changes will not be shared";
        }else{
          console.log('editor change:' + op);
          socket.emit('changeData', op);
          socket.emit('refreshData', $scope.bodyStore[$scope.currentFile].body, false);//refresh data on server but don't broadcast
          $scope.bodyStore[$scope.currentFile].isDirty = true;
        }
      }
    };

    $scope.editorOptions = {
        lineWrapping : true,
        lineNumbers: true,
        matchBrackets: true,
        readOnly: true,
        mode: '',
        onChange: $scope.onEditorChange
    };
  });


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.kaazing</groupId>
        <artifactId>gateway</artifactId>
        <version>develop-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <artifactId>gateway.resource.address.httpx</artifactId>
    <name>Httpx Resource Address</name>
    <description>Resource Address for httpx endpoint</description>

    <url>https://github.com/kaazing/gateway.resource.address.httpx.git</url>
    <scm>
        <connection>scm:git:${project.scm.url}</connection>
        <developerConnection>scm:git:${project.scm.url}</developerConnection>
        <url>git@github.com:kaazing/gateway.resource.address.httpx.git</url>
    </scm>

    <dependencies>
        <dependency>
            <groupId>org.kaazing</groupId>
            <artifactId>gateway.resource.address.http</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>

</project>