text:
package examplepb

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api"

import (
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

type EmptyProto struct {
}

func (m *EmptyProto) Reset()                    { *m = EmptyProto{} }
func (m *EmptyProto) String() string            { return proto.CompactTextString(m) }
func (*EmptyProto) ProtoMessage()               {}
func (*EmptyProto) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{0} }

type NonEmptyProto struct {
	A string `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"`
	B string `protobuf:"bytes,2,opt,name=b" json:"b,omitempty"`
	C string `protobuf:"bytes,3,opt,name=c" json:"c,omitempty"`
}

func (m *NonEmptyProto) Reset()                    { *m = NonEmptyProto{} }
func (m *NonEmptyProto) String() string            { return proto.CompactTextString(m) }
func (*NonEmptyProto) ProtoMessage()               {}
func (*NonEmptyProto) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{1} }

func (m *NonEmptyProto) GetA() string {
	if m != nil {
		return m.A
	}
	return ""
}

func (m *NonEmptyProto) GetB() string {
	if m != nil {
		return m.B
	}
	return ""
}

func (m *NonEmptyProto) GetC() string {
	if m != nil {
		return m.C
	}
	return ""
}

type UnaryProto struct {
	Str string `protobuf:"bytes,1,opt,name=str" json:"str,omitempty"`
}

func (m *UnaryProto) Reset()                    { *m = UnaryProto{} }
func (m *UnaryProto) String() string            { return proto.CompactTextString(m) }
func (*UnaryProto) ProtoMessage()               {}
func (*UnaryProto) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{2} }

func (m *UnaryProto) GetStr() string {
	if m != nil {
		return m.Str
	}
	return ""
}

type NestedProto struct {
	A *UnaryProto `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"`
	B string      `protobuf:"bytes,2,opt,name=b" json:"b,omitempty"`
	C string      `protobuf:"bytes,3,opt,name=c" json:"c,omitempty"`
}

func (m *NestedProto) Reset()                    { *m = NestedProto{} }
func (m *NestedProto) String() string            { return proto.CompactTextString(m) }
func (*NestedProto) ProtoMessage()               {}
func (*NestedProto) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{3} }

func (m *NestedProto) GetA() *UnaryProto {
	if m != nil {
		return m.A
	}
	return nil
}

func (m *NestedProto) GetB() string {
	if m != nil {
		return m.B
	}
	return ""
}

func (m *NestedProto) GetC() string {
	if m != nil {
		return m.C
	}
	return ""
}

type SingleNestedProto struct {
	A *UnaryProto `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"`
}

func (m *SingleNestedProto) Reset()                    { *m = SingleNestedProto{} }
func (m *SingleNestedProto) String() string            { return proto.CompactTextString(m) }
func (*SingleNestedProto) ProtoMessage()               {}
func (*SingleNestedProto) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{4} }

func (m *SingleNestedProto) GetA() *UnaryProto {
	if m != nil {
		return m.A
	}
	return nil
}

func init() {
	proto.RegisterType((*EmptyProto)(nil), "grpc.gateway.examples.examplepb.EmptyProto")
	proto.RegisterType((*NonEmptyProto)(nil), "grpc.gateway.examples.examplepb.NonEmptyProto")
	proto.RegisterType((*UnaryProto)(nil), "grpc.gateway.examples.examplepb.UnaryProto")
	proto.RegisterType((*NestedProto)(nil), "grpc.gateway.examples.examplepb.NestedProto")
	proto.RegisterType((*SingleNestedProto)(nil), "grpc.gateway.examples.examplepb.SingleNestedProto")
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4

// Client API for FlowCombination service

type FlowCombinationClient interface {
	RpcEmptyRpc(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (*EmptyProto, error)
	RpcEmptyStream(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcEmptyStreamClient, error)
	StreamEmptyRpc(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyRpcClient, error)
	StreamEmptyStream(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyStreamClient, error)
	RpcBodyRpc(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (*EmptyProto, error)
	RpcPathSingleNestedRpc(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (*EmptyProto, error)
	RpcPathNestedRpc(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (*EmptyProto, error)
	RpcBodyStream(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcBodyStreamClient, error)
	RpcPathSingleNestedStream(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathSingleNestedStreamClient, error)
	RpcPathNestedStream(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathNestedStreamClient, error)
}

type flowCombinationClient struct {
	cc *grpc.ClientConn
}

func NewFlowCombinationClient(cc *grpc.ClientConn) FlowCombinationClient {
	return &flowCombinationClient{cc}
}

func (c *flowCombinationClient) RpcEmptyRpc(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) {
	out := new(EmptyProto)
	err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcEmptyRpc", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *flowCombinationClient) RpcEmptyStream(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcEmptyStreamClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[0], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/RpcEmptyStream", opts...)
	if err != nil {
		return nil, err
	}
	x := &flowCombinationRpcEmptyStreamClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type FlowCombination_RpcEmptyStreamClient interface {
	Recv() (*EmptyProto, error)
	grpc.ClientStream
}

type flowCombinationRpcEmptyStreamClient struct {
	grpc.ClientStream
}

func (x *flowCombinationRpcEmptyStreamClient) Recv() (*EmptyProto, error) {
	m := new(EmptyProto)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *flowCombinationClient) StreamEmptyRpc(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyRpcClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[1], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/StreamEmptyRpc", opts...)
	if err != nil {
		return nil, err
	}
	x := &flowCombinationStreamEmptyRpcClient{stream}
	return x, nil
}

type FlowCombination_StreamEmptyRpcClient interface {
	Send(*EmptyProto) error
	CloseAndRecv() (*EmptyProto, error)
	grpc.ClientStream
}

type flowCombinationStreamEmptyRpcClient struct {
	grpc.ClientStream
}

func (x *flowCombinationStreamEmptyRpcClient) Send(m *EmptyProto) error {
	return x.ClientStream.SendMsg(m)
}

func (x *flowCombinationStreamEmptyRpcClient) CloseAndRecv() (*EmptyProto, error) {
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	m := new(EmptyProto)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *flowCombinationClient) StreamEmptyStream(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyStreamClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[2], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/StreamEmptyStream", opts...)
	if err != nil {
		return nil, err
	}
	x := &flowCombinationStreamEmptyStreamClient{stream}
	return x, nil
}

type FlowCombination_StreamEmptyStreamClient interface {
	Send(*EmptyProto) error
	Recv() (*EmptyProto, error)
	grpc.ClientStream
}

type flowCombinationStreamEmptyStreamClient struct {
	grpc.ClientStream
}

func (x *flowCombinationStreamEmptyStreamClient) Send(m *EmptyProto) error {
	return x.ClientStream.SendMsg(m)
}

func (x *flowCombinationStreamEmptyStreamClient) Recv() (*EmptyProto, error) {
	m := new(EmptyProto)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *flowCombinationClient) RpcBodyRpc(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) {
	out := new(EmptyProto)
	err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcBodyRpc", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *flowCombinationClient) RpcPathSingleNestedRpc(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (*EmptyProto, error) {
	out := new(EmptyProto)
	err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathSingleNestedRpc", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *flowCombinationClient) RpcPathNestedRpc(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (*EmptyProto, error) {
	out := new(EmptyProto)
	err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathNestedRpc", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *flowCombinationClient) RpcBodyStream(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcBodyStreamClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[3], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/RpcBodyStream", opts...)
	if err != nil {
		return nil, err
	}
	x := &flowCombinationRpcBodyStreamClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type FlowCombination_RpcBodyStreamClient interface {
	Recv() (*EmptyProto, error)
	grpc.ClientStream
}

type flowCombinationRpcBodyStreamClient struct {
	grpc.ClientStream
}

func (x *flowCombinationRpcBodyStreamClient) Recv() (*EmptyProto, error) {
	m := new(EmptyProto)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *flowCombinationClient) RpcPathSingleNestedStream(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathSingleNestedStreamClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[4], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathSingleNestedStream", opts...)
	if err != nil {
		return nil, err
	}
	x := &flowCombinationRpcPathSingleNestedStreamClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type FlowCombination_RpcPathSingleNestedStreamClient interface {
	Recv() (*EmptyProto, error)
	grpc.ClientStream
}

type flowCombinationRpcPathSingleNestedStreamClient struct {
	grpc.ClientStream
}

func (x *flowCombinationRpcPathSingleNestedStreamClient) Recv() (*EmptyProto, error) {
	m := new(EmptyProto)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *flowCombinationClient) RpcPathNestedStream(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathNestedStreamClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[5], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathNestedStream", opts...)
	if err != nil {
		return nil, err
	}
	x := &flowCombinationRpcPathNestedStreamClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type FlowCombination_RpcPathNestedStreamClient interface {
	Recv() (*EmptyProto, error)
	grpc.ClientStream
}

type flowCombinationRpcPathNestedStreamClient struct {
	grpc.ClientStream
}

func (x *flowCombinationRpcPathNestedStreamClient) Recv() (*EmptyProto, error) {
	m := new(EmptyProto)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// Server API for FlowCombination service

type FlowCombinationServer interface {
	RpcEmptyRpc(context.Context, *EmptyProto) (*EmptyProto, error)
	RpcEmptyStream(*EmptyProto, FlowCombination_RpcEmptyStreamServer) error
	StreamEmptyRpc(FlowCombination_StreamEmptyRpcServer) error
	StreamEmptyStream(FlowCombination_StreamEmptyStreamServer) error
	RpcBodyRpc(context.Context, *NonEmptyProto) (*EmptyProto, error)
	RpcPathSingleNestedRpc(context.Context, *SingleNestedProto) (*EmptyProto, error)
	RpcPathNestedRpc(context.Context, *NestedProto) (*EmptyProto, error)
	RpcBodyStream(*NonEmptyProto, FlowCombination_RpcBodyStreamServer) error
	RpcPathSingleNestedStream(*SingleNestedProto, FlowCombination_RpcPathSingleNestedStreamServer) error
	RpcPathNestedStream(*NestedProto, FlowCombination_RpcPathNestedStreamServer) error
}

func RegisterFlowCombinationServer(s *grpc.Server, srv FlowCombinationServer) {
	s.RegisterService(&_FlowCombination_serviceDesc, srv)
}

func _FlowCombination_RpcEmptyRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(EmptyProto)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(FlowCombinationServer).RpcEmptyRpc(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcEmptyRpc",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(FlowCombinationServer).RpcEmptyRpc(ctx, req.(*EmptyProto))
	}
	return interceptor(ctx, in, info, handler)
}

func _FlowCombination_RpcEmptyStream_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(EmptyProto)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(FlowCombinationServer).RpcEmptyStream(m, &flowCombinationRpcEmptyStreamServer{stream})
}

type FlowCombination_RpcEmptyStreamServer interface {
	Send(*EmptyProto) error
	grpc.ServerStream
}

type flowCombinationRpcEmptyStreamServer struct {
	grpc.ServerStream
}

func (x *flowCombinationRpcEmptyStreamServer) Send(m *EmptyProto) error {
	return x.ServerStream.SendMsg(m)
}

func _FlowCombination_StreamEmptyRpc_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(FlowCombinationServer).StreamEmptyRpc(&flowCombinationStreamEmptyRpcServer{stream})
}

type FlowCombination_StreamEmptyRpcServer interface {
	SendAndClose(*EmptyProto) error
	Recv() (*EmptyProto, error)
	grpc.ServerStream
}

type flowCombinationStreamEmptyRpcServer struct {
	grpc.ServerStream
}

func (x *flowCombinationStreamEmptyRpcServer) SendAndClose(m *EmptyProto) error {
	return x.ServerStream.SendMsg(m)
}

func (x *flowCombinationStreamEmptyRpcServer) Recv() (*EmptyProto, error) {
	m := new(EmptyProto)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func _FlowCombination_StreamEmptyStream_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(FlowCombinationServer).StreamEmptyStream(&flowCombinationStreamEmptyStreamServer{stream})
}

type FlowCombination_StreamEmptyStreamServer interface {
	Send(*EmptyProto) error
	Recv() (*EmptyProto, error)
	grpc.ServerStream
}

type flowCombinationStreamEmptyStreamServer struct {
	grpc.ServerStream
}

func (x *flowCombinationStreamEmptyStreamServer) Send(m *EmptyProto) error {
	return x.ServerStream.SendMsg(m)
}

func (x *flowCombinationStreamEmptyStreamServer) Recv() (*EmptyProto, error) {
	m := new(EmptyProto)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func _FlowCombination_RpcBodyRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(NonEmptyProto)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(FlowCombinationServer).RpcBodyRpc(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcBodyRpc",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(FlowCombinationServer).RpcBodyRpc(ctx, req.(*NonEmptyProto))
	}
	return interceptor(ctx, in, info, handler)
}

func _FlowCombination_RpcPathSingleNestedRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(SingleNestedProto)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(FlowCombinationServer).RpcPathSingleNestedRpc(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathSingleNestedRpc",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(FlowCombinationServer).RpcPathSingleNestedRpc(ctx, req.(*SingleNestedProto))
	}
	return interceptor(ctx, in, info, handler)
}

func _FlowCombination_RpcPathNestedRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(NestedProto)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(FlowCombinationServer).RpcPathNestedRpc(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathNestedRpc",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(FlowCombinationServer).RpcPathNestedRpc(ctx, req.(*NestedProto))
	}
	return interceptor(ctx, in, info, handler)
}

func _FlowCombination_RpcBodyStream_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(NonEmptyProto)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(FlowCombinationServer).RpcBodyStream(m, &flowCombinationRpcBodyStreamServer{stream})
}

type FlowCombination_RpcBodyStreamServer interface {
	Send(*EmptyProto) error
	grpc.ServerStream
}

type flowCombinationRpcBodyStreamServer struct {
	grpc.ServerStream
}

func (x *flowCombinationRpcBodyStreamServer) Send(m *EmptyProto) error {
	return x.ServerStream.SendMsg(m)
}

func _FlowCombination_RpcPathSingleNestedStream_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(SingleNestedProto)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(FlowCombinationServer).RpcPathSingleNestedStream(m, &flowCombinationRpcPathSingleNestedStreamServer{stream})
}

type FlowCombination_RpcPathSingleNestedStreamServer interface {
	Send(*EmptyProto) error
	grpc.ServerStream
}

type flowCombinationRpcPathSingleNestedStreamServer struct {
	grpc.ServerStream
}

func (x *flowCombinationRpcPathSingleNestedStreamServer) Send(m *EmptyProto) error {
	return x.ServerStream.SendMsg(m)
}

func _FlowCombination_RpcPathNestedStream_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(NestedProto)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(FlowCombinationServer).RpcPathNestedStream(m, &flowCombinationRpcPathNestedStreamServer{stream})
}

