text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    public partial class NetworkSecurityGroup : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Id))
            {
                writer.WritePropertyName("id");
                writer.WriteStringValue(Id);
            }
            if (Optional.IsDefined(Location))
            {
                writer.WritePropertyName("location");
                writer.WriteStringValue(Location);
            }
            if (Optional.IsCollectionDefined(Tags))
            {
                writer.WritePropertyName("tags");
                writer.WriteStartObject();
                foreach (var item in Tags)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteStringValue(item.Value);
                }
                writer.WriteEndObject();
            }
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsCollectionDefined(SecurityRules))
            {
                writer.WritePropertyName("securityRules");
                writer.WriteStartArray();
                foreach (var item in SecurityRules)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static NetworkSecurityGroup DeserializeNetworkSecurityGroup(JsonElement element)
        {
            Optional<string> etag = default;
            Optional<string> id = default;
            Optional<string> name = default;
            Optional<string> type = default;
            Optional<string> location = default;
            Optional<IDictionary<string, string>> tags = default;
            Optional<IList<SecurityRule>> securityRules = default;
            Optional<IReadOnlyList<SecurityRule>> defaultSecurityRules = default;
            Optional<IReadOnlyList<NetworkInterface>> networkInterfaces = default;
            Optional<IReadOnlyList<Subnet>> subnets = default;
            Optional<IReadOnlyList<FlowLog>> flowLogs = default;
            Optional<string> resourceGuid = default;
            Optional<ProvisioningState> provisioningState = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("etag"))
                {
                    etag = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary<string, string> dictionary = new Dictionary<string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("securityRules"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<SecurityRule> array = new List<SecurityRule>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(SecurityRule.DeserializeSecurityRule(item));
                            }
                            securityRules = array;
                            continue;
                        }
                        if (property0.NameEquals("defaultSecurityRules"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<SecurityRule> array = new List<SecurityRule>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(SecurityRule.DeserializeSecurityRule(item));
                            }
                            defaultSecurityRules = array;
                            continue;
                        }
                        if (property0.NameEquals("networkInterfaces"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<NetworkInterface> array = new List<NetworkInterface>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(NetworkInterface.DeserializeNetworkInterface(item));
                            }
                            networkInterfaces = array;
                            continue;
                        }
                        if (property0.NameEquals("subnets"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<Subnet> array = new List<Subnet>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(Subnet.DeserializeSubnet(item));
                            }
                            subnets = array;
                            continue;
                        }
                        if (property0.NameEquals("flowLogs"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<FlowLog> array = new List<FlowLog>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(FlowLog.DeserializeFlowLog(item));
                            }
                            flowLogs = array;
                            continue;
                        }
                        if (property0.NameEquals("resourceGuid"))
                        {
                            resourceGuid = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = new ProvisioningState(property0.Value.GetString());
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new NetworkSecurityGroup(id.Value, name.Value, type.Value, location.Value, Optional.ToDictionary(tags), etag.Value, Optional.ToList(securityRules), Optional.ToList(defaultSecurityRules), Optional.ToList(networkInterfaces), Optional.ToList(subnets), Optional.ToList(flowLogs), resourceGuid.Value, Optional.ToNullable(provisioningState));
        }
    }
}


text:
require "spec_helper"
require "hamster/sorted_set"

describe Hamster::SortedSet do
  describe "#first" do
    [
      [[], nil],
      [["A"], "A"],
      [%w[A B C], "A"],
      [%w[Z Y X], "X"]
    ].each do |values, expected|
      context "on #{values.inspect}" do
        it "returns #{expected.inspect}" do
          Hamster.sorted_set(*values).first.should eql(expected)
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
""" #    Get "counter" variable from node number: 0
self.breakpointVariable = self.tossimNodes[0].getVariable(self.appName + "." + "counter")
"""

""" #    Stop after "counter" is more than 15
if breakpointVariable.getData() > 15:
    breakpointOutput = "Breakpoint reached"
    stop = True
"""

""" #    Stop after "counter" is more than before
try:
    if self.breakpointVariable.getData() > self.breakpointCounter:
        self.breakpointCounter = self.breakpointVariable.getData()
        breakpointOutput = "Breakpoint reached"
        stop = True
except:
    breakpointCounter = 0
"""


text:
<?php

// Protect from unauthorized access
defined('FOF_INCLUDED') or die;

/**
 * FrameworkOnFramework model behavior class
 *
 * @package  FrameworkOnFramework
 * @since    2.1
 */
class FOFModelBehaviorEmptynonzero extends FOFModelBehavior
{
	/**
	 * This event runs when we are building the query used to fetch a record
	 * list in a model
	 *
	 * @param   FOFModel        &$model  The model which calls this event
	 * @param   JDatabaseQuery  &$query  The query being built
	 *
	 * @return  void
	 */
	public function onBeforeBuildQuery(&$model, &$query)
	{
		$model->setState('_emptynonzero', '1');
	}
}


text:
import requests
from models import Setting

def report_data(cuckoo_task_id):
    settings = Setting.query.filter_by(_id=1).first()
    host = settings.cuckoohost
    port = settings.cuckooapiport
    if host:
        cuckoo_api_resource = '/tasks/report/'
        url = 'http://' + host + ':' + port + cuckoo_api_resource + cuckoo_task_id
        r = requests.get(url)
        if r.status_code == 200:
            try:
                # TODO: Processing take a significant amount of time.
                sha1 = r.json()['target']['file']['sha1']
                task_started = r.json()['info']['started']
                # tcp_data = r.json()['network']['tcp']
                # http_data = r.json()['network']['http']
                dns_data = r.json()['network']['dns']
                host_data = r.json()['network']['hosts']

                return host_data, dns_data, sha1, task_started
            except:
                pass
    else:
        return None, None, None, None

def get_tasks():
    try:
        settings = Setting.query.filter_by(_id=1).first()
        host = settings.cuckoohost
        port = settings.cuckooapiport
        if host:
            url = 'http://' + host + ':' + port + '/tasks/list'
            r = requests.get(url)
            if r.status_code == 200:
                tasks = {}
                for t in r.json()['tasks']:
                    if 'file' in t['category']:
                        tasks[t['id']] = t['added_on']
                return tasks
    except:
        return {'[!] Error': 'Check Cuckoo API service'}


text:
package org.apache.geronimo.deployment.plugin;

import javax.enterprise.deploy.spi.TargetModuleID;
import javax.enterprise.deploy.spi.Target;
import javax.enterprise.deploy.shared.ModuleType;
import java.io.Serializable;

/**
 *
 *
 * @version $Rev$ $Date$
 */
public class TargetModuleIDImpl implements TargetModuleID, Serializable {
    private String webURL;
    private ModuleType type;
    private final Target target;
    private final String moduleID;
    private final TargetModuleID parentTargetModuleID;
    private final TargetModuleID[] childTargetModuleID;

    public TargetModuleIDImpl(Target target, String moduleID) {
        this.target = target;
        this.moduleID = moduleID;
        parentTargetModuleID = null;
        childTargetModuleID = null;
    }

    public TargetModuleIDImpl(Target target, String moduleID, String[] childIDs) {
        this.target = target;
        this.moduleID = moduleID;
        parentTargetModuleID = null;
        if(childIDs == null || childIDs.length == 0) {
            childTargetModuleID = null;
        } else {
            childTargetModuleID = new TargetModuleID[childIDs.length];
            for (int i = 0; i < childIDs.length; i++) {
                String childID = childIDs[i];
                childTargetModuleID[i] = new TargetModuleIDImpl(target, childID, this);
            }
        }
    }

    private TargetModuleIDImpl(Target target, String moduleID, TargetModuleID parent) {
        this.target = target;
        this.moduleID = moduleID;
        this.parentTargetModuleID = parent;
        childTargetModuleID = null;
    }

    public Target getTarget() {
        return target;
    }

    public String getModuleID() {
        return moduleID;
    }

    public TargetModuleID getParentTargetModuleID() {
        return parentTargetModuleID;
    }

    public TargetModuleID[] getChildTargetModuleID() {
        return childTargetModuleID;
    }

    public String getWebURL() {
        return webURL;
    }

    public void setWebURL(String webURL) {
        this.webURL = webURL;
    }

    public ModuleType getType() {
        return type;
    }

    public void setType(ModuleType type) {
        this.type = type;
    }

    public String toString() {
        return "[" + target + ", " + moduleID + "]";
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof TargetModuleIDImpl)) return false;

        final TargetModuleIDImpl targetModuleID = (TargetModuleIDImpl) o;

        if (!moduleID.equals(targetModuleID.moduleID)) return false;
        if (!target.equals(targetModuleID.target)) return false;

        return true;
    }

    public int hashCode() {
        int result;
        result = target.hashCode();
        result = 29 * result + moduleID.hashCode();
        return result;
    }
}


text:
package com.jmss.infra.results;

public interface HtmlResult {
    // TODO refactor with Enum for specifying media and get rid of boolean value???
    String toHtml(boolean toPdf);
    String getInitialFileName();
}