type FlowCombination_RpcPathNestedStreamServer interface {
	Send(*EmptyProto) error
	grpc.ServerStream
}

type flowCombinationRpcPathNestedStreamServer struct {
	grpc.ServerStream
}

func (x *flowCombinationRpcPathNestedStreamServer) Send(m *EmptyProto) error {
	return x.ServerStream.SendMsg(m)
}

var _FlowCombination_serviceDesc = grpc.ServiceDesc{
	ServiceName: "grpc.gateway.examples.examplepb.FlowCombination",
	HandlerType: (*FlowCombinationServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "RpcEmptyRpc",
			Handler:    _FlowCombination_RpcEmptyRpc_Handler,
		},
		{
			MethodName: "RpcBodyRpc",
			Handler:    _FlowCombination_RpcBodyRpc_Handler,
		},
		{
			MethodName: "RpcPathSingleNestedRpc",
			Handler:    _FlowCombination_RpcPathSingleNestedRpc_Handler,
		},
		{
			MethodName: "RpcPathNestedRpc",
			Handler:    _FlowCombination_RpcPathNestedRpc_Handler,
		},
	},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "RpcEmptyStream",
			Handler:       _FlowCombination_RpcEmptyStream_Handler,
			ServerStreams: true,
		},
		{
			StreamName:    "StreamEmptyRpc",
			Handler:       _FlowCombination_StreamEmptyRpc_Handler,
			ClientStreams: true,
		},
		{
			StreamName:    "StreamEmptyStream",
			Handler:       _FlowCombination_StreamEmptyStream_Handler,
			ServerStreams: true,
			ClientStreams: true,
		},
		{
			StreamName:    "RpcBodyStream",
			Handler:       _FlowCombination_RpcBodyStream_Handler,
			ServerStreams: true,
		},
		{
			StreamName:    "RpcPathSingleNestedStream",
			Handler:       _FlowCombination_RpcPathSingleNestedStream_Handler,
			ServerStreams: true,
		},
		{
			StreamName:    "RpcPathNestedStream",
			Handler:       _FlowCombination_RpcPathNestedStream_Handler,
			ServerStreams: true,
		},
	},
	Metadata: "examples/examplepb/flow_combination.proto",
}

func init() { proto.RegisterFile("examples/examplepb/flow_combination.proto", fileDescriptor3) }

var fileDescriptor3 = []byte{
	// 656 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xbc, 0x96, 0x3f, 0x8f, 0x12, 0x4f,
	0x18, 0xc7, 0xf3, 0x70, 0xc9, 0x2f, 0xb9, 0xe1, 0xfe, 0x70, 0xcb, 0x2f, 0x08, 0x1c, 0x1e, 0x77,
	0xe3, 0x25, 0xe2, 0xbf, 0x5d, 0x82, 0xd5, 0x51, 0x9e, 0xd1, 0x92, 0x5c, 0xb8, 0xd8, 0x6c, 0x63,
	0x66, 0x87, 0x15, 0x48, 0x60, 0x67, 0x6e, 0x77, 0x0d, 0x5e, 0x08, 0x31, 0xb1, 0xb1, 0xb4, 0xf0,
	0x05, 0x58, 0x5a, 0xf9, 0x06, 0xec, 0xac, 0x6c, 0x4c, 0x2c, 0x4c, 0xec, 0xec, 0xec, 0x7c, 0x13,
	0x66, 0x67, 0x66, 0x77, 0x58, 0x05, 0x37, 0x18, 0xb1, 0xdb, 0x99, 0x79, 0x9e, 0x67, 0x3e, 0xf3,
	0x7d, 0xbe, 0x0f, 0x01, 0xdd, 0x70, 0x9f, 0x92, 0x31, 0x1f, 0xb9, 0x81, 0xa5, 0x3e, 0xb8, 0x63,
	0x3d, 0x1e, 0xb1, 0xc9, 0x23, 0xca, 0xc6, 0xce, 0xd0, 0x23, 0xe1, 0x90, 0x79, 0x26, 0xf7, 0x59,
	0xc8, 0x8c, 0x7a, 0xdf, 0xe7, 0xd4, 0xec, 0x93, 0xd0, 0x9d, 0x90, 0x4b, 0x33, 0xce, 0x33, 0x93,
	0xbc, 0x6a, 0xad, 0xcf, 0x58, 0x7f, 0xe4, 0x5a, 0x84, 0x0f, 0x2d, 0xe2, 0x79, 0x2c, 0x14, 0xd9,
	0x81, 0x4c, 0xc7, 0x5b, 0x08, 0xdd, 0x1f, 0xf3, 0xf0, 0xf2, 0x4c, 0xac, 0x4e, 0xd0, 0x76, 0x87,
	0x79, 0x7a, 0xc3, 0xd8, 0x42, 0x40, 0xca, 0x70, 0x08, 0x8d, 0xcd, 0x2e, 0x90, 0x68, 0xe5, 0x94,
	0x73, 0x72, 0xe5, 0x44, 0x2b, 0x5a, 0xde, 0x90, 0x2b, 0x8a, 0x0f, 0x10, 0x7a, 0xe8, 0x11, 0x5f,
	0xe5, 0x15, 0xd0, 0x46, 0x10, 0xfa, 0x2a, 0x33, 0xfa, 0xc4, 0x3d, 0x94, 0xef, 0xb8, 0x41, 0xe8,
	0xf6, 0x64, 0xc0, 0x49, 0x5c, 0x38, 0xdf, 0xba, 0x65, 0x66, 0x3c, 0xc1, 0xd4, 0x85, 0xb3, 0x28,
	0x3a, 0x68, 0xef, 0x7c, 0xe8, 0xf5, 0x47, 0xee, 0xdf, 0xb9, 0xab, 0xf5, 0x71, 0x17, 0xed, 0x3e,
	0x18, 0xb1, 0xc9, 0x3d, 0xad, 0xbb, 0xf1, 0x0c, 0xe5, 0xbb, 0x9c, 0x0a, 0x91, 0xba, 0x9c, 0x1a,
	0xd9, 0x25, 0xb5, 0x9e, 0xd5, 0x55, 0x82, 0x71, 0xe9, 0xf9, 0xe7, 0x6f, 0xaf, 0x72, 0x05, 0xbc,
	0x63, 0xf9, 0x9c, 0x5a, 0x6e, 0x74, 0x10, 0x7d, 0x19, 0x2f, 0x00, 0xed, 0xc4, 0x04, 0xe7, 0xa1,
	0xef, 0x92, 0xf1, 0x1a, 0x21, 0x2a, 0x02, 0xa2, 0x88, 0xf7, 0xe6, 0x20, 0x02, 0x71, 0x69, 0x13,
	0x04, 0x89, 0x24, 0xf8, 0x07, 0x72, 0x68, 0x12, 0x79, 0xbf, 0x56, 0xa4, 0x01, 0xc6, 0x4b, 0x40,
	0x7b, 0x73, 0x24, 0x6b, 0x97, 0xa5, 0x26, 0x60, 0x4a, 0xf8, 0xff, 0x34, 0x8c, 0x5c, 0x34, 0xa0,
	0x09, 0xc6, 0xdb, 0x1c, 0x42, 0x5d, 0x4e, 0x4f, 0x59, 0x4f, 0xe8, 0x62, 0x66, 0x56, 0x4f, 0x4d,
	0xde, 0x6a, 0x34, 0xef, 0x41, 0xe0, 0xbc, 0x03, 0xbc, 0x2d, 0xda, 0xe4, 0xb0, 0x9e, 0x10, 0xa6,
	0x0d, 0x37, 0xed, 0x7d, 0x5c, 0x11, 0x7b, 0x9c, 0x84, 0x03, 0x6b, 0x4a, 0x66, 0xd6, 0xd4, 0x99,
	0x59, 0x53, 0x3a, 0x8b, 0x36, 0xed, 0xd8, 0x5c, 0x17, 0x4f, 0x5c, 0x5f, 0x64, 0xd8, 0x75, 0x5c,
	0xd5, 0x25, 0x52, 0x39, 0xa2, 0x1e, 0xb5, 0xcb, 0xb8, 0xa8, 0x03, 0x92, 0xbc, 0xe8, 0xe4, 0x08,
	0xd7, 0x16, 0xa4, 0xa6, 0x42, 0x2a, 0xf8, 0x4a, 0x1a, 0x26, 0x39, 0x35, 0x5e, 0x03, 0x2a, 0x75,
	0x39, 0x3d, 0x23, 0xe1, 0x60, 0x7e, 0x84, 0x23, 0xed, 0x5a, 0x99, 0x5a, 0xfc, 0x32, 0xf4, 0xab,
	0xe9, 0x77, 0x2c, 0xe4, 0x3b, 0x50, 0xfc, 0x11, 0xdc, 0x1d, 0x4f, 0xd4, 0xb2, 0xa6, 0xc4, 0x0c,
	0x42, 0x5f, 0x3c, 0xde, 0xf8, 0x0a, 0xa8, 0xa0, 0x08, 0x35, 0xdb, 0xed, 0xec, 0xbe, 0xfe, 0x29,
	0x95, 0x27, 0xa8, 0x06, 0xf8, 0x70, 0x29, 0xd5, 0x5c, 0x5b, 0x32, 0xe0, 0x93, 0xe6, 0x2c, 0x39,
	0x6f, 0x03, 0x35, 0x3e, 0xe4, 0xd0, 0xb6, 0x72, 0xac, 0x9a, 0x9f, 0xb5, 0x9a, 0xf6, 0x8b, 0x34,
	0xed, 0x27, 0xc0, 0x05, 0x6d, 0x1b, 0x39, 0x40, 0x91, 0x6f, 0xe7, 0x1f, 0x94, 0xf2, 0xad, 0x0c,
	0xb1, 0xe3, 0x9f, 0x24, 0xe9, 0x20, 0xb5, 0x89, 0xf1, 0xd5, 0x25, 0xee, 0x8d, 0x0b, 0x53, 0x7b,
	0x1f, 0x97, 0x7e, 0x36, 0xb0, 0x3e, 0x3c, 0xc6, 0xf5, 0xa5, 0x1e, 0xd6, 0x51, 0x35, 0x35, 0x24,
	0x0b, 0x03, 0x9a, 0x60, 0xbc, 0x01, 0x54, 0x59, 0xe0, 0x65, 0xa5, 0xea, 0xda, 0xed, 0x7c, 0x5d,
	0x08, 0x7b, 0xa4, 0x9e, 0xb2, 0xa8, 0xe3, 0x09, 0xe9, 0x77, 0x40, 0xc5, 0x94, 0xa7, 0x15, 0xe3,
	0x1a, 0x6d, 0x3d, 0x11, 0x74, 0x17, 0xf8, 0xda, 0x6f, 0x6d, 0xad, 0xc5, 0xce, 0x7e, 0x47, 0xd2,
	0xb5, 0xe5, 0x21, 0x6d, 0xa0, 0x4d, 0x38, 0xcd, 0xdb, 0x9b, 0x09, 0x92, 0xf3, 0x9f, 0xf8, 0x07,
	0x74, 0xf7, 0x47, 0x00, 0x00, 0x00, 0xff, 0xff, 0xaf, 0x85, 0xaf, 0x3c, 0x6d, 0x09, 0x00, 0x00,
}


text:
=begin
   Copyright 2016 Telegraph-ai

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
=end

require 'digest'
require 'date'

module Pages
	class AdminCitoyen < Sinatra::Application
		def initialize(base)
			super(base)
			@queries={
				'get_citizen_by_key'=><<END,
SELECT c.slug,c.firstname,c.lastname,c.email,c.reset_code,c.registered,c.country,c.user_key,c.validation_level,c.birthday,c.telephone,c.city,ci.zipcode,ci.population,ci.departement,ci.num_circonscription,ci.num_commune,ci.code_departement, t.national as telephone_national, ci.code_insee
FROM users AS c
LEFT JOIN cities AS ci ON (ci.city_id=c.city_id)
LEFT JOIN telephones AS t ON (t.international=c.telephone)
WHERE c.user_key=$1
END
				'get_citizen_by_email'=><<END,
SELECT c.slug,c.firstname,c.lastname,c.email,c.reset_code,c.registered,c.country,c.user_key,c.validation_level,c.birthday,c.telephone,c.city,ci.zipcode,ci.population,ci.departement,ci.num_circonscription,ci.num_commune,ci.code_departement, t.national as telephone_national
FROM users AS c
LEFT JOIN cities AS ci ON (ci.city_id=c.city_id)
LEFT JOIN telephones AS t ON (t.international=c.telephone)
WHERE c.email=$1
END
				'get_election_by_slug'=><<END,
SELECT e.*,e1.name as parent_name, e1.slug as parent_slug, CASE WHEN c.id is not null THEN true ELSE false END as circonscription
FROM elections AS e
LEFT JOIN circonscriptions AS c ON (c.id=e.circonscription_id)
LEFT JOIN elections AS e1 ON (e1.election_id=e.parent_election_id)
WHERE e.slug=$1
END
				'get_qualified_candidates_by_election'=><<END,
SELECT u.*,ce.fields,ce.finalist
FROM users AS u
INNER JOIN candidates_elections AS ce ON (ce.email=u.email AND ce.qualified)
INNER JOIN elections as e ON (ce.election_id=e.election_id)
WHERE e.slug=$1
END
				'reset_citizen_email'=><<END,
UPDATE users SET email_status=2, validation_level=(validation_level & 14), email=reset_email, reset_email=null, reset_code=null WHERE email=$1 AND reset_email IS NOT null RETURNING *
END
				'get_ballot_by_id'=><<END,
SELECT b.ballot_id,b.vote_id,b.date_generated,b.vote_status,v.cc_vote_id,u.* FROM ballots as b INNER JOIN users as u ON (u.email=b.email) INNER JOIN votes as v ON (v.vote_id=b.vote_id) WHERE b.ballot_id=$1 AND u.user_key=$2;
END
				'get_vote_by_id'=><<END,
SELECT * FROM votes WHERE vote_id=$1
END
				'get_ballot_by_email'=><<END,
SELECT b.ballot_id,b.vote_status,b.date_generated FROM ballots as b WHERE b.email=$1 and b.vote_id=$2;
END
				'get_ballots_stats'=><<END,
SELECT count(*),c.slug,c.candidate_id FROM candidates as c LEFT JOIN candidates_ballots as cb ON (cb.candidate_id=c.candidate_id AND cb.vote_status='complete') WHERE c.qualified AND NOT c.abandonned GROUP BY c.slug,c.candidate_id ORDER BY c.slug ASC;
END
				'create_ballot'=><<END,
INSERT INTO ballots (email,vote_id) VALUES ($1,$2) RETURNING *;
END
				'update_citizen_hash'=><<END,
UPDATE users SET hash=$1 WHERE email=$2 RETURNING *;
END
				'populate_ballot'=><<END,
WITH ballot_candidates AS (
	INSERT INTO candidates_ballots (ballot_id,candidate_id,position) VALUES ($1,$2,1), ($1,$3,2), ($1,$4,3), ($1,$5,4), ($1,$6,5) RETURNING *
)
SELECT b.ballot_id,b.completed,b.date_generated,bc.position,bc.vote_status,c.*
FROM candidates AS c
INNER JOIN ballot_candidates as bc ON (bc.candidate_id=c.candidate_id)
INNER JOIN ballots as b ON (b.ballot_id=bc.ballot_id)
ORDER BY bc.position ASC;
END
				'get_circonscription_by_email'=><<END,
SELECT c.*,e.slug as election_slug
FROM voters as v
INNER JOIN users AS u ON (u.email=v.email AND u.email=$1)
INNER JOIN elections as e ON (e.election_id=v.election_id)
INNER JOIN elections as e2 ON (e.parent_election_id=e2.election_id)
INNER JOIN circonscriptions as c ON (c.id=e.circonscription_id)
WHERE e2.slug=$2
END
				'set_circonscription_by_email'=><<END,
INSERT INTO voters (election_id,email) SELECT ev.election_id,$1 FROM elections_view as ev WHERE ev.circonscription_id=$2 AND ev.parent_slug=$3
END
				'add_supporter'=><<END,
INSERT INTO supporters (election_id,supporter,candidate)
SELECT e.election_id,$1,c.email
FROM users AS c ON (c.slug=$2)
END
				'get_donations_by_email'=><<END,
SELECT d.*,d.created::date as donation_date,z.total,ca.name,date_part('year',d.created) AS year
FROM donations AS d
INNER JOIN (
	SELECT SUM(amount) AS total,email FROM donations WHERE email=$1 GROUP BY email
) AS z ON (d.email=z.email)
LEFT JOIN candidates AS ca ON (ca.candidate_id=d.candidate_id)
WHERE d.email=$1 ORDER BY d.created DESC
END
				'get_elections_by_organization'=><<END,
SELECT e.*,
CASE WHEN ce.email is not null THEN true ELSE false END as participating,
CASE WHEN e.end_at<now() THEN false ELSE true END as current,
CASE WHEN e.parent_election_id is null THEN true ELSE false END as main_election,
ce.accepted, ce.verified, ce.qualified, ce.finalist, ce.abandonned, ce.disqualified
FROM elections AS e
INNER JOIN organizations AS o ON (e.organization_id=o.id AND o.slug=$1)
INNER JOIN organizations_users AS ou ON (ou.organization_id=o.id AND ou.email=$2)
LEFT JOIN candidates_elections AS ce ON (ce.email=$2 AND ce.election_id=e.election_id)
ORDER BY e.end_at DESC
END
				'get_candidate_by_election'=><<END,
SELECT e2.slug,ce.email, CASE WHEN c.id is not null THEN true ELSE false END as circonscription
FROM elections AS e1
INNER JOIN elections AS e2 ON (e1.election_id=e2.parent_election_id AND e1.slug=$2)
INNER JOIN candidates_elections AS ce ON (ce.election_id=e2.election_id AND ce.email=$1)
LEFT JOIN circonscriptions AS c ON (c.id=e2.circonscription_id)
END
				'get_candidate_by_slug'=><<END,
SELECT u.*, ce.*,ci.code_departement,ci.num_circonscription, CASE WHEN s.soutiens is NULL THEN 0 ELSE s.soutiens END
    FROM users as u
    INNER JOIN candidates_elections as ce ON (ce.email=u.email)
    INNER JOIN elections as e ON (ce.election_id=e.election_id AND e.election_id=$2)
    INNER JOIN circonscriptions as ci ON (ci.id=e.circonscription_id)
    LEFT JOIN (
	    SELECT candidate,election_id,count(supporter) as soutiens
	    FROM supporters
	    GROUP BY candidate,election_id
      ) as s
  on (s.candidate = u.email AND s.election_id=e.election_id)
WHERE u.slug = $1;
END
				'set_candidate_slug'=><<END,
UPDATE users SET slug=$2
FROM (
	SELECT count(*)
	FROM users
	WHERE slug=$2
) AS z
WHERE email=$1 AND z.count=0
RETURNING *
END
			}
		end

		helpers do
			def filter_output(obj)
				filters=['email','tel','user_key','address1','address2','birthday','birthplace','candidate_key','email_status','hash','mc_group_id','referal_code','reset_code','reset_email','suppleant_email','tags','telegram_id','telephone','vote_id']
				filters.each {|f| obj.delete(f)}
				return obj
			end

			def error_occurred(code,msg)
				status code
				return JSON.dump({
					'title'=>msg['title'],
					'msg'=>msg['msg']
				})
			end

			def authenticate_citizen(user_key)
				res=Pages.db_query(@queries["get_citizen_by_key"],[user_key])
				return res.num_tuples.zero? ? nil : res[0]
			end

			def authenticate_election(election_slug)
				res=Pages.db_query(@queries["get_election_by_slug"],[election_slug])
				return res.num_tuples.zero? ? nil : res[0]
			end

			def get_circonscription(email,election_slug)
				res=Pages.db_query(@queries["get_circonscription_by_email"],[email,election_slug])
				return res.num_tuples.zero? ? nil : res[0]
			end

			def set_circonscription(email,circonscription_id,election_slug)
				res=Pages.db_query(@queries["set_circonscription_by_email"],[email,circonscription_id,election_slug])
				return res.num_tuples.zero? ? nil : res[0]
			end

			def get_donations(email)
				res=Pages.db_query(@queries["get_donations_by_email"],[email])
				return res.num_tuples.zero? ? nil : res
			end

			def get_elections(organization_slug,user_email)
				res=Pages.db_query(@queries["get_elections_by_organization"],[organization_slug,user_email])
				return res.num_tuples.zero? ? nil : res
			end

			def is_candidate(candidate_email,election_slug)
				res=Pages.db_query(@queries["get_candidate_by_election"],[candidate_email,election_slug])
				return res.num_tuples.zero? ? nil : res[0]
			end

			def get_candidate_by_slug(candidate_slug,election_id)
				res=Pages.db_query(@queries["get_candidate_by_slug"],[candidate_slug,election_id])
				return res.num_tuples.zero? ? nil : res[0]
			end

			def register_candidate(candidate_email,candidate_slug)
				res=Pages.db_query(@queries["set_candidate_slug"],[candidate_email,candidate_slug])
				return (not res.num_tuples.zero?)
			end

			def page_info(infos=nil)
				return {
					'page_description'=>"description",
					'page_author'=>"Des citoyens ordinaires",
					'page_image'=>"pas de photo",
					'page_url'=>"https://laprimaire.org",
					'page_title'=>"Votez !",
					'social_title'=>"Votez !"
				} if infos.nil?
				return {
					'page_description'=>"description",
					'page_author'=>"Des citoyens ordinaires",
					'page_image'=>"pas de photo",
					'page_url'=>"https://laprimaire.org/citoyen/vote/#{infos['user_key']}",
					'page_title'=>"Votez !",
						'social_title'=>"Votez !"
				}
			end

			def create_ballot(email,vote_id)
				res=Pages.db_query(@queries["create_ballot"],[email,vote_id])
				ballot_id=res[0]['ballot_id']
				return {'ballot_id'=>ballot_id,'vote_status'=>"absent",'candidates'=>[]}
			end

			def generate_set()
				res=Pages.db_query(@queries["get_ballots_stats"])
				candidats=[]
				weights=[]
				res.each_with_index do |r,i|
					candidats.push(r['candidate_id'])
					weights.push(r['count'])
				end
				wrs = -> (freq) { freq.max_by { |_, weight| rand ** (1.0 / weight) }.first }
				probas=weights.map {|w| 1/w.to_f}
				ps=probas.map {|w| (Float w)/probas.reduce(:+)}
				wcandidats = candidats.zip(ps).to_h
				set=[]
				while set.length<5 do
					c=wrs[wcandidats]
					set.push(c)
					wcandidats.delete(c)
				end
				return set
			end

			def email_domain_valid(email)
				check="SELECT domain FROM forbidden_domains as fd WHERE fd.domain=substring($1 from '@(.*)$')"
				res=Pages.db_query(check,[email])
				return res.num_tuples.zero?
			end

			def clones_count()
				check="SELECT count(*),ip_address,useragent_raw FROM (SELECT ip_address,email,ua.useragent_raw FROM auth_history AS a INNER JOIN user_agents AS ua ON (ua.useragent_id=a.useragent_id) GROUP BY ip_address,email,useragent_raw) as a where ip_address=$1 and useragent_raw=$2 group by ip_address,useragent_raw order by count desc"
				res=Pages.db_query(check,[request.ip,request.user_agent])
				return res.num_tuples.zero? ? 0 : res[0]['count']
			end
		end

		configure do
			set :view, 'views'
			set :root, File.expand_path('../../',__FILE__)
		end

		get '/citoyen/:user_key' do
			errors=[]
			success=[]
			begin
				Pages.db_init()
				res=Pages.db_query(@queries["get_citizen_by_key"],[params['user_key']])
				return erb :error, :locals=>{:msg=>{"title"=>"Page inconnue","message"=>"La page demandée n'existe pas"}} if res.num_tuples.zero?
				citoyen=res[0]
				#1 We check the validation level of the candidate authentication
				auth={
					'email_valid'=>(citoyen['validation_level'].to_i&1)!=0,
					'phone_valid'=>(citoyen['validation_level'].to_i&2)!=0
				}
				redirect "/citoyen/auth/#{params['user_key']}" if citoyen['validation_level'].to_i<3
				email=citoyen['email']
				if not params['reset_email'].nil? then
					if not params['reset_code'].nil? and params['reset_code']==citoyen['reset_code'] then
						res1=Pages.db_query(@queries["reset_citizen_email"],[email])
						if not res1.num_tuples.zero? then
							updated_citoyen=res1[0]
							citoyen['email']=updated_citoyen['email']
							citoyen['email_status']=updated_citoyen['email_status']
							citoyen['validation_level']=updated_citoyen['validation_level']
							success.push("Votre email a bien été mis-à-jour. Votre nouvel email : #{citoyen['email']}")
						end
					else
						errors.push("Impossible de mettre à jour votre email : le code fourni est erroné.")
					end
				end
			rescue PG::Error => e
				status 500
				return erb :error, :locals=>{:msg=>{"title"=>"Erreur serveur","message"=>e.message}}
			ensure
				Pages.db_close()
			end
			if !success.empty?() then
				return erb :success, :locals=>{:msg=>{"title"=>"Email mis à jour","message"=>success[0]}}
			elsif !errors.empty?() then
				return erb :error, :locals=>{:msg=>{"title"=>"Email non mis à jour","message"=>errors[0]}}
			end
			return erb :error, :locals=>{:msg=>{"title"=>"Page inconnue","message"=>"La page demandée n'existe pas"}} if res.num_tuples.zero?
			return erb :admin_citoyen, :locals=>{
				'citoyen'=>citoyen,
				'errors'=>errors,
				'success'=>success
			}
		end

		get '/citoyen/vote/tutorial' do
			erb :vote_tutorial
		end

		get '/citoyen/vote/tutorial_final' do
			erb :vote_tutorial2
		end

		get '/citoyen/vote/100k' do
			erb :illustration_100k
		end

		get '/citoyen/vote/facebook_11' do
			return JSON.dump({'param_missing'=>'token'}) if params['token'].nil?
			app_id=CC_APP_ID_FB
			vote_id=FB_VOTE_ID_11
			test=params['test']
			vote_id=FB_VOTE_ID_TEST if test=='1'
			vote_id=FB_VOTE_ID_TEST_2 if test=='2'
			erb :fb_voting, :locals=>{
				'cocorico_app_id'=>app_id,
				'cc_vote_id'=>vote_id,
				'token'=>params['token'],
				'test'=>test,
				'callback'=>'api/vote_completed_11'
			}
		end

		get '/citoyen/vote/facebook_4' do
			return JSON.dump({'param_missing'=>'token'}) if params['token'].nil?
			app_id=CC_APP_ID_FB
			vote_id=FB_VOTE_ID_4
			test=params['test']
			vote_id=FB_VOTE_ID_TEST if test=='1'
			vote_id=FB_VOTE_ID_TEST_2 if test=='2'
			erb :fb_voting, :locals=>{
				'cocorico_app_id'=>app_id,
				'cc_vote_id'=>vote_id,
				'token'=>params['token'],
				'test'=>test,
				'callback'=>'api/vote_completed_4'
			}
		end

		get '/citoyen/vote/comparateur' do
			erb :index, :locals=>{
				'page_info'=>{
					'page_description'=>"Explorez et comparez les propositions des 5 citoyen(ne)s candidat(e)s finalistes à LaPrimaire.org.",
					'page_author'=>"Les citoyen(ne)s candidat(e)s à LaPrimaire.org",
					'page_image'=>"https://s3.eu-central-1.amazonaws.com/laprimaire/images/comparateur.jpg",
					'page_url'=>"https://laprimaire.org/citoyen/vote/comparateur",
					'page_title'=>"Explorez et comparez les propositions des citoyen(ne)s candidat(e)s à LaPrimaire.org !",
					'social_title'=>"Explorez et comparez les propositions des citoyen(ne)s candidat(e)s à LaPrimaire.org !"
				},
				'template'=>:comparateur,
				'vars'=>{}
			}
		end

		get '/citoyen/verif/:email' do
			return erb :error, :locals=>{:msg=>{"title"=>"Page inconnue","message"=>"La page demandée n'existe pas"}} if params['email'].nil?
			email=params['email'].downcase.gsub(/\A\p{Space}*|\p{Space}*\z/, '')
			return erb :error, :locals=>{:msg=>{"title"=>"Mauvais email","message"=>"Votre email n'est pas valide"}} if email.match(/\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/).nil?
			erb :index, :locals=>{
				'page_info'=>page_info(),
				'vars'=>{'email'=>params['email'],'newcitizen'=>params['newcitizen']},
				'no_navbar'=>true,
				'template'=>:email_verification
			}
		end

		get '/citoyen/auth/:user_key' do
			begin
				Pages.db_init()
				res=Pages.db_query(@queries["get_citizen_by_key"],[params['user_key']])
				return erb :error, :locals=>{:msg=>{"title"=>"Page inconnue","message"=>"La page demandée n'existe pas"}} if res.num_tuples.zero?
				citoyen=res[0]
				if !email_domain_valid(citoyen['email']) then
					status 403
					citoyen['forbidden']=1
					Pages.log.error "Forbidden email domain name : #{citoyen['email']}"
				end
				clones=clones_count()
				if clones>FRAUD_THRESHOLD_CLONES then
					status 403
					citoyen['fraud_suspected']=1
					Pages.log.error "Fraud suspected : #{citoyen['email']} [#{clones} clones]"
				end
			rescue PG::Error => e
				Pages.log.error "/citoyen/auth DB Error #{params}\n#{e.message}"
				status 500
				return erb :error, :locals=>{:msg=>{"title"=>"Erreur serveur","message"=>e.message}}
			ensure
				Pages.db_close()
			end
			redirect "/citoyen/#{params['user_key']}" if (citoyen['validation_level'].to_i>2 && params['reauth'].nil?)
			citoyen['birthday']=Date.parse(citoyen['birthday']).strftime('%d/%m/%Y') unless citoyen['birthday'].nil?
			erb :index, :locals=>{
				'page_info'=>page_info(citoyen),
				'vars'=>{'citoyen'=>citoyen},
				'no_navbar'=>true,
				'template'=>:authentication
			}
		end

		get '/citoyen/token/:user_key' do
			return JSON.dump({'param_missing'=>'ballot'}) if params['ballot'].nil?
			return JSON.dump({'param_missing'=>'user key'}) if params['user_key'].nil?
			return JSON.dump({'param_missing'=>'vote id'}) if params['vote_id'].nil?
			if VOTE_PAUSED then
				status 404
				return JSON.dump({'message'=>'votes are currently paused, please retry in a few minutes...'})
			end
			begin
				Pages.db_init()
				res=Pages.db_query(@queries["get_ballot_by_id"],[params['ballot'],params['user_key']])
				ballot=res[0]
				token={
					:iss=> COCORICO_APP_ID,
					:sub=> Digest::SHA256.hexdigest(ballot['email']),
					:email=> ballot['email'],
					:lastName=> ballot['lastname'],
					:firstName=> ballot['firstname'],
					:birthdate=> ballot['birthday'],
					:authorizedVotes=> [ballot['cc_vote_id']],
					:exp=>(Time.new.getutc+VOTING_TIME_ALLOWED).to_i
				}
				vote_token=JWT.encode token, COCORICO_SECRET, 'HS256'
				res=Pages.db_query(@queries["update_citizen_hash"],[token[:sub],ballot['email']])
			rescue PG::Error => e
				Pages.log.error "/citoyen/token DB Error #{params}\n#{e.message}"
				status 500
				return JSON.dump({"title"=>"Erreur serveur","message"=>e.message})
			ensure
				Pages.db_close()
			end
			return JSON.dump({'token'=>vote_token})
		end

		get '/citoyen/vote/:user_key/1' do
			redirect "/citoyen/vote/#{params['user_key']}/2"
		end

		get '/citoyen/spa/:user_key/election/run' do
			begin
				Pages.db_init()
				citoyen=authenticate_citizen(params['user_key'])
				return error_occurred(404,{"title"=>"Page inconnue","msg"=>"La page demandée n'existe pas [code:CSER00]"}) if citoyen.nil?
				res=get_elections('laprimaire-org',citoyen['email']) #FIXME the right organization slug should be found dynamically here with the hostname
				elections={}
				main_elections={}
				if !res.nil? then
					res.each do |e|
						elections[e['election_id']]=e
						main_elections[e['election_id']]=e if e['main_election'].to_b
					end
				end
				elections.each do |k,v|
					if (!v['parent_election_id'].nil? && v['participating'].to_b) then
						main_elections[v['parent_election_id']]['participating']=v['participating'].to_b
						main_elections[v['parent_election_id']]['accepted']=v['accepted'].to_b
						main_elections[v['parent_election_id']]['verified']=v['verified'].to_b
						main_elections[v['parent_election_id']]['qualified']=v['qualified'].to_b
						main_elections[v['parent_election_id']]['finalist']=v['finalist'].to_b
						main_elections[v['parent_election_id']]['abandonned']=v['abandonned'].to_b
						main_elections[v['parent_election_id']]['disqualified']=v['disqualified'].to_b
						main_elections[v['parent_election_id']]['parent_slug']=v['slug']
					end
				end
			rescue PG::Error => e
				Pages.log.error "/citoyen/spa/election/run DB Error [code:CSER01] #{params}\n#{e.message}"
				return error_occurred(500,{"title"=>"Erreur serveur","msg"=>"Récupération des infos impossible [code:CSER01]"})
			ensure
				Pages.db_close()
			end
			return erb 'spa/candidats/choose-election'.to_sym, :locals=>{
				'citoyen'=>citoyen,
				'elections'=>main_elections
			}

		end

		get '/citoyen/spa/:user_key/election/:election_slug/run' do
			begin
				Pages.db_init()
				citoyen=authenticate_citizen(params['user_key'])
				return error_occurred(404,{"title"=>"Page inconnue","msg"=>"La page demandée n'existe pas [code:CSER0]"}) if citoyen.nil?
				election=authenticate_election(params['election_slug'])
				return error_occurred(404,{"title"=>"Page inconnue","msg"=>"La page demandée n'existe pas [code:CSER2]"}) if election.nil?
				previous_election=is_candidate(citoyen['email'],election['slug']) #a candidate can be a candidate only in 1 circonscription and he cannot change it later on.
				election=previous_election if not previous_election.nil?
				if citoyen['slug'].nil? then #a citizen does not have slug by default. We create it the 1st time he wants to be a candidate
					slug=(citoyen['firstname']+'-'+citoyen['lastname']).slugify
					while not register_candidate(citoyen['email'],slug) do
						slug=(citoyen['firstname']+'-'+citoyen['lastname']+rand(100).to_s).slugify
					end
					citoyen['slug']=slug
				end
				raise 'choose-circonscription' if not election['circonscription'].to_b #candidate has not yet registered to the election
				candidate=get_candidate_by_slug(citoyen['slug'],election['election_id'])
				return error_occurred(404,{"title"=>"Erreur","msg"=>"Candidat inconnu"}) if candidate.nil?
				candidate_fields=JSON.parse(candidate['fields'])
				candidate.merge!(candidate_fields){|k,o,n| n.nil? ? o : n }
				candidate.delete('fields')
				birthday=Date.parse(candidate['birthday'].split('?')[0]) unless candidate['birthday'].nil?
				age=nil
				unless birthday.nil? then
					now = Time.now.utc.to_date
					candidate['age'] = now.year - birthday.year - ((now.month > birthday.month || (now.month == birthday.month && now.day >= birthday.day)) ? 0 : 1)
				end
			rescue RuntimeError => e
				return erb 'spa/candidats/choose-circonscription'.to_sym, :locals=>{
					'citoyen'=>citoyen
				}
			rescue PG::Error => e
				Pages.log.error "/citoyen/spa/election/run DB Error [code:CSER1] #{params}\n#{e.message}"
				return error_occurred(500,{"title"=>"Erreur serveur","msg"=>"Récupération des infos impossible [code:CSER1]"})
			ensure
				Pages.db_close()
			end
			return erb 'spa/candidats/run'.to_sym, :locals=>{
				'citoyen'=>candidate,
				'election'=>election
			}
		end

		get '/citoyen/spa/:user_key/election/:election_slug/candidat/:candidate_slug' do
			begin
				Pages.db_init()
				citoyen=authenticate_citizen(params['user_key'])
				return error_occurred(404,{"title"=>"Page inconnue","msg"=>"La page demandée n'existe pas [code:CSEC0]"}) if citoyen.nil?
				election=authenticate_election(params['election_slug'])
				return error_occurred(404,{"title"=>"Page inconnue","msg"=>"La page demandée n'existe pas [code:CSEC2]"}) if election.nil?
			rescue PG::Error => e
				Pages.log.error "/citoyen/spa/election/candidat DB Error [code:CSEC1] #{params}\n#{e.message}"
				return error_occurred(500,{"title"=>"Erreur serveur","msg"=>"Récupération des infos impossible [code:CSEC1]"})
			ensure
				Pages.db_close()
			end
			return erb 'spa/candidats/summary'.to_sym, :locals=>{
				'citoyen'=>citoyen,
				'election'=>election,
				'candidate_slug'=>params['candidate_slug']
			}
		end

		get '/citoyen/spa/:user_key/election/legislatives-2017' do
			errors=[]
			success=[]
			begin
				Pages.db_init()
				citoyen=authenticate_citizen(params['user_key'])
				return error_occurred(404,{"title"=>"Page inconnue","msg"=>"La page demandée n'existe pas [code:CSEL0]"}) if citoyen.nil?
				redirect "/citoyen/auth/#{params['user_key']}" if citoyen['validation_level'].to_i<3
				circonscription=get_circonscription(citoyen['email'],'legislatives-2017')
				raise 'choose-circonscription' if circonscription.nil? #user has not yet registered to the election
				circonscription['deputy_slug']=circonscription['deputy_url'].split('/')[-1]
			rescue RuntimeError => e
				return erb 'spa/elections/choose-circonscription'.to_sym, :locals=>{
					'citoyen'=>citoyen
				}
			rescue PG::Error => e
				Pages.log.error "/citoyen/spa/election/legislatives-2017 DB Error [code:CSEL1] #{params}\n#{e.message}"
				return error_occurred(500,{"title"=>"Erreur serveur","msg"=>"Récupération des infos impossible [code:CSEL1]"})
			ensure
				Pages.db_close()
			end
			return erb 'spa/elections/legislatives-2017'.to_sym, :locals=>{
				'citoyen'=>citoyen,
				'circonscription'=>circonscription,
				'errors'=>errors,
				'success'=>success
			}
		end

		get '/citoyen/spa/:user_key/election/presidentielle-2017' do
			begin
				Pages.db_init()
				citoyen=authenticate_citizen(params['user_key'])
				return error_occurred(404,{"title"=>"Page inconnue","msg"=>"La page demandée n'existe pas [code:CSEL0]"}) if citoyen.nil?
				res=Pages.db_query(@queries["get_qualified_candidates_by_election"],['presidentielle-2017'])
				qualified=[]
				finalists=[]
				if not res.num_tuples.zero? then
					res.each do |c|
						c['fields']=JSON.parse(c['fields'])
						qualified.push(filter_output(c))
						finalists.push(filter_output(c)) if c['finalist'].to_b
					end
				end
			rescue PG::Error => e
				Pages.log.error "/citoyen/spa/election DB Error #{params}\n#{e.message}"
				return error_occurred(500,{"title"=>"Erreur serveur","msg"=>"Récupération des infos impossible [code:CSEP0]"})
			ensure
				Pages.db_close()
			end
			erb 'spa/elections/presidentielle-2017'.to_sym, :locals=>{
				'partial'=>'presidentielle-2017',
				'qualified'=>qualified
			}
		end

		get '/citoyen/spa/:user_key/candidate/:partial' do
			erb 'spa/candidate'.to_sym, :locals=>{
				'partial'=>params['partial']
			}
		end

		get '/citoyen/spa/:user_key/about' do
			erb 'spa/about'.to_sym, :locals=>{ }
		end

		get '/citoyen/spa/:user_key/donations' do
			begin
				Pages.db_init()
				citoyen=authenticate_citizen(params['user_key'])
				return error_occurred(404,{"title"=>"Page inconnue","msg"=>"La page demandée n'existe pas [code:CSD0]"}) if citoyen.nil?
				res=get_donations(citoyen['email'])
				donations=[]
				dons={}
				if not res.nil? then
					res.each do |d|
						if d['recipient']=='ASSO' then
							d['structure']='Association Democratech'
							d['recipient']='Association Democratech'
							d['objet']='Préparation LaPrimaire.org'
							d['fisc']='Non'
						elsif d['recipient']=='PARTI' then
							d['structure']='Parti LaPrimaire.org'
							d['recipient']='Parti LaPrimaire.org'
							d['fisc']='Oui, en 2018' if d['year']=='2017'
							d['fisc']='Oui, en 2017' if d['year']=='2016'
							d['objet']='Financement LaPrimaire.org'
							d['objet']="Campagne #{d['name']}" if not d['name'].nil?
						end
						dons[d['recipient']]={} if dons[d['recipient']].nil?
						dons[d['recipient']][d['year']]={'total'=>0,'dons'=>[]} if dons[d['recipient']][d['year']].nil?
						dons[d['recipient']][d['year']]['total']+=d['amount'].to_i
						dons[d['recipient']][d['year']]['dons'].push(d)
						donations.push(d)
					end
				end
			rescue PG::Error => e
				Pages.log.error "/citoyen/spa/donations DB Error #{params}\n#{e.message}"
				return error_occurred(500,{"title"=>"Erreur serveur","msg"=>"Récupération des infos impossible [code:CSD0]"})
			ensure
				Pages.db_close()
			end
			erb 'spa/donations'.to_sym, :locals=>{
				'citoyen'=>citoyen,
				'donations'=>donations,
				'dons'=>dons
			}
		end

		get '/citoyen/spa/:user_key/home' do
			begin
				Pages.db_init()
				citoyen=authenticate_citizen(params['user_key'])
				return error_occurred(404,{"title"=>"Page inconnue","msg"=>"La page demandée n'existe pas [code:CSH0]"}) if citoyen.nil?
			rescue PG::Error => e
				Pages.log.error "/citoyen/spa/home DB Error #{params}\n#{e.message}"
				return error_occurred(500,{"title"=>"Erreur serveur","msg"=>"Récupération des infos impossible [code:CSH0]"})
			ensure
				Pages.db_close()
			end
			erb 'spa/home'.to_sym, :locals=>{
				'citoyen'=>citoyen
			}
		end

		get '/citoyen/vote/:user_key' do
			redirect "/citoyen/vote/#{params['user_key']}/2"
		end

		get '/citoyen/vote/:user_key/:vote_id' do
			begin
				Pages.db_init()
				res=Pages.db_query(@queries["get_citizen_by_key"],[params['user_key']])
				return erb :error, :locals=>{:msg=>{"title"=>"Page inconnue","message"=>"La page demandée n'existe pas"}} if res.num_tuples.zero?
				citoyen=res[0]
				res=Pages.db_query(@queries["get_vote_by_id"],[params['vote_id']])
				return erb :error, :locals=>{:msg=>{"title"=>"Vote inconnu","message"=>"La page demandée n'existe pas"}} if res.num_tuples.zero?
				vote=res[0]
				#1 We check the validation level of the candidate authentication
				auth={
					'email_valid'=>(citoyen['validation_level'].to_i&1)!=0,
					'phone_valid'=>(citoyen['validation_level'].to_i&2)!=0
				}
				redirect "/citoyen/auth/#{params['user_key']}" if citoyen['validation_level'].to_i<3
				res=Pages.db_query("SELECT * FROM candidates WHERE finalist")
				finalists=[]
				res.each { |f| finalists.push(f.clone) } if !res.num_tuples.zero?
				#2 We check if a ballot has already been created
				res=Pages.db_query(@queries["get_ballot_by_email"],[citoyen['email'],vote['vote_id']])
				if res.num_tuples.zero? then
					#2bis If no pre-existing ballot exist we create one for the citizen
					ballot=create_ballot(citoyen['email'],vote['vote_id'])
				else
					vote_status=res[0]['vote_status'].nil? ? "absent" : res[0]['vote_status']
					ballot={'ballot_id'=>res[0]['ballot_id'],'vote_status'=>vote_status,'candidates'=>[]}
				end
				finalists.shuffle.each { |r| ballot["candidates"].push(r) }
			rescue PG::Error => e
				Pages.log.error "/citoyen/vote DB Error #{params}\n#{e.message}"
				status 500
				return erb :error, :locals=>{:msg=>{"title"=>"Erreur serveur","message"=>e.message}}
			ensure
				Pages.db_close()
			end
			ballot['candidates'].each do |candidate|
				candidate['firstname']=candidate['name'].split(' ')[0]
				candidate['lastname']=candidate['name'].split(' ')[1]
				candidate['vote_status']= vote['vote_status'].nil? ? "absent" : vote['vote_status']
				birthday=Date.parse(candidate['birthday'].split('?')[0]) unless candidate['birthday'].nil?
				age=nil
				unless birthday.nil? then
					now = Time.now.utc.to_date
					age = now.year - birthday.year - ((now.month > birthday.month || (now.month == birthday.month && now.day >= birthday.day)) ? 0 : 1)
				end
				candidate['age']=age
			end
			tmp={
				'e'=>citoyen['email'],
				'f'=>citoyen['firstname'],
				'l'=>citoyen['lastname'],
				'a'=>citoyen['address'],
				'z'=>citoyen['zipcode'],
				'v'=>citoyen['city']
			}
			donation_params=""
			tmp.each do |k,v|
				donation_params+="#{k}="+CGI.escape(v) if !v.nil?
				donation_params+="&" if k!='v'
			end
			donation_params="?"+donation_params if !donation_params.empty?
			citoyen['donation_params']=donation_params
			erb :vote_citoyen, :locals=>{
				'auth'=>auth,
				'cocorico_app_id'=>COCORICO_APP_ID,
				'citoyen'=>citoyen,
				'ballot'=>ballot,
				'vote'=>vote
			}
		end
	end