text:
[![build status](https://img.shields.io/travis/tanem/react-redux-playground/master.svg?style=flat-square)](https://travis-ci.org/tanem/react-redux-playground)
[![coverage status](https://img.shields.io/coveralls/tanem/react-redux-playground.svg?style=flat-square)](https://coveralls.io/github/tanem/react-redux-playground)

 _Work in progress_

Messing about with [React](https://github.com/facebook/react) and [Redux](https://github.com/rackt/redux). There's a bunch of useful info out there, but hopefully there are a few bits and pieces others might find helpful here too.

## Features

The app is based on Redux's [counter example](https://github.com/rackt/redux/tree/master/examples/counter), and includes:

- ES2015+ syntax via [Babel](https://babeljs.io/)
- Hot reloading React classes via [react-transform-hmr](https://github.com/gaearon/react-transform-hmr)
- Live editing time travel via [Redux DevTools](https://github.com/gaearon/redux-devtools)
- Routing via [redux-simple-router](https://github.com/jlongster/redux-simple-router)
- Unit testing via [mocha](https://github.com/mochajs/mocha), [chai](https://github.com/chaijs/chai), and [sinon](https://github.com/sinonjs/sinon)
- Code coverage reporting via [isparta](https://github.com/douglasduteil/isparta)

## Start

1. Clone the repo
2. `npm install` the dependencies
3. Run `npm start`
4. Open `http://localhost:3000/` in your browser.

## Testing

Single run, specs only:

```
$ npm run test:spec
```

Run specs and watch:

```
$ npm run test:watch
```

Generate coverage reports:

```
$ npm run test:cov
```


text:
<!DOCTYPE html>

    <link rel="icon" href=img\snake_icon.png>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Blog Post 9.11.17</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

    <link href="css/clean-blog.min.css" rel="stylesheet">

        Snake Shenanigans
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
            Menu

          </button>

                Home

                About

                  Laboratory

                Blog Posts

                Contact

Genesis

In the beginning there was nothing...just kidding we had something.

              Posted by
                Nelson Raphael
                on September 11, 2017

Welcome to my Research Blog

Welcome to my first blog post. Let's get you up to speed regarding my research. After some careful code reorganization and debugging we have completed the visual processing portion of the project. This now gives us more information regarding the environment that the robotic snake is in. We can get exact information that helps us traverse obstacles and engage particular motion primitives.

We will have to rebuild the snake and this time all of the joints will move solely in the x and y plane, however, these small changes will have to be made to the code to adapt to the new dimensions of the snake.

I can illustrate a little bit more here. So the current closed loop process uses object oriented classes that house the information for the snake, the environment, and other things respectively. Therefore when instantiating the Snake model class object we have to pass in the rotational angles, the displacement between each motor joint that moves in the plane we want, and the tailframe in SE2 notation.

                %MATLAB code
                d = [50,100,150,200,250,300,350];
                rot = [0,0,0,0,0,0];
                tailframe = SE2([0,0],0);
                snk = SnakeModel(d,rot,tailframe);

                %These are arbitrary values to illustrate a point

When all of the various classes work together they create this visual interface that models the snake's shape real time using SE2 notation, visual data, and tactile sensing. Below is the result.

 Photographs by
              NASA on The Commons.

Copyright © Nelson Raphael


text:
My dotfiles. Use on your own risk ;)

```bash
curl -sSL https://raw.github.com/klausmeyer/dotfiles/master/setup.sh | bash
```


text:
title: Maths using Def
layout: post
author: josh.king
permalink: /maths-using-def/
source-id: 1s-knf5cXYJlW6IM4Wqq90NcxdP24ZzxQi6xjmX08MWg
published: true
---

    Title
    Maths using def
    Date
    8/1/2018

    Lesson Review

    How did I learn? What strategies were effective?

    At the start of the lesson we were given a demonstration on how using def (define) you can complete relatively simple maths equations. Here is my code https://repl.it/@joshking/Maths-using-def . We used def to declare the functions which we were using. I followed that up with "main():" to give me "def main():" after that I had to end the piece of code with main().

    What limited my learning? Which habits do I need to work on?

    Often whilest completing the task it was easy for me to be tempted to copy some of the code however by copying some of the code straight of the board allowed me to understand the main parts of the code.

    What will I change for next time? How will I improve my learning?

    Next time I will be able to be more confident in myself so I dont have to depend on someone elses code.


text:
/**
 * get a substring of a particular length from the left
 *
 * @function module:String.prototype.left
 * @param {number}     n     The lenth of the string to return
 * @return {string}
 * @example
 *  'foobar'.left(3) === 'foo'
 */
String.prototype.left = String.prototype.left || function(n) {
	return this.substr(0,n);
};


text:
$(document).ready(function() {
    var tableController = new TableController(
            {"tableData": jsonData,
             "tableDiv": $("#table"),
             "tableType": "grid"
            });
    tableController.createTable();
});


text:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:paddingLeft="10dp"
        android:paddingTop="10dp"
        android:text="User List"
        android:textSize="15sp"
        android:visibility="visible" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@android:color/darker_gray" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:paddingBottom="@dimen/list_item_spacing_half"
        android:layout_marginTop="10dp"
        tools:context="io.github.powerinside.syncplay.UserListDialogFragment"
        tools:listitem="@layout/fragment_user_list_dialog_item">
        </androidx.recyclerview.widget.RecyclerView>
</LinearLayout>


text:
python3 -m examples.experiments.regression_exp --dataset=housing  --score=MLE --lr=0.0007 --n-est=5000
python3 -m examples.experiments.regression_exp --dataset=concrete  --score=MLE  --lr=0.002 --n-est=5000
python3 -m examples.experiments.regression_exp --dataset=energy  --score=MLE  --lr=0.002 --n-est=5000
python3 -m examples.experiments.regression_exp --dataset=kin8nm  --score=MLE
python3 -m examples.experiments.regression_exp --dataset=naval  --score=MLE
python3 -m examples.experiments.regression_exp --dataset=power  --score=MLE
python3 -m examples.experiments.regression_exp --dataset=protein  --score=MLE --n-splits=5
python3 -m examples.experiments.regression_exp --dataset=wine  --score=MLE
python3 -m examples.experiments.regression_exp --dataset=yacht  --score=MLE
python3 -m examples.experiments.regression_exp --dataset=msd  --score=MLE


text:
const co = require('co');
const sinon = require('sinon');
const ActionRunner = require('../../lib/core/action-runner');

/* eslint require-yield: 0 */

describe('core/action-runner', function() {
  it('work with filters', function() {
    // Filter A
    const A = {
      beforeAction: function* () {
        this.info = {
          name: 'plover'
        };

        this.data.list = [];
      },

      afterAction: function* () {
        this.data.list.push('A');
      }
    };

    // Filter B
    const B = {
      beforeAction: function* () {
        this.info.desc = 'node js web framework';
      },

      afterAction: function() {
        this.data.list.push('B');
      }
    };

    const app = {};
    const filters = [
      {
        filter: A
      },
      {
        filter: B
      }
    ];
    const runner = new ActionRunner(app, { filters: filters });

    // Controller
    const C = {
      beforeAction: function() {
        this.info.version = '1.0';
      },

      view: function* () {
        this.data.list.push('C1');
      },

      afterAction: function() {
        this.data.list.push('C2');
      }
    };

    // ActionContext
    const ctx = {
      data: {}
    };

    const rd = {
      module: C,
      route: {
        module: 'test',
        action: 'view'
      }
    };

    return co(function* () {
      yield runner.run(rd, ctx);

      ctx.info.should.eql({
        name: 'plover',
        version: '1.0',
        desc: 'node js web framework'
      });

      // after render执行是逆序的
      ctx.data.list.should.eql(['C1', 'C2', 'B', 'A']);
    });
  });

  it('break in filter before action', function() {
    const A = {
      beforeAction: function() {
        this.body = 'ok';
        return false;
      }
    };

    const ctx = {};
    const rd = {
      route: {
        module: 'test',
        action: 'update'
      }
    };

    const runner = new ActionRunner({}, { filters: [{ filter: A }] });
    return co(function* () {
      yield runner.run(rd, ctx);
      ctx.body.should.equal('ok');
    });
  });

  it('break in action', function() {
    const controller = {
      view: function() {
        this.body = 'hello';
        return false;
      },
      afterAction: sinon.spy()
    };

    return co(function* () {
      const ctx = {};
      yield runAction(controller, ctx);
      ctx.body.should.equal('hello');
      controller.afterAction.called.should.be.false();
    });
  });

  it('no filter', function() {
    const controller = {
      view: sinon.spy()
    };

    return co(function* () {
      const ctx = {};
      yield runAction(controller, ctx);
      controller.view.called.should.be.true();
    });
  });

  it('break in controller beforeAction', function() {
    const controller = {
      beforeAction: function* () {
        this.body = 'hello';
        return false;
      },
      view: sinon.spy()
    };

    return co(function* () {
      const ctx = {};
      yield runAction(controller, ctx);
      ctx.body.should.equal('hello');
      controller.view.called.should.be.false();
    });
  });

  it('break in after filter', function() {
    const controller = {
      view: sinon.spy(),
      afterAction: function* () {
        return { content: 'hello world' };
      }
    };

    return co(function* () {
      const ctx = {};
      const ret = yield runAction(controller, ctx);
      ret.should.eql({ content: 'hello world' });
    });
  });

  it('work with arrow function', function() {
    const controller = {};
    controller.view = ctx => {
      ctx.body = 'hello';
    };

    return co(function* () {
      const ctx = {};
      yield runAction(controller, ctx);
      ctx.body.should.equal('hello');
    });
  });
});

function* runAction(controller, ctx) {
  const rd = {
    module: controller,
    route: {
      module: 'test',
      action: 'view'
    }
  };

  const runner = new ActionRunner({}, { filters: [] });
  return yield runner.run(rd, ctx);
}


text:
cask :v1 => 'font-noto-serif' do
  version :latest
  sha256 :no_check

  url 'http://www.google.com/get/noto/pkgs/NotoSerif-unhinted.zip'
  homepage 'http://www.google.com/get/noto/#/family/noto-serif'
  license :apache

  font 'NotoSerif-Bold.ttf'
  font 'NotoSerif-BoldItalic.ttf'
  font 'NotoSerif-Italic.ttf'
  font 'NotoSerif-Regular.ttf'
end


text:
package core

// Viewable is the interface to a View
type Viewable interface {
	Widget
	Backspace()
	Backend() Backend
	ClearSelections()
	Copy()
	CurCol() int
	CurLine() int
	CursorMvmt(mvmt CursorMvmt)
	Cut()
	Delete(row1, col1, row, col2 int, undoable bool)
	DeleteCur()
	Dirty() bool
	Id() int64
	Insert(row, col int, text string, undoable bool)
	InsertCur(text string)
	InsertNewLineCur()
	LastViewCol() int
	LastViewLine() int
	LineCount() int
	// LineRunesTo returns the number of raw runes to the given line column
	LineRunesTo(s *Slice, line, col int) int
	// MoveCursor moves the cursor by the y, x offsets (in runes)
	MoveCursor(y, x int)
	MoveCursorRoll(y, x int)
	OpenSelection(newView bool)
	Paste()
	// Reload reloads the view data from it's source (backend)
	Reload()
	// Reset reinitializes the view to it's startup state.
	Reset()
	Save() // Save from buffer to src
	ScrollPos() (ln, col int)
	SetBackend(backend Backend)
	SetDirty(bool)
	SelectAll()
	SelectWord(ln, col int)
	Selections() *[]Selection
	// SetAutoScroll is used to make the view scroll contonuously in y,x increments
	// keeps scrolling until x and y are set to 0.
	SetAutoScroll(y, x int, isSelect bool)
	SetCursorPos(y, x int)
	SetScrollPct(ypct int)
	SetScrollPos(y, x int)
	SetTitle(title string)
	SetViewType(t ViewType)
	SetVtCols(cols int)
	// Sets the view work directory, commands and "open" actions will be relative
	// to this path.
	SetWorkDir(dir string)
	// Slice returns a view's text subset (rectangle)
	Slice() *Slice
	StretchSelection(prevl, prevc, ln, c int)
	SyncSlice()
	Title() string
	Text(ln1, col1, ln2, col2 int) [][]rune
	Type() ViewType
	WorkDir() string
}


text:
namespace base {
class DictionaryValue;
class Value;
}

struct Session;
class Status;
class WebView;

typedef base::Callback<Status(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue&,
    scoped_ptr<base::Value>*)> WindowCommand;

// Execute a Window Command on the target window.
Status ExecuteWindowCommand(
    WindowCommand command,
    Session* session,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Loads a URL.
Status ExecuteGet(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Evaluates a given script with arguments.
Status ExecuteExecuteScript(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Changes the targeted frame for the given session.
Status ExecuteSwitchToFrame(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Get the current page title.
Status ExecuteGetTitle(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Get the current page source.
Status ExecuteGetPageSource(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Search for an element on the page, starting from the document root.
Status ExecuteFindElement(
    int interval_ms,
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Search for multiple elements on the page, starting from the document root.
Status ExecuteFindElements(
    int interval_ms,
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Get the current page url.
Status ExecuteGetCurrentUrl(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Navigate backward in the browser history.
Status ExecuteGoBack(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Navigate forward in the browser history.
Status ExecuteGoForward(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Refresh the current page.
Status ExecuteRefresh(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Move the mouse by an offset of the element if specified .
Status ExecuteMouseMoveTo(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Click a mouse button at the coordinates set by the last moveto.
Status ExecuteMouseClick(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Click and hold a mouse button at the coordinates set by the last moveto.
Status ExecuteMouseButtonDown(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Releases the mouse button previously held (where the mouse is currently at).
Status ExecuteMouseButtonUp(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

// Double-clicks at the current mouse coordinates (set by last moveto).
Status ExecuteMouseDoubleClick(
    Session* session,
    WebView* web_view,
    const base::DictionaryValue& params,
    scoped_ptr<base::Value>* value);

#endif  // CHROME_TEST_CHROMEDRIVER_WINDOW_COMMANDS_H_


text:
if [ ! -d build ]; then
  mkdir build
fi
cd build
cmake -DCMAKE_C_COMPILER=/usr/bin/gcc -DCMAKE_CXX_COMPILER=/usr/bin/g++ ..


text:
My [dotfiles](https://dotfiles.github.io/).

## Install

    curl -s https://raw.githubusercontent.com/messivanio/dotfiles/master/install/install-dotfiles.sh | sh
    source ~/dotfiles/bash/.bashrc
    sudo timedatectl set-timezone America/Sao_Paulo
    mkdir -p ~/code/agora
    ln -s ~/dotfiles/config/kitty/ ~/.config/kitty

Or...

    git clone ssh://git@github.com/messivanio/dotfiles.git


text:
namespace gpopt
{
using namespace gpos;

class CWindowTest
{
public:
	// unittests
	static GPOS_RESULT EresUnittest();
};	// class CWindowTest
}  // namespace gpopt

#endif	// !GPOPT_CWindowTest_H

// EOF


text:
/********************************************************
 * Engine is our container for our main program logic
 *
 * This allows us to only place code in main.c that
 * interacts with the user through our framework and
 * thus change framework if needed.
 *
 ********************************************************/

#include "engine.h"

//////////////////////////////////////////////////////////
// For now we just some global state to make life easy

EngineError engineErrCallback = NULL;
EngineKeyPressed engineKeyPressedCallback = NULL;

// object info
llist *       materials = NULL;
llist *       meshes = NULL;

// and some globals for our fonts
FONScontext * fs = NULL;
int           font = FONS_INVALID;
float         lineHeight = 0.0f;

// shaders
shaderStdInfo   colorShader;
shaderStdInfo   texturedShader;
shaderStdInfo   reflectShader;

// lights
lightSource   sun;

// our camera
mat4          view;
vec3          camera_eye = { -200.0, 20.0, 500.0 };
vec3          camera_lookat =  { -300.0, 100.0, -50.0 };

// and some runtime variables.
double        frames = 0.0f;
double        fps = 0.0f;
double        lastframes = 0.0f;
double        lastsecs = 0.0f;

//////////////////////////////////////////////////////////
// error handling

// sets our error callback method which is modelled after
// GLFWs error handler so you can use the same one
void engineSetErrorCallback(EngineError pCallback) {
  engineErrCallback = pCallback;

  // Set our callbacks in our support libraries
//  tsSetErrorCallback(engineErrCallback);
//  spSetErrorCallback(engineErrCallback);
};

//////////////////////////////////////////////////////////
// keyboard handling

// sets a callback that allows us to test if a key is
// pressed
void engineSetKeyPressedCallback(EngineKeyPressed pCallback) {
  engineKeyPressedCallback = pCallback;
};

//////////////////////////////////////////////////////////
// fonts
void load_font() {
  // we start with creating a font context that tells us about the font we'll be rendering
  fs = gl3fonsCreate(512, 512, FONS_ZERO_TOPLEFT);
  if (fs != NULL) {
    // then we load our font
    font = fonsAddFont(fs, "sans", "DroidSerif-Regular.ttf");
    if (font != FONS_INVALID) {
      // setup our font
      fonsSetColor(fs, gl3fonsRGBA(255,255,255,255)); // white
      fonsSetSize(fs, 16.0f); // 16 point font
      fonsSetAlign(fs, FONS_ALIGN_LEFT | FONS_ALIGN_TOP); // left/top aligned
      fonsVertMetrics(fs, NULL, NULL, &lineHeight);
    } else {
      engineErrCallback(-201, "Couldn't load DroidSerif-Regular.ttf");
    };
  } else {
    engineErrCallback(-200, "Couldn't create our font context");
  };
};

void unload_font() {
  if (fs != NULL) {
    gl3fonsDelete(fs);
    fs = NULL;
  };
};

//////////////////////////////////////////////////////////
// Shaders

// load contents of a file
// return NULL on failure
// returns string on success, calling function is responsible for freeing the text
char* loadFile(const char* pFileName) {
  char  error[1024];
  char* result = NULL;

  // read "binary", we simply keep our newlines as is
  FILE* file = fopen(pFileName,"rb");
  if (file == NULL) {
    sprintf(error,"Couldn't open %s",pFileName);
    engineErrCallback(-100, error);
  } else {
    long size;

    // find the end of the file to get its size
    fseek(file, 0, SEEK_END);
    size = ftell(file);
    fseek(file, 0, SEEK_SET);

    // allocate space for our data
    result = (char*) malloc(size+1);
    if (result == NULL) {
      sprintf(error,"Couldn't allocate memory buffer for %li bytes",size);
      engineErrCallback(-101, error);
    } else {
      // and load our text
      fread(result, 1, size, file);
      result[size] = 0;
    };

    fclose(file);
  };

  return result;
};

void load_shaders() {
  char* shaderText = NULL;
  GLuint vertexShader = NO_SHADER, fragmentShader = NO_SHADER;

  shaderText = loadFile("standard.vs");
  if (shaderText != NULL) {
    vertexShader = shaderCompile(GL_VERTEX_SHADER, shaderText);
    free(shaderText);

    if (vertexShader != NO_SHADER) {
      // compile our color shader
      shaderText = loadFile("flatcolor.fs");
      if (shaderText != NULL) {
        fragmentShader = shaderCompile(GL_FRAGMENT_SHADER, shaderText);
        free(shaderText);

        if (fragmentShader != NO_SHADER) {
          colorShader = shaderGetStdInfo(shaderLink(2, vertexShader, fragmentShader));

          // no longer need this...
          glDeleteShader(fragmentShader);
        };
      };

      // compile our textured shader
      shaderText = loadFile("textured.fs");
      if (shaderText != NULL) {
        fragmentShader = shaderCompile(GL_FRAGMENT_SHADER, shaderText);
        free(shaderText);

        if (fragmentShader != NO_SHADER) {
          texturedShader = shaderGetStdInfo(shaderLink(2, vertexShader, fragmentShader));

          // no longer need this...
          glDeleteShader(fragmentShader);
        };
      };

      // compile our refleect shader
      shaderText = loadFile("reflect.fs");
      if (shaderText != NULL) {
        fragmentShader = shaderCompile(GL_FRAGMENT_SHADER, shaderText);
        free(shaderText);

        if (fragmentShader != NO_SHADER) {
          reflectShader = shaderGetStdInfo(shaderLink(2, vertexShader, fragmentShader));

          // no longer need this...
          glDeleteShader(fragmentShader);
        };
      };

      // no longer need this...
      glDeleteShader(vertexShader);
    };
  };
};

void unload_shaders() {
  // should add proper functions for freeing up shaders here
  glDeleteProgram(colorShader.program);
  glDeleteProgram(texturedShader.program);
  glDeleteProgram(reflectShader.program);
};

//////////////////////////////////////////////////////////
// Objects

void load_objects() {
	int x, y, comp;
  unsigned char * data;
  char * text;
  vec3 tmpvector;
  mesh3d * mesh;
  material * mat;

  // create a retainer for materials
  materials = newMatList();

  // create a retainer for meshes
  meshes = newMeshList();
  if (meshes != NULL) {
    llistNode * node;

/*
    mat = newMaterial("cube");                  // create a material for our cube
    matLoadTexture(mat, "boxtexture.jpg", GL_LINEAR, GL_CLAMP_TO_EDGE);  // load our texture map
    mesh = newMesh(24, 36);                     // init our cube with enough space for our buffers
    strcpy(mesh->name,"cube");                  // set name to cube
    meshSetMaterial(mesh, mat);                 // assign our material
    matRelease(mat);                            // and release it, our mesh now owns it
    meshMakeCube(mesh, 10.0, 10.0, 10.0);       // create our cube
    mat4Translate(&mesh->defModel, vec3Set(&tmpvector, -10.0, 0.0, 0.0)); // position it
    meshCopyToGL(mesh, true);                   // copy our cube data to the GPU
    llistAddTo(meshes, mesh);                   // add it to our list
    meshRelease(mesh);                          // and release it, our list now owns it
*/

    mat = newMaterial("sphere");                // create a material for our sphere
    matLoadTexture(mat, "EarthMap.jpg", GL_LINEAR, GL_CLAMP_TO_EDGE);  // load our texture map
    mesh = newMesh(10585, 62208);               // init our sphere with default space for our buffers
    strcpy(mesh->name,"sphere");                // set name to sphere
    meshSetMaterial(mesh, mat);                 // assign our material
    matRelease(mat);                            // and release it, our mesh now owns it
    meshMakeSphere(mesh, 100.0);                // create our sphere
    mat4Translate(&mesh->defModel, vec3Set(&tmpvector, 100.0, 0.0, 0.0)); // position it
    meshCopyToGL(mesh, true);                   // copy our sphere data to the GPU
    llistAddTo(meshes, mesh);                   // add it to our list
    meshRelease(mesh);                          // and release it, our list now owns it

    // load our mtl file
    text = loadFile("tie-bomber.mtl");
    if (text != NULL) {
      matParseMtl(text, materials);

      free(text);
    };

    // load our obj file
    text = loadFile("tie-bomber.obj");
    if (text != NULL) {
      meshParseObj(text, meshes, materials, true);

      free(text);
    };
  };
};

void unload_objects() {
  // free our mesh list, this will also destoy all the meshes within
  if (meshes != NULL) {
    llistFree(meshes);
    meshes = NULL;
  };

  if (materials != NULL) {
    llistFree(materials);
    materials = NULL;
  };
};

//////////////////////////////////////////////////////////
// Main engine

// engineInit initializes any variables, kinda like our constructor
void engineInit() {

};

// engineLoad loads any data that we need to load before we can start outputting stuff
void engineLoad() {
  vec3  upvector;

  // load our font
  load_font();

  // load, compile and link our shader(s)
  load_shaders();

  // setup our light
  vec3Set(&sun.position, 0.0, 10000.0, 5000.00);

  // load our objects
  load_objects();

  // init our view matrix
  mat4Identity(&view);
  mat4LookAt(&view, &camera_eye, &camera_lookat, vec3Set(&upvector, 0.0, 1.0, 0.0));
};

// engineUnload unloads and frees up any data associated with our engine
void engineUnload() {
  // lets be nice and cleanup
  unload_shaders();
  unload_objects();
  unload_font();
};

// engineUpdate is called to handle any updates of our data
// pSecondsPassed is the number of seconds passed since our application was started.
void engineUpdate(double pSecondsPassed) {
  const joystickInfo * joystick = getJoystickInfo(0);
  float         delta;
  vec3          avector, bvector, upvector;
  mat4          M;
  float         moveHorz = 0.0;
  float         moveVert = 0.0;

  // handle our joystick
  if (joystick == NULL) {
    // no joystick
  } else if (joystick->enabled) {
    moveHorz = joystick->axes[0] * 2.0;
    moveVert = joystick->axes[1] * 2.0;
  };

  // handle our keys....
  if (engineKeyPressedCallback(GLFW_KEY_A)) {
    moveHorz = 1.0;
  } else if (engineKeyPressedCallback(GLFW_KEY_D)) {
    moveHorz = -1.0;
  } else if (engineKeyPressedCallback(GLFW_KEY_W)) {
    moveVert = 1.0;
  } else if (engineKeyPressedCallback(GLFW_KEY_S)) {
    moveVert = -1.0;
  };

  // adjust camera
  if ((moveHorz <= -0.1) || (moveHorz >= 0.1)) {
    // rotate position left

    // get our (reverse) looking direction vector
    vec3Copy(&avector, &camera_eye);
    vec3Sub(&avector, &camera_lookat);

    // rotate our looking direction vector around our up vector
    mat4Identity(&M);
    mat4Rotate(&M, moveHorz, vec3Set(&bvector, view.m[0][1], view.m[1][1], view.m[2][1]));

    // and update our eye position accordingly
    mat4ApplyToVec3(&camera_eye, &avector, &M);
    vec3Add(&camera_eye, &camera_lookat);
  };

  if ((moveVert <= -0.1) || (moveVert >= 0.1)) {
    // get our (reverse) looking direction vector
    vec3Copy(&avector, &camera_eye);
    vec3Sub(&avector, &camera_lookat);

    // rotate our looking direction vector around our right vector
    mat4Identity(&M);
    mat4Rotate(&M, moveVert, vec3Set(&bvector, view.m[0][0], view.m[1][0], view.m[2][0]));

    // and update our eye position accordingly
    mat4ApplyToVec3(&camera_eye, &avector, &M);
    vec3Add(&camera_eye, &camera_lookat);
  };

  // update our view matrix
  mat4Identity(&view);
  mat4LookAt(&view, &camera_eye, &camera_lookat, vec3Set(&upvector, 0.0, 1.0, 0.0));

  // update our frame counter
  frames += 1.0f;
  delta = pSecondsPassed - lastsecs;
  fps = (frames - lastframes) / delta;

  if (frames - lastframes > 100.0f) {
    // reset every 100 frames
    lastsecs = pSecondsPassed;
    lastframes = frames;
  };
};

// structure for storing info about transparent meshes that we render later on
typedef struct alphaMesh {
  mesh3d *  mesh;
  mat4      model;
  GLfloat   z;
} alphaMesh;

// engineRender is called to render our stuff
// pWidth and pHeight define the size of our drawing buffer
// pMode is 0 => mono, 1 => left eye, 2 => right eye
void engineRender(int pWidth, int pHeight, float pRatio, int pMode) {
  shaderMatrices  matrices;
  vec3            tmpvector;
  float           left, top;
  int             i;
  dynarray *      meshesWithAlpha = newDynArray(sizeof(alphaMesh));

  // calculate our sun position, we want to do this only once
  mat4ApplyToVec3(&sun.adjPosition,&sun.position, &view);

  // enable and configure our backface culling
  glEnable(GL_CULL_FACE);   // enable culling
  glFrontFace(GL_CW);       // clockwise
  glCullFace(GL_BACK);      // backface culling
  // enable our depth test
  glEnable(GL_DEPTH_TEST);
  // disable alpha blending
  glDisable(GL_BLEND);

  // set our model view projection matrix

  // init our projection matrix, we use a 3D projection matrix now
  mat4Identity(&matrices.projection);
//  mat4Projection(&matrices.projection, 45.0, pRatio, 1.0, 10000.0);
  // distance between eyes is on average 6.5 cm, this should be setable
  mat4Stereo(&matrices.projection, 45.0, pRatio, 1.0, 10000.0, 6.5, 200.0, pMode);

  // copy our view matrix into our state
  mat4Copy(&matrices.view, &view);

  if (meshes != NULL) {
    int count = 0;
    llistNode * node = meshes->first;
    while (node != NULL) {
      mesh3d * mesh = (mesh3d *) node->data;
      if (mesh == NULL) {
        // skip
      } else if (!mesh->visible) {
        // skip
      } else {
        bool doRender = true;
        // set our model matrix, this calculation will be more complex in due time
        mat4Copy(&matrices.model, &mesh->defModel);

        // select our shader, for now we have 3 shaders that do different types of shading
        // eventually we'll add something that allows us to make combinations
        if (mesh->material == NULL) {
          shaderSelectProgram(&colorShader, &matrices, &sun, NULL);
        } else if (mesh->material->alpha != 1.0) {
          // postpone
          alphaMesh aMesh;
          GLfloat z = 0; // we should calculate this by taking our modelview matrix and taking our Z offset

          // copy our mesh info
          aMesh.mesh = mesh;
          mat4Copy(&aMesh.model, &matrices.model);
          aMesh.z = z;

          // and push it...
          dynArrayPush(meshesWithAlpha, &aMesh); // this copies our structure
          doRender = false; // we're postponing...
        } else if (mesh->material->reflectId != MAT_NO_TEXTURE) {
          shaderSelectProgram(&reflectShader, &matrices, &sun, mesh->material);
        } else if (mesh->material->textureId != MAT_NO_TEXTURE) {
          shaderSelectProgram(&texturedShader, &matrices, &sun, mesh->material);
        } else {
          shaderSelectProgram(&colorShader, &matrices, &sun, mesh->material);
        };

        if (doRender) {
          // and render it, if we fail we won't render it again
          mesh->visible = meshRender(mesh);
        };
      };

      node = node->next;
      count++;
    };
  };

  // now render our alpha meshes
  if (meshesWithAlpha->numEntries > 0) {
    // we should sort meshesWithAlpha by Z

    // we blend our colors here...
  	glEnable(GL_BLEND);
  	glBlendEquation(GL_FUNC_ADD);
  	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    for (i = 0; i < meshesWithAlpha->numEntries; i++) {
      alphaMesh * aMesh = dynArrayDataAtIndex(meshesWithAlpha, i);

      mat4Copy(&matrices.model, &aMesh->model);
      if (aMesh->mesh->material->reflectId != MAT_NO_TEXTURE) {
        shaderSelectProgram(&reflectShader, &matrices, &sun, aMesh->mesh->material);
      } else if (aMesh->mesh->material->textureId != MAT_NO_TEXTURE) {
        shaderSelectProgram(&texturedShader, &matrices, &sun, aMesh->mesh->material);
      } else {
        shaderSelectProgram(&colorShader, &matrices, &sun, aMesh->mesh->material);
      };

      aMesh->mesh->visible = meshRender(aMesh->mesh);
    };
  };

  // and free
  dynArrayFree(meshesWithAlpha);

  // unset stuff
  glBindVertexArray(0);
  glUseProgram(0);

  ////////////////////////////////////
  // UI

  // change our state a little
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_CULL_FACE);
	glEnable(GL_BLEND);
	glBlendEquation(GL_FUNC_ADD);
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

  // now render our FPS
	if ((fs != NULL) && (font != FONS_INVALID)) {
    const joystickInfo * joystick = getJoystickInfo(0);
    float virtualScreenHeight = 250.0;
    char info[256];

    // We want a orthographic projection for our frame counter
    mat4Identity(&matrices.projection);
    mat4Ortho(&matrices.projection, -pRatio * virtualScreenHeight, pRatio * virtualScreenHeight, virtualScreenHeight, -virtualScreenHeight, 1.0f, -1.0f);
    gl3fonsProjection(fs, (GLfloat *)matrices.projection.m);

    // what text shall we draw?
    sprintf(info,"FPS: %0.1f, use wasd to move the camera", fps);

    // and draw some text
    fonsDrawText(fs, -pRatio * 250.0f, 230.0f, info, NULL);

    // lets display some info about our joystick:
    if (joystick != NULL) {
      if (joystick->enabled) {
        sprintf(info, "Joystick %s is active", joystick->name);
        fonsDrawText(fs, -pRatio * 250.0f, -250.0f, info, NULL);

        sprintf(info, "Axes: %f %f %f %f %f %f %f %f", joystick->axes[0], joystick->axes[1], joystick->axes[2], joystick->axes[3], joystick->axes[4], joystick->axes[5], joystick->axes[6], joystick->axes[7]);
        fonsDrawText(fs, -pRatio * 250.0f, -230.0f, info, NULL);

        sprintf(info, "Buttons: %i %i %i %i %i %i %i %i", joystick->buttons[0], joystick->buttons[1], joystick->buttons[2], joystick->buttons[3], joystick->buttons[4], joystick->buttons[5], joystick->buttons[6], joystick->buttons[7]);
        fonsDrawText(fs, -pRatio * 250.0f, -210.0f, info, NULL);
      } else {
        sprintf(info, "Joystick %s is inactive", joystick->name);
        fonsDrawText(fs, -pRatio * 250.0f, -250.0f, info, NULL);
      };
    };
  };
};

void engineKeyPressed(int pKey) {
//  pushKey(pKey);
};


text:
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone

from konfera.models.abstract import KonferaModel
from konfera.models.order import Order, AWAITING
from konfera.models.speaker import TITLE_UNSET, TITLE_CHOICES

REQUESTED = 'requested'
REGISTERED = 'registered'
CHECKEDIN = 'checked-in'
CANCELLED = 'cancelled'

TICKET_STATUS = (
    (REQUESTED, _('Requested')),
    (REGISTERED, _('Registered')),
    (CHECKEDIN, _('Checked-in')),
    (CANCELLED, _('Cancelled')),
)

class Ticket(KonferaModel):
    type = models.ForeignKey('TicketType')
    discount_code = models.ForeignKey('DiscountCode', blank=True, null=True)
    status = models.CharField(choices=TICKET_STATUS, max_length=32)
    title = models.CharField(choices=TITLE_CHOICES, max_length=4, default=TITLE_UNSET)
    first_name = models.CharField(max_length=128)
    last_name = models.CharField(max_length=128)
    email = models.EmailField()
    phone = models.CharField(max_length=64, blank=True)
    description = models.TextField(blank=True)
    order = models.ForeignKey('Order', blank=True)

    def __str__(self):
        return '{title} {first_name} {last_name}'.format(
            title=dict(TITLE_CHOICES)[self.title],
            first_name=self.first_name,
            last_name=self.last_name
        ).strip()

    def discount_calculator(self):

        if self.discount_code:
            return self.type.price * self.discount_code.discount / 100
        return 0

    def clean(self):
        if self.discount_code and self.discount_code.ticket_type != self.type:
            raise ValidationError(
                {'discount_code': _('Discount code is not applicable for the selected ticket type.')})
        super().clean()

    def save(self, *args, **kwargs):
        self.clean()
        if not hasattr(self, 'order'):
            discount = self.discount_calculator()
            order = Order(price=self.type.price, discount=discount, status=AWAITING, purchase_date=timezone.now())
            order.save()
            self.order = order
        super(Ticket, self).save(*args, **kwargs)


text:
"use strict";

var assert = require("../util/assert.js");
var reset = require("../__reset.js");
var quixote = require("../quixote.js");
var ElementEdge = require("./element_edge.js");
var Position = require("../values/position.js");
var RelativePosition = require("./relative_position.js");
var PositionDescriptor = require("./position_descriptor.js");

describe("ElementEdge", function() {

	var frame;
	var element;
	var top;
	var right;
	var bottom;
	var left;

	var TOP = 10;
	var RIGHT = 150;
	var BOTTOM = 70;
	var LEFT = 20;

	beforeEach(function() {
		frame = reset.frame;
		element = frame.add(
			"
element
",
			"element"
		);
		top = ElementEdge.top(element);
		right = ElementEdge.right(element);
		bottom = ElementEdge.bottom(element);
		left = ElementEdge.left(element);
	});

	it("is a position descriptor", function() {
		assert.implements(top, PositionDescriptor);
	});

	it("resolves to value", function() {
		assert.objEqual(top.value(), Position.y(TOP), "top");
		assert.objEqual(right.value(), Position.x(RIGHT), "right");
		assert.objEqual(bottom.value(), Position.y(BOTTOM), "bottom");
		assert.objEqual(left.value(), Position.x(LEFT), "left");
	});

	it("converts arguments to comparable values", function() {
		assert.objEqual(top.convert(13, "number"), Position.y(13), "top");
		assert.objEqual(right.convert(13, "number"), Position.x(13), "right");
		assert.objEqual(bottom.convert(13, "number"), Position.y(13), "bottom");
		assert.objEqual(left.convert(13, "number"), Position.x(13), "left");
	});

	it("converts to string", function() {
		assertDesc(element, top, "top edge of ", "top");
		assertDesc(element, right, "right edge of ", "right");
		assertDesc(element, bottom, "bottom edge of ", "bottom");
		assertDesc(element, left, "left edge of ", "left");

		function assertDesc(element, edge, expected, message) {
			assert.equal(edge.toString(), expected + element, message);
		}
	});

	it("accounts for scrolling", function() {
		if (quixote.browser.enlargesFrameToPageSize()) return;

		frame.add("
scroll enabler
");

		frame.scroll(50, 60);

		assert.objEqual(top.value(), Position.y(TOP), "top");
		assert.objEqual(right.value(), Position.x(RIGHT), "right");
		assert.objEqual(bottom.value(), Position.y(BOTTOM), "bottom");
		assert.objEqual(left.value(), Position.x(LEFT), "left");
	});

});


text:
var __ = require('./i18n')(__dirname).__,
	mix = require('./util').mix,
	sp = require('./subprocess'),
	run = sp.run,
	findExecutable = sp.findExecutable,
	afs = require('./fs'),
	async = require('async'),
	fs = require('fs'),
	path = require('path'),
	cache;

/**
 * Detects if Java and the JDK are installed.
 * @param {Object} [config] - The CLI configuration
 * @param {Object} [opts] - Detection options; currently only 'bypassCache'
 * @param {Function} finished - A function to call with the result
 * @example
 * require('./lib/jdk').detect(function (r) { console.log(r); });
 */
exports.detect = function detect(config, opts, finished) {
	if (typeof config === 'function') {
		// 1 arg (function)
		finished = config;
		config = {};
		opts = {};
	} else if (typeof opts === 'function') {
		// 2 args (object, function)
		finished = opts;
		opts = {};
	} else {
		opts || (opts = {});
	}

	if (cache && !opts.bypassCache) return finished(cache);

	var exe = process.platform === 'win32' ? '.exe' : '',
		javaHome = (config.get ? config.get('java.home', process.env.JAVA_HOME) : (config.java && config.java.home || process.env.JAVA_HOME)) || null,
		jdkPaths = [],
		requiredTools = ['java', 'javac', 'keytool', 'jarsigner', 'jar'],
		executables = {},
		results = {
			jdks: {},
			home: null,
			version: null,
			build: null,
			executables: executables,
			issues: []
		};

	function isJDK(dir) {
		if (fs.existsSync(path.join(dir, 'bin', 'javac' + exe)) && fs.existsSync(path.join(dir, 'lib', 'dt.jar'))) {
			// try to find the jvm lib
			var libjvmLocations = [];

			if (process.platform === 'linux') {
				if (process.arch === 'x64') {
					libjvmLocations = [
						'lib/amd64/client/libjvm.so',
						'lib/amd64/server/libjvm.so',
						'jre/lib/amd64/client/libjvm.so',
						'jre/lib/amd64/server/libjvm.so'
					];
				} else {
					libjvmLocations = [
						'lib/i386/client/libjvm.so',
						'lib/i386/server/libjvm.so',
						'jre/lib/i386/client/libjvm.so',
						'jre/lib/i386/server/libjvm.so'
					];
				}
			} else if (process.platform === 'darwin') {
				libjvmLocations = [
					'jre/lib/server/libjvm.dylib',
					'../Libraries/libjvm.dylib'
				];
			} else if (process.platform === 'win32') {
				libjvmLocations = [
					'jre/bin/server/jvm.dll',
					'jre/bin/client/jvm.dll'
				];
			}

			return libjvmLocations.some(function (p) {
				return fs.existsSync(path.resolve(dir, p));
			});
		}
	}

	// sanity check the java home
	if (javaHome) {
		javaHome = afs.resolvePath(javaHome);
		if (fs.existsSync(javaHome)) {
			isJDK(javaHome) && jdkPaths.push(javaHome);
		} else {
			javaHome = null;
		}
	}
	results.home = javaHome;

	async.series([
		function detectLinux(next) {
			if (process.platform !== 'linux') return next();

			findExecutable('javac', function (err, p) {
				if (!err && p) {
					p = path.dirname(path.dirname(p));
					jdkPaths.indexOf(p) === -1 && isJDK(p) && jdkPaths.push(p);
				}
				next();
			});
		},
		function detectOSX(next) {
			if (process.platform !== 'darwin') return next();

			run('/usr/libexec/java_home', function (err, stdout, stderr) {
				if (!err) {
					var p = stdout.trim();
					p && jdkPaths.indexOf(p) === -1 && isJDK(p) && jdkPaths.push(p);
				}

				findExecutable('javac', function (err, p) {
					if (!err && p) {
						p = fs.realpathSync(path.dirname(path.dirname(p)));
						jdkPaths.indexOf(p) === -1 && isJDK(p) && jdkPaths.push(p);
					}

					['/Library/Java/JavaVirtualMachines', '/System/Library/Java/JavaVirtualMachines'].forEach(function (parent) {
						fs.existsSync(parent) && fs.readdirSync(parent).forEach(function (name) {
							var p = path.join(parent, name, 'Contents', 'Home');
							jdkPaths.indexOf(p) === -1 && isJDK(p) && jdkPaths.push(p);
						});
					});

					next();
				});
			});
		},
		function detectWin(next) {
			if (process.platform !== 'win32') return next();

			['%SystemDrive%', '%ProgramFiles%', '%ProgramFiles(x86)%', '%ProgramW6432%', '~'].forEach(function (dir) {
				dir = afs.resolvePath(dir);
				fs.existsSync(dir) && fs.readdirSync(dir).forEach(function (name) {
					var subdir = path.join(dir, name);
					isJDK(subdir) && jdkPaths.indexOf(subdir) === -1 && jdkPaths.push(subdir);
				});
			});

			next();
		}
	], function () {
		async.parallel(jdkPaths.map(function (home) {
			return function (next) {
				var jdkInfo = {
						home: home,
						version: null,
						build: null,
						executables: {}
					},
					missingTools = [];

				requiredTools.forEach(function (cmd) {
				    var p = path.join(home, 'bin', cmd + exe);
					if (fs.existsSync(p)) {
						jdkInfo.executables[cmd] = fs.realpathSync(p);
					} else {
						missingTools.push(cmd);
					}
				});

				if (missingTools.length) {
					results.issues.push({
						id: 'JDK_MISSING_PROGRAMS',
						type: 'warning',
						message: __('JDK (Java Development Kit) at %s missing required programs: %s', home, '__' + missingTools.join(', ') + '__') + '\n'
							+ (process.env.JAVA_HOME
								? __('Please verify your __JAVA_HOME__ environment variable is correctly set to the JDK install location.') + '\n' +
								  __('__JAVA_HOME__ is currently set to "%s".', process.env.JAVA_HOME) + '\n'
								: __('Please set the __JAVA_HOME__ environment variable to the JDK install location and not the JRE (Java Runtime Environment).') + '\n'
							)
							+ __('The __JAVA_HOME__ environment variable must point to the JDK and not the JRE (Java Runtime Environment).') + '\n'
							+ __('You may want to reinstall the JDK by downloading it from %s.',
								'__http://appcelerator.com/jdk__')
					});
					return next();
				}

				function finalize(str, arch) {
					var m = str !== null && str.match(/javac (.+)_(.+)/);
					if (m) {
						jdkInfo.version = m[1];
						jdkInfo.build = m[2];
						jdkInfo.architecture = arch;
						next(null, jdkInfo);
					} else {
						next();
					}
				}

				// get the version
				// try the 64-bit version first
				run(jdkInfo.executables.javac, ['-version', '-d64'], function (code, stdout, stderr) {
					if (!code) {
						// 64-bit version
						return finalize(stderr, '64bit');
					}

					// try the 32-bit version
					run(jdkInfo.executables.javac, '-version', function (code, stdout, stderr) {
						finalize(code ? null : stderr, '32bit');
					});
				});
			};
		}), function (err, jdks) {
			if (jdks.length) {
				jdks.forEach(function (jdk) {
					results.jdks[jdk.version + '_' + jdk.build] = jdk;

					// only add the first jdk as it's probably the JAVA_HOME based one
					if (results.version === null) {
						mix(results, jdk);
					}
				});
			} else {
				results.issues.push({
					id: 'JDK_NOT_INSTALLED',
					type: 'error',
					message: __('JDK (Java Development Kit) not installed.') + '\n'
						+ __('If you already have installed the JDK, verify your __JAVA_HOME__ environment variable is correctly set.') + '\n'
						+ __('The JDK is required for Titanium and must be manually downloaded and installed from %s.',
							'__http://appcelerator.com/jdk__')
				});
			}

			finished(cache = results);
		});
	});
};


text:
typedef struct {
	int numSamples;
	short *pData;
} wavedata_t;

#define AUDIOMIXER_MAX_VOLUME 100

_Bool stopping;

int rock_status;
wavedata_t rock1[3];

void nanoSleepFunc(int a, int b);

// init() must be called before any other functions,
// cleanup() must be called last to stop playback threads and free memory.
void initBeat();
void AudioMixer_reset();
void AudioMixer_init(void);
void AudioMixer_cleanup(void);
long AudioMixer_getSleepTime(void);

// Read the contents of a wave file into the pSound structure. Note that
// the pData pointer in this structure will be dynamically allocated in
// readWaveFileIntoMemory(), and is freed by calling freeWaveFileData().
void AudioMixer_readWaveFileIntoMemory(char *fileName, wavedata_t *pSound);
void AudioMixer_freeWaveFileData(wavedata_t *pSound);

// Queue up another sound bite to play as soon as possible.
void AudioMixer_queueSound(wavedata_t *pSound);

// Get/set the volume.
// setVolume() function posted by StackOverflow user "trenki" at:
// http://stackoverflow.com/questions/6787318/set-alsa-master-volume-from-c-code
int  AudioMixer_getVolume();
void AudioMixer_setVolume(int newVolume);

int AudioMixer_getBPM();
void AudioMixer_setBPM(int newBPM);

char* AudioMixer_getBeat(int beat_num);

void* playbackThread(void* arg);

#endif


text:
package com.simiacryptus.util.binary;

/**
 * The type Interval.
 */
public class Interval {
  /**
   * The Start.
   */
  public final long start;
  /**
   * The Max.
   */
  public final long max;
  /**
   * The Length.
   */
  public final long length;

  /**
   * Instantiates a new Interval.
   *
   * @param start  the start
   * @param length the length
   * @param max    the max
   */
  public Interval(long start, long length, long max) {
    super();
    if (0 >= max) throw new IllegalArgumentException();
    if (0 > start || max <= start) throw new IllegalArgumentException();
    if (0 >= length) throw new IllegalArgumentException();
    if (max < start + length) throw new IllegalArgumentException();
    this.start = start;
    this.max = max;
    this.length = length;
  }

  /**
   * End long.
   *
   * @return the long
   */
  public long end() {
    return start + length;
  }

  /**
   * To bits bits.
   *
   * @return the bits
   */
  public Bits toBits() {
    int peekBits = (int) Math.ceil(Math.log(max) / Math.log(2)) + 4;
    Bits startBits = Bits.divide(start, max, peekBits).padRight(peekBits);
    Bits endBits = Bits.divide(end(), max, peekBits).padRight(peekBits);
    for (int i = 0; i < peekBits; i++) {
      long a = startBits.range(0, i).toLong();
      long b = endBits.range(0, i).toLong();
      if (b - a > 1) {
        Bits bits = new Bits(a + 1, i);
        assert (Bits.ZERO.equals(bits.range(0, 1)));
        return bits.range(1);
      }
    }
    throw new RuntimeException();
  }

  @Override
  public String toString() {
    final StringBuffer sb = new StringBuffer("Interval{");
    sb.append("start=").append(start);
    sb.append(", length=").append(length);
    sb.append(", max=").append(max);
    sb.append('}');
    return sb.toString();
  }
}


text:
package com.seifernet.shadowsatyr.persistence.dto;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table( name="permission" )
public class Permission implements Serializable{

	private static final long serialVersionUID = 1L;

	@Id
	private Long id;

	@Column( nullable = false, length = 500 )
	private String permission;

	@Column( nullable = false, length = 500 )
	private String description;

	/**
	 * @return the id
	 */
	public Long getId( ) {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId( Long id ) {
		this.id = id;
	}

	/**
	 * @return the permission
	 */
	public String getPermission( ) {
		return permission;
	}

	/**
	 * @param permission the permission to set
	 */
	public void setPermission( String permission ) {
		this.permission = permission;
	}

	/**
	 * @return the description
	 */
	public String getDescription( ) {
		return description;
	}

	/**
	 * @param description the description to set
	 */
	public void setDescription( String description ) {
		this.description = description;
	}
}


text:
namespace HuUtils.DataSynchronization
{
    partial class DSForm3
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.txtMsg = new System.Windows.Forms.TextBox();
            this.btnSend = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // txtMsg
            //
            this.txtMsg.Location = new System.Drawing.Point(52, 57);
            this.txtMsg.Name = "txtMsg";
            this.txtMsg.Size = new System.Drawing.Size(96, 21);
            this.txtMsg.TabIndex = 3;
            //
            // btnSend
            //
            this.btnSend.Location = new System.Drawing.Point(167, 57);
            this.btnSend.Name = "btnSend";
            this.btnSend.Size = new System.Drawing.Size(96, 21);
            this.btnSend.TabIndex = 2;
            this.btnSend.Text = "同步";
            this.btnSend.UseVisualStyleBackColor = true;
            this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
            //
            // DSForm3
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(337, 159);
            this.Controls.Add(this.txtMsg);
            this.Controls.Add(this.btnSend);
            this.Name = "DSForm3";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox txtMsg;
        private System.Windows.Forms.Button btnSend;
    }
}


text: var app = angular.module("contactsApp", ['ui.bootstrap']);


text:
using System.Text;

namespace TuxedoBerries.ScenePanel
{
	/// <summary>
	/// Scene file entity.
	/// </summary>
	public class SceneFileEntity : ISceneFileEntity
	{

		private string _name;
		private string _fullPath;
		private string _guid;

		public SceneFileEntity () : this ("", "") { }

		public SceneFileEntity (string name) : this (name, "") { }

		public SceneFileEntity (string name, string fullPath)
		{
			_name = name;
			_fullPath = fullPath;
		}

		/// <summary>
		/// Gets the name of the scene.
		/// </summary>
		/// <value>The name.</value>
		public string Name {
			get {
				return _name;
			}
			set {
				_name = value;
			}
		}

		/// <summary>
		/// Gets the full path of the scene.
		/// </summary>
		/// <value>The full path.</value>
		public string FullPath {
			get {
				return _fullPath;
			}
			set {
				_fullPath = value;
			}
		}

		/// <summary>
		/// Gets the GUID.
		/// </summary>
		/// <value>The GUID.</value>
		public string GUID {
			get {
				return _guid;
			}
			set {
				_guid = value;
			}
		}

		/// <summary>
		/// Returns a <see cref="System.String"/> that represents the current <see cref="TuxedoBerries.ScenePanel.SceneFileEntity"/>.
		/// </summary>
		/// <returns>A <see cref="System.String"/> that represents the current <see cref="TuxedoBerries.ScenePanel.SceneFileEntity"/>.</returns>
		public override string ToString ()
		{
			var builder = new StringBuilder ();
			builder.Append ("{");
			// Name
			builder.Append ("\"name\":");
			builder.Append ("\"");
			builder.Append (Name);
			builder.Append ("\",");
			// Full Path
			builder.Append ("\"full_path\":");
			builder.Append ("\"");
			builder.Append (FullPath);
			builder.Append ("\",");
			// GUID
			builder.Append ("\"guid\":");
			builder.Append ("\"");
			builder.Append (GUID);
			builder.Append ("\"");

			builder.Append ("}");
			return builder.ToString ();
		}

		public static SceneFileEntity GetCurrent ()
		{
			var currentScenePath = SceneMainPanelUtility.CurrentActiveScene;
			var currentName = System.IO.Path.GetFileNameWithoutExtension (currentScenePath);
			return new SceneFileEntity (currentName, currentScenePath);
		}
	}
}


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

namespace LazyLoading.ValueHolder
{
    public class ValueHolder<T>
    {
        private T value;

        private IValueLoader<T> loader;

        public T Value
        {
            get
            {
                if (value == null)
                {
                    value = loader.load();
                }

                return value;
            }
        }

        public ValueHolder(IValueLoader<T> loader)
        {
            this.loader = loader;
        }
    }
}


text:
from __future__ import absolute_import, division, print_function, unicode_literals

import lib.bitcoin.core
from lib.bitcoin.core import CoreMainParams, CoreTestNetParams, CoreRegTestParams
from lib.bitcoin.core import coreparams

# Note that setup.py can break if __init__.py imports any external
# dependencies, as these might not be installed when setup.py runs. In this
# case __version__ could be moved to a separate version.py and imported here.
__version__ = '0.5.1-SNAPSHOT'

class MainParams(CoreMainParams):
    MESSAGE_START = b'\xf9\xbe\xb4\xd9'
    DEFAULT_PORT = 8877
    RPC_PORT = 8878
    DNS_SEEDS = (("91.230.123.11", "91.230.123.11"))
    BASE58_PREFIXES = {'PUBKEY_ADDR':12,
                       'SCRIPT_ADDR':8,
                       'SECRET_KEY' :128}

class TestNetParams(CoreTestNetParams):
    MESSAGE_START = b'\x0b\x11\x09\x07'
    DEFAULT_PORT = 23235
    RPC_PORT = 23245
    DNS_SEEDS = ()
    BASE58_PREFIXES = {'PUBKEY_ADDR':13,
                       'SCRIPT_ADDR':9,
                       'SECRET_KEY' :239}

class RegTestParams(CoreRegTestParams):
    MESSAGE_START = b'\xfa\xbf\xb5\xda'
    DEFAULT_PORT = 18444
    RPC_PORT = 18332
    DNS_SEEDS = ()
    BASE58_PREFIXES = {'PUBKEY_ADDR':111,
                       'SCRIPT_ADDR':196,
                       'SECRET_KEY' :239}

"""Master global setting for what chain params we're using.

However, don't set this directly, use SelectParams() instead so as to set the
lib.bitcoin.core.params correctly too.
"""
params = coreparams = MainParams()
#params = MainParams()

def SelectParams(name):
    """Select the chain parameters to use

    name is one of 'mainnet', 'testnet', or 'regtest'

    Default chain is 'mainnet'
    """
    global params
    lib.bitcoin.core._SelectCoreParams(name)
    if name == 'mainnet':
        params = coreparams = MainParams()
    elif name == 'testnet':
        params = coreparams = TestNetParams()
    elif name == 'regtest':
        params = coreparams = RegTestParams()
    else:
        raise ValueError('Unknown chain %r' % name)


text:
package feign;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.SocketPolicy;
import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule;

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

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import feign.Target.HardCodedTarget;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import feign.codec.StringDecoder;

import static feign.Util.UTF_8;
import static feign.assertj.MockWebServerAssertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class FeignTest {

  @Rule
  public final ExpectedException thrown = ExpectedException.none();
  @Rule
  public final MockWebServerRule server = new MockWebServerRule();

  @Test
  public void iterableQueryParams() throws Exception {
    server.enqueue(new MockResponse().setBody("foo"));

    TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort());

    api.queryParams("user", Arrays.asList("apple", "pear"));

    assertThat(server.takeRequest())
        .hasPath("/?1=user&2=apple&2=pear");
  }

  @Test
  public void postTemplateParamsResolve() throws Exception {
    server.enqueue(new MockResponse().setBody("foo"));

    TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort());

    api.login("netflix", "denominator", "password");

    assertThat(server.takeRequest())
        .hasBody(
            "{\"customer_name\": \"netflix\", \"user_name\": \"denominator\", \"password\": \"password\"}");
  }

  @Test
  public void responseCoercesToStringBody() throws Exception {
    server.enqueue(new MockResponse().setBody("foo"));

    TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort());

    Response response = api.response();
    assertTrue(response.body().isRepeatable());
    assertEquals("foo", response.body().toString());
  }

  @Test
  public void postFormParams() throws Exception {
    server.enqueue(new MockResponse().setBody("foo"));

    TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort());

    api.form("netflix", "denominator", "password");

    assertThat(server.takeRequest())
        .hasBody(
            "{\"customer_name\":\"netflix\",\"user_name\":\"denominator\",\"password\":\"password\"}");
  }

  @Test
  public void postBodyParam() throws Exception {
    server.enqueue(new MockResponse().setBody("foo"));

    TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort());

    api.body(Arrays.asList("netflix", "denominator", "password"));

    assertThat(server.takeRequest())
        .hasHeaders("Content-Length: 32")
        .hasBody("[netflix, denominator, password]");
  }

  /**
   * The type of a parameter value may not be the desired type to encode as. Prefer the interface
   * type.
   */
  @Test
  public void bodyTypeCorrespondsWithParameterType() throws Exception {
    server.enqueue(new MockResponse().setBody("foo"));

    final AtomicReference<Type> encodedType = new AtomicReference<Type>();
    TestInterface api = new TestInterfaceBuilder()
        .encoder(new Encoder.Default() {
          @Override
          public void encode(Object object, Type bodyType, RequestTemplate template) {
            encodedType.set(bodyType);
          }
        })
        .target("http://localhost:" + server.getPort());

    api.body(Arrays.asList("netflix", "denominator", "password"));

    server.takeRequest();

    assertThat(encodedType.get()).isEqualTo(new TypeToken<List<String>>() {
    }.getType());
  }

  @Test
  public void postGZIPEncodedBodyParam() throws Exception {
    server.enqueue(new MockResponse().setBody("foo"));

    TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort());

    api.gzipBody(Arrays.asList("netflix", "denominator", "password"));

    assertThat(server.takeRequest())
        .hasNoHeaderNamed("Content-Length")
        .hasGzippedBody("[netflix, denominator, password]".getBytes(UTF_8));
  }

  @Test
  public void singleInterceptor() throws Exception {
    server.enqueue(new MockResponse().setBody("foo"));

    TestInterface api = new TestInterfaceBuilder()
        .requestInterceptor(new ForwardedForInterceptor())
        .target("http://localhost:" + server.getPort());

    api.post();

    assertThat(server.takeRequest())
        .hasHeaders("X-Forwarded-For: origin.host.com");
  }

  @Test
  public void multipleInterceptor() throws Exception {
    server.enqueue(new MockResponse().setBody("foo"));

    TestInterface api = new TestInterfaceBuilder()
        .requestInterceptor(new ForwardedForInterceptor())
        .requestInterceptor(new UserAgentInterceptor())
        .target("http://localhost:" + server.getPort());

    api.post();

    assertThat(server.takeRequest()).hasHeaders("X-Forwarded-For: origin.host.com",
                                                "User-Agent: Feign");
  }

  @Test
  public void customExpander() throws Exception {
    server.enqueue(new MockResponse());

    TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort());

    api.expand(new Date(1234l));

    assertThat(server.takeRequest())
        .hasPath("/?date=1234");
  }

  @Test
  public void toKeyMethodFormatsAsExpected() throws Exception {
    assertEquals("TestInterface#post()",
                 Feign.configKey(TestInterface.class.getDeclaredMethod("post")));
    assertEquals("TestInterface#uriParam(String,URI,String)",
                 Feign.configKey(TestInterface.class
                                     .getDeclaredMethod("uriParam", String.class, URI.class,
                                                        String.class)));
  }

  @Test
  public void canOverrideErrorDecoder() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(404).setBody("foo"));
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("zone not found");

    TestInterface api = new TestInterfaceBuilder()
        .errorDecoder(new IllegalArgumentExceptionOn404())
        .target("http://localhost:" + server.getPort());

    api.post();
  }

  @Test
  public void retriesLostConnectionBeforeRead() throws Exception {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START));
    server.enqueue(new MockResponse().setBody("success!"));

    TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort());

    api.post();

    assertEquals(2, server.getRequestCount());
  }

  @Test
  public void overrideTypeSpecificDecoder() throws Exception {
    server.enqueue(new MockResponse().setBody("success!"));

    TestInterface api = new TestInterfaceBuilder()
        .decoder(new Decoder() {
          @Override
          public Object decode(Response response, Type type) {
            return "fail";
          }
        }).target("http://localhost:" + server.getPort());

    assertEquals(api.post(), "fail");
  }

  /**
   * when you must parse a 2xx status to determine if the operation succeeded or not.
   */
  @Test
  public void retryableExceptionInDecoder() throws Exception {
    server.enqueue(new MockResponse().setBody("retry!"));
    server.enqueue(new MockResponse().setBody("success!"));

    TestInterface api = new TestInterfaceBuilder()
        .decoder(new StringDecoder() {
          @Override
          public Object decode(Response response, Type type) throws IOException {
            String string = super.decode(response, type).toString();
            if ("retry!".equals(string)) {
              throw new RetryableException(string, null);
            }
            return string;
          }
        }).target("http://localhost:" + server.getPort());

    assertEquals(api.post(), "success!");
    assertEquals(2, server.getRequestCount());
  }

  @Test
  public void doesntRetryAfterResponseIsSent() throws Exception {
    server.enqueue(new MockResponse().setBody("success!"));
    thrown.expect(FeignException.class);
    thrown.expectMessage("timeout reading POST http://");

    TestInterface api = new TestInterfaceBuilder()
        .decoder(new Decoder() {
          @Override
          public Object decode(Response response, Type type) throws IOException {
            throw new IOException("timeout");
          }
        }).target("http://localhost:" + server.getPort());

    api.post();
  }

  @Test
  public void okIfDecodeRootCauseHasNoMessage() throws Exception {
    server.enqueue(new MockResponse().setBody("success!"));
    thrown.expect(DecodeException.class);

    TestInterface api = new TestInterfaceBuilder()
        .decoder(new Decoder() {
          @Override
          public Object decode(Response response, Type type) throws IOException {
            throw new RuntimeException();
          }
        }).target("http://localhost:" + server.getPort());

    api.post();
  }

  @Test
  public void okIfEncodeRootCauseHasNoMessage() throws Exception {
    server.enqueue(new MockResponse().setBody("success!"));
    thrown.expect(EncodeException.class);

    TestInterface api = new TestInterfaceBuilder()
        .encoder(new Encoder() {
          @Override
          public void encode(Object object, Type bodyType, RequestTemplate template) {
            throw new RuntimeException();
          }
        }).target("http://localhost:" + server.getPort());

    api.body(Arrays.asList("foo"));
  }

  @Test
  public void equalsHashCodeAndToStringWork() {
    Target<TestInterface>
        t1 =
        new HardCodedTarget<TestInterface>(TestInterface.class, "http://localhost:8080");
    Target<TestInterface>
        t2 =
        new HardCodedTarget<TestInterface>(TestInterface.class, "http://localhost:8888");
    Target<OtherTestInterface> t3 =
        new HardCodedTarget<OtherTestInterface>(OtherTestInterface.class, "http://localhost:8080");
    TestInterface i1 = Feign.builder().target(t1);
    TestInterface i2 = Feign.builder().target(t1);
    TestInterface i3 = Feign.builder().target(t2);
    OtherTestInterface i4 = Feign.builder().target(t3);

    assertThat(i1)
        .isEqualTo(i2)
        .isNotEqualTo(i3)
        .isNotEqualTo(i4);

    assertThat(i1.hashCode())
        .isEqualTo(i2.hashCode())
        .isNotEqualTo(i3.hashCode())
        .isNotEqualTo(i4.hashCode());

    assertThat(i1.toString())
        .isEqualTo(i2.toString())
        .isNotEqualTo(i3.toString())
        .isNotEqualTo(i4.toString());

    assertThat(t1)
        .isNotEqualTo(i1);

    assertThat(t1.hashCode())
        .isEqualTo(i1.hashCode());

    assertThat(t1.toString())
        .isEqualTo(i1.toString());
  }

  @Test
  public void decodeLogicSupportsByteArray() throws Exception {
    byte[] expectedResponse = {12, 34, 56};
    server.enqueue(new MockResponse().setBody(expectedResponse));

    OtherTestInterface
        api =
        Feign.builder().target(OtherTestInterface.class, "http://localhost:" + server.getPort());

    assertThat(api.binaryResponseBody())
        .containsExactly(expectedResponse);
  }

  @Test
  public void encodeLogicSupportsByteArray() throws Exception {
    byte[] expectedRequest = {12, 34, 56};
    server.enqueue(new MockResponse());

    OtherTestInterface
        api =
        Feign.builder().target(OtherTestInterface.class, "http://localhost:" + server.getPort());

    api.binaryRequestBody(expectedRequest);

    assertThat(server.takeRequest())
        .hasBody(expectedRequest);
  }

  interface TestInterface {

    @RequestLine("POST /")
    Response response();

    @RequestLine("POST /")
    String post();

    @RequestLine("POST /")
    @Body("%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D")
    void login(
        @Param("customer_name") String customer, @Param("user_name") String user,
        @Param("password") String password);

    @RequestLine("POST /")
    void body(List<String> contents);

    @RequestLine("POST /")
    @Headers("Content-Encoding: gzip")
    void gzipBody(List<String> contents);

    @RequestLine("POST /")
    void form(
        @Param("customer_name") String customer, @Param("user_name") String user,
        @Param("password") String password);

    @RequestLine("GET /{1}/{2}")
    Response uriParam(@Param("1") String one, URI endpoint, @Param("2") String two);

    @RequestLine("GET /?1={1}&2={2}")
    Response queryParams(@Param("1") String one, @Param("2") Iterable<String> twos);

    @RequestLine("POST /?date={date}")
    void expand(@Param(value = "date", expander = DateToMillis.class) Date date);

    class DateToMillis implements Param.Expander {

      @Override
      public String expand(Object value) {
        return String.valueOf(((Date) value).getTime());
      }
    }
  }

  interface OtherTestInterface {

    @RequestLine("POST /")
    String post();

    @RequestLine("POST /")
    byte[] binaryResponseBody();

    @RequestLine("POST /")
    void binaryRequestBody(byte[] contents);
  }

  static class ForwardedForInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
      template.header("X-Forwarded-For", "origin.host.com");
    }
  }

  static class UserAgentInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
      template.header("User-Agent", "Feign");
    }
  }

  static class IllegalArgumentExceptionOn404 extends ErrorDecoder.Default {

    @Override
    public Exception decode(String methodKey, Response response) {
      if (response.status() == 404) {
        return new IllegalArgumentException("zone not found");
      }
      return super.decode(methodKey, response);
    }
  }

  static final class TestInterfaceBuilder {

    private final Feign.Builder delegate = new Feign.Builder()
        .decoder(new Decoder.Default())
        .encoder(new Encoder() {
          @Override
          public void encode(Object object, Type bodyType, RequestTemplate template) {
            if (object instanceof Map) {
              template.body(new Gson().toJson(object));
            } else {
              template.body(object.toString());
            }
          }
        });

    TestInterfaceBuilder requestInterceptor(RequestInterceptor requestInterceptor) {
      delegate.requestInterceptor(requestInterceptor);
      return this;
    }

    TestInterfaceBuilder encoder(Encoder encoder) {
      delegate.encoder(encoder);
      return this;
    }

    TestInterfaceBuilder decoder(Decoder decoder) {
      delegate.decoder(decoder);
      return this;
    }

    TestInterfaceBuilder errorDecoder(ErrorDecoder errorDecoder) {
      delegate.errorDecoder(errorDecoder);
      return this;
    }

    TestInterface target(String url) {
      return delegate.target(TestInterface.class, url);
    }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Zend_Service_ReCaptcha - Zend Framework Manual</title>

                    Zend_Service_Nirvanix

Zend_Service

                        Programmer's Reference Guide

Zend_Service_ShortUrl

Zend_Service_ReCaptcha

Introduction

            Zend_Service_ReCaptcha provides a client for the » reCAPTCHA Web Service.
            Per the reCAPTCHA site, "reCAPTCHA is a free CAPTCHA service that
            helps to digitize books." Each reCAPTCHA requires the user to input
            two words, the first of which is the actual CAPTCHA, and the second
            of which is a word from some scanned text that Optical Character
            Recognition (OCR) software has been unable to identify.
            The assumption is that if a user correctly provides the first
            word, the second is likely correctly entered as well, and can be
            used to improve OCR software for digitizing books.

            In order to use the reCAPTCHA service, you will need to » sign up for an
                account and register one or more domains with the
            service in order to generate public and private keys.

Simplest use

            Instantiate a Zend_Service_ReCaptcha object, passing it
            your public and private keys:

Example #1 Creating an instance of the reCAPTCHA service

$recaptcha = new Zend_Service_ReCaptcha($pubKey, $privKey);

            To render the reCAPTCHA, simply call the  getHTML()
            method:

Example #2 Displaying the reCAPTCHA

echo $recaptcha->getHTML();

            When the form is submitted, you should receive two fields,
            'recaptcha_challenge_field' and 'recaptcha_response_field'. Pass
            these to the reCAPTCHA object's  verify() method:

Example #3 Verifying the form fields

$result = $recaptcha->verify(

    $_POST['recaptcha_challenge_field'],

    $_POST['recaptcha_response_field']

);

            Once you have the result, test against it to see if it is valid. The
            result is a Zend_Service_ReCaptcha_Response object,
            which provides an  isValid() method.

Example #4 Validating the reCAPTCHA

if (!$result->isValid()) {

    // Failed validation

}

            It is even simpler to use the reCAPTCHA
            Zend_Captcha adapter, or to use that adapter as a
            backend for the CAPTCHA form
                element. In each case, the details of rendering and
            validating the reCAPTCHA are automated for you.

Hiding email addresses

            Zend_Service_ReCaptcha_MailHide can be used to hide email
            addresses. It will replace a part of an email address with a link that opens a popup
            window with a reCAPTCHA challenge. Solving the challenge will reveal the complete
            email address.

            In order to use this component you will need
            » an account to generate
            public and private keys for the mailhide <acronym class="acronym">API</acronym>.

Example #5 Using the mail hide component

// The mail address we want to hide

$mail = 'mail@example.com';

// Create an instance of the mailhide component, passing it your public

// and private keys, as well as the mail address you want to hide

$mailHide = new Zend_Service_ReCaptcha_MailHide();

$mailHide->setPublicKey($pubKey);

$mailHide->setPrivateKey($privKey);

$mailHide->setEmail($mail);

// Display it

print($mailHide);

            The example above will display "m...@example.com" where "..." has a link that opens up
            a popup window with a reCAPTCHA challenge.

            The public key, private key, and the email address can also be specified in the
            constructor of the class. A fourth argument also exists that enables you to set some
            options for the component. The available options are listed in the following table:

Zend_Service_ReCaptcha_MailHide options

                            Option
                            Description
                            Expected Values
                            Default Value

                            linkTitle
                            The title attribute of the link
                            string
                            'Reveal this e-mail address'

                            linkHiddenText
                            The text that includes the popup link
                            string
                            '...'

                            popupWidth
                            The width of the popup window
                            int
                            500

                            popupHeight
                            The height of the popup window
                            int
                            300

            The configuration options can be set by sending them as the fourth argument to the
            constructor or by calling  setOptions($options), which takes
            an associative array or an instance of Zend_Config.

Example #6 Generating many hidden email addresses

// Create an instance of the mailhide component, passing it your public

// and private keys, as well as some configuration options

$mailHide = new Zend_Service_ReCaptcha_MailHide();

$mailHide->setPublicKey($pubKey);

$mailHide->setPrivateKey($privKey);

$mailHide->setOptions(array(

    'linkTitle' => 'Click me',

    'linkHiddenText' => '+++++',

));

// The mail addresses we want to hide

$mailAddresses = array(

    'mail@example.com',

    'johndoe@example.com',

    'janedoe@example.com',

);

foreach ($mailAddresses as $mail) {

    $mailHide->setEmail($mail);

    print($mailHide);

}

                    Zend_Service_Nirvanix

Zend_Service

                        Programmer's Reference Guide

Zend_Service_ShortUrl

Programmer's Reference Guide

Programmer's Reference Guide

Zend Framework Reference

Zend_Service

Введение

Zend_Service_Akismet

Zend_Service_Amazon

Zend_Service_Amazon_Ec2

Zend_Service_Amazon_Ec2: Instances

Zend_Service_Amazon_Ec2: Windows Instances

Zend_Service_Amazon_Ec2: Reserved Instances

Zend_Service_Amazon_Ec2: CloudWatch Monitoring

Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)

Zend_Service_Amazon_Ec2: Elastic Block Storage (EBS)

Zend_Service_Amazon_Ec2: Elastic IP Addresses

Zend_Service_Amazon_Ec2: Keypairs

Zend_Service_Amazon_Ec2: Regions and Availability Zones

Zend_Service_Amazon_Ec2: Security Groups

Zend_Service_Amazon_S3

Zend_Service_Amazon_Sqs

Zend_Service_Audioscrobbler

Zend_Service_Delicious

Zend_Service_DeveloperGarden

Zend_Service_Ebay

Zend_Service_Ebay_Finding

Zend_Service_Flickr

Zend_Service_LiveDocx

Zend_Service_Nirvanix

Zend_Service_ReCaptcha

Zend_Service_ShortUrl

Zend_Service_Simpy

Zend_Service_SlideShare

Zend_Service_StrikeIron

Zend_Service_StrikeIron: Bundled Services

Zend_Service_StrikeIron: Advanced Uses

Zend_Service_Technorati

Zend_Service_Twitter

Zend_Service_WindowsAzure

Zend_Service_WindowsAzure_Storage_Blob

Zend_Service_WindowsAzure_Diagnostics_Manager

Zend_Service_WindowsAzure_Storage_Queue

Zend_Service_WindowsAzure_Storage_Table

Zend_Service_Yahoo