end

redpajama_set_name: RedPajamaGithub


text:
If you want to write an option parser, and have it be good, there are
two ways to do it.  The Right Way, and the Wrong Way.

The Wrong Way is to sit down and write an option parser.  We've all done
that.

The Right Way is to write some complex configurable program with so many
options that you go half-insane just trying to manage them all, and put
it off with duct-tape solutions until you see exactly to the core of the
problem, and finally snap and write an awesome option parser.

If you want to write an option parser, don't write an option parser.
Write a package manager, or a source control system, or a service
restarter, or an operating system.  You probably won't end up with a
good one of those, but if you don't give up, and you are relentless and
diligent enough in your procrastination, you may just end up with a very
nice option parser.

## USAGE

    // my-program.js
    var nopt = require("nopt")
      , Stream = require("stream").Stream
      , path = require("path")
      , knownOpts = { "foo" : [String, null]
                    , "bar" : [Stream, Number]
                    , "baz" : path
                    , "bloo" : [ "big", "medium", "small" ]
                    , "flag" : Boolean
                    , "pick" : Boolean
                    , "many" : [String, Array]
                    }
      , shortHands = { "foofoo" : ["--foo", "Mr. Foo"]
                     , "b7" : ["--bar", "7"]
                     , "m" : ["--bloo", "medium"]
                     , "p" : ["--pick"]
                     , "f" : ["--flag"]
                     }
                 // everything is optional.
                 // knownOpts and shorthands default to {}
                 // arg list defaults to process.argv
                 // slice defaults to 2
      , parsed = nopt(knownOpts, shortHands, process.argv, 2)
    console.log(parsed)

This would give you support for any of the following:

```bash
$ node my-program.js --foo "blerp" --no-flag
{ "foo" : "blerp", "flag" : false }

$ node my-program.js ---bar 7 --foo "Mr. Hand" --flag
{ bar: 7, foo: "Mr. Hand", flag: true }

$ node my-program.js --foo "blerp" -f -----p
{ foo: "blerp", flag: true, pick: true }

$ node my-program.js -fp --foofoo
{ foo: "Mr. Foo", flag: true, pick: true }

$ node my-program.js --foofoo -- -fp  # -- stops the flag parsing.
{ foo: "Mr. Foo", argv: { remain: ["-fp"] } }

$ node my-program.js --blatzk 1000 -fp # unknown opts are ok.
{ blatzk: 1000, flag: true, pick: true }

$ node my-program.js --blatzk true -fp # but they need a value
{ blatzk: true, flag: true, pick: true }

$ node my-program.js --no-blatzk -fp # unless they start with "no-"
{ blatzk: false, flag: true, pick: true }

$ node my-program.js --baz b/a/z # known paths are resolved.
{ baz: "/Users/isaacs/b/a/z" }

# if Array is one of the types, then it can take many
# values, and will always be an array.  The other types provided
# specify what types are allowed in the list.

$ node my-program.js --many 1 --many null --many foo
{ many: ["1", "null", "foo"] }

$ node my-program.js --many foo
{ many: ["foo"] }
```

Read the tests at the bottom of `lib/nopt.js` for more examples of
what this puppy can do.

## Types

The following types are supported, and defined on `nopt.typeDefs`

* String: A normal string.  No parsing is done.
* path: A file system path.  Gets resolved against cwd if not absolute.
* url: A url.  If it doesn't parse, it isn't accepted.
* Number: Must be numeric.
* Date: Must parse as a date. If it does, and `Date` is one of the options,
  then it will return a Date object, not a string.
* Boolean: Must be either `true` or `false`.  If an option is a boolean,
  then it does not need a value, and its presence will imply `true` as
  the value.  To negate boolean flags, do `--no-whatever` or `--whatever
  false`
* NaN: Means that the option is strictly not allowed.  Any value will
  fail.
* Stream: An object matching the "Stream" class in node.  Valuable
  for use when validating programmatically.  (npm uses this to let you
  supply any WriteStream on the `outfd` and `logfd` config options.)
* Array: If `Array` is specified as one of the types, then the value
  will be parsed as a list of options.  This means that multiple values
  can be specified, and that the value will always be an array.

If a type is an array of values not on this list, then those are
considered valid values.  For instance, in the example above, the
`--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`,
and any other value will be rejected.

When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be
interpreted as their JavaScript equivalents, and numeric values will be
interpreted as a number.

You can also mix types and values, or multiple types, in a list.  For
instance `{ blah: [Number, null] }` would allow a value to be set to
either a Number or null.  When types are ordered, this implies a
preference, and the first type that can be used to properly interpret
the value will be used.

To define a new type, add it to `nopt.typeDefs`.  Each item in that
hash is an object with a `type` member and a `validate` method.  The
`type` member is an object that matches what goes in the type list.  The
`validate` method is a function that gets called with `validate(data,
key, val)`.  Validate methods should assign `data[key]` to the valid
value of `val` if it can be handled properly, or return boolean
`false` if it cannot.

You can also call `nopt.clean(data, types, typeDefs)` to clean up a
config object and remove its invalid properties.

## Error Handling

By default, nopt outputs a warning to standard error when invalid
options are found.  You can change this behavior by assigning a method
to `nopt.invalidHandler`.  This method will be called with
the offending `nopt.invalidHandler(key, val, types)`.

If no `nopt.invalidHandler` is assigned, then it will console.error
its whining.  If it is assigned to boolean `false` then the warning is
suppressed.

## Abbreviations

Yes, they are supported.  If you define options like this:

```javascript
{ "foolhardyelephants" : Boolean
, "pileofmonkeys" : Boolean }
```

Then this will work:

```bash
node program.js --foolhar --pil
node program.js --no-f --pileofmon
# etc.
```

## Shorthands

Shorthands are a hash of shorter option names to a snippet of args that
they expand to.

If multiple one-character shorthands are all combined, and the
combination does not unambiguously match any other option or shorthand,
then they will be broken up into their constituent parts.  For example:

```json
{ "s" : ["--loglevel", "silent"]
, "g" : "--global"
, "f" : "--force"
, "p" : "--parseable"
, "l" : "--long"
}
```

```bash
npm ls -sgflp
# just like doing this:
npm ls --loglevel silent --global --force --long --parseable
```

## The Rest of the args

The config object returned by nopt is given a special member called
`argv`, which is an object with the following fields:

* `remain`: The remaining args after all the parsing has occurred.
* `original`: The args as they originally appeared.
* `cooked`: The args after flags and shorthands are expanded.

## Slicing

Node programs are called with more or less the exact argv as it appears
in C land, after the v8 and node-specific options have been plucked off.
As such, `argv[0]` is always `node` and `argv[1]` is always the
JavaScript program being run.

That's usually not very useful to you.  So they're sliced off by
default.  If you want them, then you can pass in `0` as the last
argument, or any other number that you'd like to slice off the start of
the list.


text:
package org.apache.kafka.streams.examples.pageview;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.Deserializer;

import java.util.Map;

/**
 * JSON deserializer for Jackson's JsonNode tree model. Using the tree model allows it to work with arbitrarily
 * structured data without having associated Java classes. This deserializer also supports Connect schemas.
 */
public class JsonPOJODeserializer<T> implements Deserializer<T> {
    private ObjectMapper objectMapper = new ObjectMapper();

    private Class<T> tClass;

    /**
     * Default constructor needed by Kafka
     */
    public JsonPOJODeserializer() {
    }

    @SuppressWarnings("unchecked")
    @Override
    public void configure(Map<String, ?> props, boolean isKey) {
        tClass = (Class<T>) props.get("JsonPOJOClass");
    }

    @Override
    public T deserialize(String topic, byte[] bytes) {
        if (bytes == null)
            return null;

        T data;
        try {
            data = objectMapper.readValue(bytes, tClass);
        } catch (Exception e) {
            throw new SerializationException(e);
        }

        return data;
    }

    @Override
    public void close() {

    }
}


text:
export LD_LIBRARY_PATH=$(PWD)/libgit2/install/lib
export DYLD_LIBRARY_PATH=$(PWD)/libgit2/install/lib
export PKG_CONFIG_PATH=$(PWD)/libgit2/install/lib/pkgconfig
URL_BASE_GIT2GO=https://github.com/libgit2/git2go/archive
GIT2GO_VERSION=master
all: prepare build

test:
	@go test ./lexical/ ./parser/ ./semantical ./runtime

clean:
	@rm -rf ./libgit2

prepare: clean
	@echo "Preparing...\n"
	@chmod +x $(GOPATH)/src/github.com/cloudson/git2go/script/build-libgit2.sh
	@$(GOPATH)/src/github.com/cloudson/git2go/script/build-libgit2.sh

build:
	@echo "Building..."
	@go build
	@echo "Ready to go!"

install:
	@cp ./gitql /usr/local/bin/gitql
	@ln -s -f /usr/local/bin/gitql /usr/local/bin/git-ql
	@echo "Git is in /usr/local/bin/gitql"
	@echo "You can also use: git ql 'query here'"


text:
package ApiExamples;

// ********* THIS FILE IS AUTO PORTED *********

import org.testng.annotations.Test;
import com.aspose.words.Document;
import com.aspose.words.SmartTag;
import com.aspose.words.Run;
import com.aspose.words.CustomXmlProperty;
import org.testng.Assert;
import com.aspose.words.NodeType;
import com.aspose.words.DocumentVisitor;
import com.aspose.words.VisitorAction;
import com.aspose.ms.System.msConsole;
import com.aspose.ms.System.msString;
import com.aspose.words.CustomXmlPropertyCollection;
import java.util.Iterator;

@Test
class ExSmartTag !Test class should be public in Java to run, please fix .Net source!  extends ApiExampleBase
{
    //ExStart
    //ExFor:CompositeNode.RemoveSmartTags
    //ExFor:CustomXmlProperty
    //ExFor:CustomXmlProperty.#ctor(String,String,String)
    //ExFor:CustomXmlProperty.Name
    //ExFor:CustomXmlProperty.Value
    //ExFor:Markup.SmartTag
    //ExFor:Markup.SmartTag.#ctor(DocumentBase)
    //ExFor:Markup.SmartTag.Accept(DocumentVisitor)
    //ExFor:Markup.SmartTag.Element
    //ExFor:Markup.SmartTag.Properties
    //ExFor:Markup.SmartTag.Uri
    //ExSummary:Shows how to create smart tags.
    @Test //ExSkip
    public void create() throws Exception
    {
        Document doc = new Document();

        // A smart tag appears in a document with Microsoft Word recognizes a part of its text as some form of data,
        // such as a name, date, or address, and converts it to a hyperlink that displays a purple dotted underline.
        SmartTag smartTag = new SmartTag(doc);

        // Smart tags are composite nodes that contain their recognized text in its entirety.
        // Add contents to this smart tag manually.
        smartTag.appendChild(new Run(doc, "May 29, 2019"));

        // Microsoft Word may recognize the above contents as being a date.
        // Smart tags use the "Element" property to reflect the type of data they contain.
        smartTag.setElement("date");

        // Some smart tag types process their contents further into custom XML properties.
        smartTag.getProperties().add(new CustomXmlProperty("Day", "", "29"));
        smartTag.getProperties().add(new CustomXmlProperty("Month", "", "5"));
        smartTag.getProperties().add(new CustomXmlProperty("Year", "", "2019"));

        // Set the smart tag's URI to the default value.
        smartTag.setUri("urn:schemas-microsoft-com:office:smarttags");

        doc.getFirstSection().getBody().getFirstParagraph().appendChild(smartTag);
        doc.getFirstSection().getBody().getFirstParagraph().appendChild(new Run(doc, " is a date. "));

        // Create another smart tag for a stock ticker.
        smartTag = new SmartTag(doc);
        smartTag.setElement("stockticker");
        smartTag.setUri("urn:schemas-microsoft-com:office:smarttags");

        smartTag.appendChild(new Run(doc, "MSFT"));

        doc.getFirstSection().getBody().getFirstParagraph().appendChild(smartTag);
        doc.getFirstSection().getBody().getFirstParagraph().appendChild(new Run(doc, " is a stock ticker."));

        // Print all the smart tags in our document using a document visitor.
        doc.accept(new SmartTagPrinter());

        // Older versions of Microsoft Word support smart tags.
        doc.save(getArtifactsDir() + "SmartTag.Create.doc");

        // Use the "RemoveSmartTags" method to remove all smart tags from a document.
        Assert.assertEquals(2, doc.getChildNodes(NodeType.SMART_TAG, true).getCount());

        doc.removeSmartTags();

        Assert.assertEquals(0, doc.getChildNodes(NodeType.SMART_TAG, true).getCount());
        testCreate(new Document(getArtifactsDir() + "SmartTag.Create.doc")); //ExSkip
    }

    /// <summary>
    /// Prints visited smart tags and their contents.
    /// </summary>
    private static class SmartTagPrinter extends DocumentVisitor
    {
        /// <summary>
        /// Called when a SmartTag node is encountered in the document.
        /// </summary>
        public /*override*/ /*VisitorAction*/int visitSmartTagStart(SmartTag smartTag)
        {
            System.out.println("Smart tag type: {smartTag.Element}");
            return VisitorAction.CONTINUE;
        }

        /// <summary>
        /// Called when the visiting of a SmartTag node is ended.
        /// </summary>
        public /*override*/ /*VisitorAction*/int visitSmartTagEnd(SmartTag smartTag)
        {
            System.out.println("\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

            if (smartTag.getProperties().getCount() == 0)
            {
                System.out.println("\tContains no properties");
            }
            else
            {
                msConsole.write("\tProperties: ");
                String[] properties = new String[smartTag.getProperties().getCount()];
                int index = 0;

                for (CustomXmlProperty cxp : smartTag.getProperties())
                    properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";

                System.out.println(msString.join(", ", properties));
            }

            return VisitorAction.CONTINUE;
        }
    }
    //ExEnd

    @Test (enabled = false)
    public void testCreate(Document doc)
    {
        SmartTag smartTag = (SmartTag)doc.getChild(NodeType.SMART_TAG, 0, true);

        Assert.assertEquals("date", smartTag.getElement());
        Assert.assertEquals("May 29, 2019", smartTag.getText());
        Assert.assertEquals("urn:schemas-microsoft-com:office:smarttags", smartTag.getUri());

        Assert.assertEquals("Day", smartTag.getProperties().get(0).getName());
        Assert.assertEquals("", smartTag.getProperties().get(0).getUri());
        Assert.assertEquals("29", smartTag.getProperties().get(0).getValue());
        Assert.assertEquals("Month", smartTag.getProperties().get(1).getName());
        Assert.assertEquals("", smartTag.getProperties().get(1).getUri());
        Assert.assertEquals("5", smartTag.getProperties().get(1).getValue());
        Assert.assertEquals("Year", smartTag.getProperties().get(2).getName());
        Assert.assertEquals("", smartTag.getProperties().get(2).getUri());
        Assert.assertEquals("2019", smartTag.getProperties().get(2).getValue());

        smartTag = (SmartTag)doc.getChild(NodeType.SMART_TAG, 1, true);

        Assert.assertEquals("stockticker", smartTag.getElement());
        Assert.assertEquals("MSFT", smartTag.getText());
        Assert.assertEquals("urn:schemas-microsoft-com:office:smarttags", smartTag.getUri());
        Assert.assertEquals(0, smartTag.getProperties().getCount());
    }

    @Test
    public void properties() throws Exception
    {
        //ExStart
        //ExFor:CustomXmlProperty.Uri
        //ExFor:CustomXmlPropertyCollection
        //ExFor:CustomXmlPropertyCollection.Add(CustomXmlProperty)
        //ExFor:CustomXmlPropertyCollection.Clear
        //ExFor:CustomXmlPropertyCollection.Contains(String)
        //ExFor:CustomXmlPropertyCollection.Count
        //ExFor:CustomXmlPropertyCollection.GetEnumerator
        //ExFor:CustomXmlPropertyCollection.IndexOfKey(String)
        //ExFor:CustomXmlPropertyCollection.Item(Int32)
        //ExFor:CustomXmlPropertyCollection.Item(String)
        //ExFor:CustomXmlPropertyCollection.Remove(String)
        //ExFor:CustomXmlPropertyCollection.RemoveAt(Int32)
        //ExSummary:Shows how to work with smart tag properties to get in depth information about smart tags.
        Document doc = new Document(getMyDir() + "Smart tags.doc");

        // A smart tag appears in a document with Microsoft Word recognizes a part of its text as some form of data,
        // such as a name, date, or address, and converts it to a hyperlink that displays a purple dotted underline.
        // In Word 2003, we can enable smart tags via "Tools" -> "AutoCorrect options..." -> "SmartTags".
        // In our input document, there are three objects that Microsoft Word registered as smart tags.
        // Smart tags may be nested, so this collection contains more.
        SmartTag[] smartTags = doc.getChildNodes(NodeType.SMART_TAG, true).<SmartTag>OfType().ToArray();

        Assert.assertEquals(8, smartTags.length);

        // The "Properties" member of a smart tag contains its metadata, which will be different for each type of smart tag.
        // The properties of a "date"-type smart tag contain its year, month, and day.
        CustomXmlPropertyCollection properties = smartTags[7].getProperties();

        Assert.assertEquals(4, properties.getCount());

        Iterator<CustomXmlProperty> enumerator = properties.iterator();
        try /*JAVA: was using*/
        {
            while (enumerator.hasNext())
            {
                System.out.println("Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
                Assert.assertEquals("", enumerator.next().getUri());
            }
        }
        finally { if (enumerator != null) enumerator.close(); }

        // We can also access the properties in various ways, such as a key-value pair.
        Assert.assertTrue(properties.contains("Day"));
        Assert.assertEquals("22", properties.get("Day").getValue());
        Assert.assertEquals("2003", properties.get(2).getValue());
        Assert.assertEquals(1, properties.indexOfKey("Month"));

        // Below are three ways of removing elements from the properties collection.
        // 1 -  Remove by index:
        properties.removeAt(3);

        Assert.assertEquals(3, properties.getCount());

        // 2 -  Remove by name:
        properties.remove("Year");

        Assert.assertEquals(2, properties.getCount());

        // 3 -  Clear the entire collection at once:
        properties.clear();

        Assert.assertEquals(0, properties.getCount());
        //ExEnd
    }
}


text:
describe Notice do

  before do
    User.destroy

    @some_salt = Pibi.salt
    @u = User.create({
      name: 'Mysterious Mocker',
      email: 'very@mysterious.com',
      provider: 'pibi',
      password: @some_salt,
      password_confirmation: @some_salt
    })
  end

  it "should generate an email verification notice on user creation" do
    @u.email_verified.should == false
    @u.pending_notices.count.should == 1
    @u.pending_notices.first.type.should == 'email'
    @u.pending_notices.first.data.should == @u.email
  end

  it "should update the email verification status when the notice is accepted" do
    @u.email_verified.should == false
    @u.pending_notices.first.accept!
    @u.email_verified.should == true
    @u.pending_notices.count.should == 0
  end

  it "should reset the email verification status when the email address is updated" do
    @u.email_verified.should == false
    @u.pending_notices.first.accept!
    @u.email_verified.should == true

    # try with Resource#update
    @u.update({ email: 'more@mysterious.com' }).should be_true
    @u.saved?.should be_true
    @u.email_verified.should == false

    # try with Resource#save
    @u.pending_notices.first.accept!
    @u.email_verified.should == true
    @u.email = 'very@mysterious.com'
    @u.save.should be_true
    @u.email_verified.should == false
  end

  it "should generate a user temporary password notice" do
    @u.auto_password.should == false
    pnc = @u.pending_notices.count

    @u.generate_temporary_password
    @u.auto_password.should == true
    @u.pending_notices.count.should == pnc+1
  end

end


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.password_manager.settings;

/**
 * A Runnable which postpones running a given callback until it is itself run for a pre-defined
 * number of times. It is inspired by the native //base/barrier_closure.*. Unlike the native code,
 * SingleThreadBarrierClosure is only meant to be used on a single thread and is not thread-safe.
 */
public final class SingleThreadBarrierClosure implements Runnable {
    /** Counts the remaining number of runs. */
    private int mRemainingRuns;

    /** The callback to be run when {@link #mRemainingRuns} reaches 0.*/
    private final Runnable mCallback;

    /**
     * Construct a {@link Runnable} such that the first {@code runsExpected-1} calls to {@link #run}
     * are a no-op and the last one runs {@code callback}.
     * @param runsExpected The number of total {@link #run} calls expected.
     * @param callback The callback to be run once called enough times.
     */
    public SingleThreadBarrierClosure(int runsExpected, Runnable callback) {
        assert runsExpected > 0;
        assert callback != null;
        mRemainingRuns = runsExpected;
        mCallback = callback;
    }

    @Override
    public void run() {
        if (mRemainingRuns == 0) return;
        --mRemainingRuns;
        if (mRemainingRuns == 0) mCallback.run();
    }

    /**
     * Whether the next call to {@link #run} runs {@link #mCallback}.
     * @return True if the next call to {@link #run} runs {@link #mCallback}, false otherwise.
     */
    public boolean isReady() {
        return mRemainingRuns == 1;
    }
}


text:
.. raw:: html

   <!--
   Copyright 2015-2017 F5 Networks Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   -->

f5-openstack-docs
=================

|travis_badge| |slack_badge|

Introduction
------------
This repo contains documentation for the F5 Integrations for OpenStack Neutron LBaaS and OpenStack Heat.

Projects
--------
All of F5 Networks' OpenStack projects are open source and can be found at `github.com/F5Networks <https://github.com/F5Networks>`_.

Releases and Versioning
-----------------------
See `Releases and Support Matrix <http://clouddocs.f5.com/cloud/openstack/v1/support/releases-and-versioning.html>`_ on clouddocs.f5.com.

Documentation
-------------
Documentation is published on `clouddocs.f5.com <http://clouddocs.f5.com/cloud/openstack/>`_.

Filing Issues
-------------
We welcome feedback on our documentation!
If you find an issue or would like to request a new guide, please let us know by filing an `issue <https://github.com/F5Networks/f5-openstack-docs/issues>`_ in this repository; good issues contain specific and detailed information, such as links and line numbers.

Contributing
------------
See `Contributing <CONTRIBUTING.md>`_.

Copyright
---------
Copyright 2015-2017 F5 Networks, Inc.

Support
-------
See `Support <SUPPORT.md>`_.

License
-------

Apache V2.0
~~~~~~~~~~~
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Contributor License Agreement
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Individuals or business entities who contribute to this project must
have completed and submitted the `F5 Contributor License Agreement <http://f5-openstack-docs.readthedocs.org/cla_landing>`_ to Openstack_CLA@f5.com prior to their code submission being included
in this project.

.. |travis_badge| image:: https://travis-ci.org/F5Networks/f5-openstack-docs.svg?branch=master
   :target: https://travis-ci.org/F5Networks/f5-openstack-docs
   :alt: Documentation Status

.. |slack_badge| image:: https://f5-openstack-slack.herokuapp.com/badge.svg
   :target: https://f5-openstack-slack.herokuapp.com/
   :alt: Slack


text:
<?php

return [
    'NAV_HOME'                         => 'Home',
    'NAW_CONTACT'                      => 'Contact',
    'NAV_SIGNUP'                       => 'Signup',
    'NAV_LOGIN'                        => 'Login',
    'NAV_LOGOUT'                       => 'Logout',
    'NAV_PROFILE'                      => 'Profile',
    'BUTTON_SEND'                      => 'Send',
    'BUTTON_SAVE'                      => 'Save',
    'BUTTON_UPDATE'                    => 'Update',
    'BUTTON_DELETE'                    => 'Delete',
    'HELLO {username}'                 => 'Hello, {username}!',
    'FOLLOW_TO_RESET_PASSWORD'         => 'Follow the link below to reset your password:',
    'FOLLOW_TO_CONFIRM_EMAIL'          => 'Follow the link below to confirm your email:',
    'IGNORE_IF_DO_NOT_REGISTER'        => 'If you do not register on our site just remove this mail.',
    'REGISTER_PLEAS_FORM'              => 'Please fill out the following fields to signup:',
    'TITLE_CONTACT'                    => 'Contact',
    'CONTACT_THANKS'                   => 'Thank you for contacting us. We will respond to you as soon as possible.',
    'USER_USERNAME'                    => 'Username',
    'USER_PASSWORD'                    => 'Password',
    'USER_EMAIL'                       => 'Email',
    'USER_REMEMBER_ME'                 => 'Remember My',
    'LOGIN_FORM_TEXT'                  => 'Please fill out the following fields to login:',
    'VERIFY_CODE'                      => 'Verify Code',
    'PLEASE_FILL_FOR_RESET_REQUEST'    => 'Please fill out your email. A link to reset password will be sent there.',
    'TITLE_RESET_PASSWORD'             => 'Request password reset',
    'RESET_PASSWORD'                   => 'If you forgot your password you can',
    'RESET_IT'                         => 'reset it.',
    'ERROR_WRONG_USERNAME_OR_PASSWORD' => 'The username or password you entered is incorrect.',
    'ERROR_PROFILE_BLOCKED'            => 'Your account is blocked.',
    'ERROR_PROFILE_NOT_CONFIRMED'      => 'Your account has not been confirmed.',
    'CONFIRM_EMAIL'                    => 'Confirm your email address.',
    'THANK_YOUR_EMAIL_CONFIRM'         => 'Thank you! Your Email successfully confirmed',
    'ERROR_CONFIRMATION_EMAIL'         => 'Error confirmation email.',
    'EMAIL_SENT_PASSWORD_RECOVERY'     => 'Thank! In your E Mail sent a letter referring to the password recovery.',
    'PROBLEMS_SHIPMENT'                => 'Excuse me. We had problems with the shipment.',
    'PASSWORD_SUCCESS_CHANGE'          => 'Thank you! Password successfully changed.',
];


text:
using System.ComponentModel;
using System.Windows;
using EasySubtitle.WPF.ViewModels;

namespace EasySubtitle.WPF.Windows
{
    /// <summary>
    /// Interaction logic for ProgressDialogWindow.xaml
    /// </summary>
    public partial class ProgressDialogWindow : Window
    {
        public ProgressDialogWindow()
        {
            InitializeComponent();
        }

        private void OnWindowClosing(object sender, CancelEventArgs e)
        {
            var viewModel = (ProgressDialogViewModel)this.DataContext;
            viewModel.Cancel.Execute(null);
        }
    }
}


text:
   Hello , {{ name }}

   Your Paper titled {{ paperTitle }} has been published
   in the {{journalEdition}}.

   You can download your Paper Certificate from the website.

   Thanks

   From The Journal Team


text:
package fsa_easwari.sudoshutdown;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    public static final String HOST_KEY = "fsa_easwari.sudoshutdown.HOST";
    public static final String PORT_KEY = "fsa_easwari.sudoshutdown.PORT";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Retreving previous Host/Port setting
        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        final String host = preferences.getString(HOST_KEY, "");
        final int port = preferences.getInt(PORT_KEY, -1);

        final EditText hostField = (EditText) findViewById(R.id.etHost);
        final EditText portField = (EditText) findViewById(R.id.etPort);
        if (host != null && port != -1) {
            hostField.setText(host);
            portField.setText("" + port);
        }

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String tHost = "", tPort = "";
                tHost = hostField.getText().toString();
                tPort = portField.getText().toString();
                if (tHost.isEmpty() || tPort.isEmpty())
                    Snackbar.make(view, "Configure Host IP & Port Properly", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                else {
                    new ConnectThread(MainActivity.this).execute();

                    //updating previous Host/Port setting
                    if (!host.equals(tHost)) preferences.edit().putString(HOST_KEY, tHost).commit();
                    if (port != Integer.parseInt(tPort))
                        preferences.edit().putInt(PORT_KEY, Integer.parseInt(tPort)).commit();
                }
            }
        });
    }
}


text:
Wikify
======

Wikipedia Jquery Plugin

Wikify obtiene definiciones de wikipedia para tus textos y los muestra en una etiqueta. Necesitas instalar qtip2 desde http://qtip2.com/

Usos
======

	//Busca dentro de los elementos con clase "wiki" las palabras "lorem" y "dolor"
	//en la Wikipedia y muestra la definición
	$('.wiki').wikify
	({
		definitions: ['Lorem', 'dolor']
	});

	//Autocarga: Busca dentro de los elementos con clase "wikify" las palabras
	//especificadas en el atributo "params" separadas por "pipes(|)"
	$('.wikify').each(function(key, value)
	{
		var self   = $(this);
		var params = self.attr('params');
		self.wikify(
		{
			definitions: params.split('|')
		});
	});


text:
    <link rel="stylesheet" type="text/css" href="./css/style.css">

      <textarea id="input" style="display: none;"># Header

This is simple text.

*This text is italic.*

**This text is bold.**

- 1
- 2
- 3

Table example:

| First Header  | Second Header |
| ------------- | ------------- |
| Content Cell  | Content Cell  |
| Content Cell  | Content Cell  |

Code example:

```javascript
$(function(){
  console.log('test');
});
```</textarea>


text:
class Unit_TreasureBox :
	public UnitBase
{
private:
	int m_TreasureID;		// "ü'Á'Ä'¢'é•ó•¨'ÌID
	float m_FrameCount;		// ƒtƒŒ[ƒ€
public:
	Unit_TreasureBox(void);
	virtual ~Unit_TreasureBox(void);
	virtual void Init(void);
	virtual void Draw(void);
	virtual void Update(void);
	void AddDamage( int damage, int type, const VECTOR &value, UnitBase *enemy);
	// Žw'è'Ì•ó'ð"ü'ê'é
	void SetTreasureID(int id);
};

// ¶¬ŠÖ"
UnitBase* TreasureBox_CreateUnit(void);


text:
<?php

namespace Mss\S3\Exception;

/**
 * Temporary redirect.
 */
class RedirectException extends S3Exception {}


text:
import os

def relative_url_from_name(name):
    return "videos/%s" % name.replace(" ", "_")


text:
package org.mrgeo.mapalgebra

import java.awt.image.{DataBuffer, Raster}
import java.io.{Externalizable, IOException, ObjectInput, ObjectOutput}

import org.apache.spark.rdd.PairRDDFunctions
import org.apache.spark.{SparkConf, SparkContext}
import org.mrgeo.data.raster.RasterWritable
import org.mrgeo.data.rdd.RasterRDD
import org.mrgeo.image.MrsPyramidMetadata
import org.mrgeo.job.JobArguments
import org.mrgeo.mapalgebra.parser.{ParserException, ParserNode}
import org.mrgeo.mapalgebra.raster.RasterMapOp
import org.mrgeo.quantiles.Quantiles

import scala.language.existentials

object QuantilesMapOp extends MapOpRegistrar {
  override def register: Array[String] = {
    Array[String]("quantiles")
  }

  def create(raster: RasterMapOp, numQuantiles: Int, fraction:Float = 1.0f) =
    new QuantilesMapOp(Some(raster), Some(numQuantiles), Some(fraction))

  override def apply(node:ParserNode, variables: String => Option[ParserNode]): MapOp =
    new QuantilesMapOp(node, variables)
}

class QuantilesMapOp extends RasterMapOp with Externalizable {
  private var rasterRDD: Option[RasterRDD] = None

  private var inputMapOp: Option[RasterMapOp] = None
  private var numQuantiles: Option[Int] = None
  private var fraction: Option[Float] = None

  private[mapalgebra] def this(raster:Option[RasterMapOp], numQuantiles:Option[Int],
                               fraction: Option[Float]) = {
    this()

    this.inputMapOp = raster
    this.numQuantiles = numQuantiles
    this.fraction = fraction
  }

  def this(node: ParserNode, variables: String => Option[ParserNode]) {
    this()

    if ((node.getNumChildren < 2) || (node.getNumChildren > 3)) {
      throw new ParserException(
        "quantiles usage: quantiles(source raster, num quantiles, [percent of pixels to use])")
    }

    inputMapOp = RasterMapOp.decodeToRaster(node.getChild(0), variables)
    numQuantiles = MapOp.decodeInt(node.getChild(1), variables)
    if (numQuantiles.isEmpty) {
      throw new ParserException("The value for the numQuantiles parameter must be an integer")
    }
    if (node.getNumChildren > 2) {
      fraction = MapOp.decodeFloat(node.getChild(2), variables)
      fraction match {
        case Some(f) => {
          if ((f <= 0.0 || f > 1.0)) {
            throw new ParserException(
              "The fraction passed to quantiles " + f + " must be between 0.0 and 1.0")
          }
        }
        case None => throw new ParserException(
          "The value for the fraction parameter must be a number between 0.0 and 1.0");
      }
    }
  }

  override def rdd(): Option[RasterRDD] = {
    rasterRDD
  }

  override def registerClasses(): Array[Class[_]] = {
    Array[Class[_]](classOf[Array[Double]],
      classOf[Array[Float]],
      classOf[Array[Int]],
      classOf[Array[Short]],
      classOf[Array[Byte]],
      classOf[Array[Object]]
    )
  }

  override def execute(context: SparkContext): Boolean = {

    implicit val doubleOrdering = new Ordering[Double] {
      override def compare(x: Double, y: Double): Int = x.compareTo(y)
    }

    implicit val floatOrdering = new Ordering[Float] {
      override def compare(x: Float, y: Float): Int = x.compareTo(y)
    }

    implicit val intOrdering = new Ordering[Int] {
      override def compare(x: Int, y: Int): Int = x.compareTo(y)
    }

    implicit val shortOrdering = new Ordering[Short] {
      override def compare(x: Short, y: Short): Int = x.compareTo(y)
    }

    implicit val byteOrdering = new Ordering[Byte] {
      override def compare(x: Byte, y: Byte): Int = x.compareTo(y)
    }

    val input:RasterMapOp = inputMapOp getOrElse(throw new IOException("Input MapOp not valid!"))
    val numberOfQuantiles = numQuantiles getOrElse(throw new IOException("numQuantiles not valid!"))

    val meta = input.metadata() getOrElse(throw new IOException("Can't load metadata! Ouch! " + input.getClass.getName))
    rasterRDD = input.rdd()
    val rdd = rasterRDD getOrElse(throw new IOException("Can't load RDD! Ouch! " + inputMapOp.getClass.getName))
    // No reason to calculate metadata like raster map ops that actually compute a raster. This
    // map op does not compute the raster output, it just uses the input raster. All we need to
    // do is update the metadata already computed for the input raster map op.
//    metadata(SparkUtils.calculateMetadata(rasterRDD.get, meta.getMaxZoomLevel, meta.getDefaultValues,
//      bounds = meta.getBounds, calcStats = false))

    // Compute the quantile values and save them to metadata
    val quantiles = Quantiles.compute(rdd, numberOfQuantiles, fraction, meta)
    var b: Int = 0
    while (b < quantiles.length) {
      meta.setQuantiles(b, quantiles(b))
      b += 1
    }
    metadata(meta)
    true
  }

  override def setup(job: JobArguments, conf: SparkConf): Boolean = {
    true
  }

  override def teardown(job: JobArguments, conf: SparkConf): Boolean = {
    true
  }

  override def readExternal(in: ObjectInput): Unit = {}

  override def writeExternal(out: ObjectOutput): Unit = {}
}