text:
package stroom.util.concurrent;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

class TestAtomicLoopedItemSequence {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestAtomicLoopedItemSequence.class);

    @TestFactory
    Stream<DynamicTest> testGetNextItem() {

        return Stream.of(2, 3, 5, 7, 10, 99, 100, 401)
                .map(cnt ->
                        DynamicTest.dynamicTest("Count:" + cnt, () -> {
                            final AtomicLoopedItemSequence sequence = new AtomicLoopedItemSequence();
                            final LongAdder hitCount = new LongAdder();

                            final List<Integer> list = IntStream.rangeClosed(1, cnt)
                                    .boxed()
                                    .collect(Collectors.toList());

                            // Go round a few times to make sure it is looping properly
                            for (int j = 0; j < 3; j++) {
                                for (int i = 1; i < cnt + 1; i++) {
                                    Assertions.assertThat(sequence.getNextItem(list).get())
                                            .isEqualTo(i);
                                    hitCount.increment();
                                }
                            }
                            LOGGER.info("Got {} items", hitCount.sum());
                        }));
    }

    @Test
    void testGetNextItem_empty() {
        final AtomicLoopedItemSequence sequence = new AtomicLoopedItemSequence();
        final List<Integer> list = Collections.emptyList();

        final Optional<Integer> optItem = sequence.getNextItem(list);
        Assertions.assertThat(optItem)
                .isEmpty();
    }

    @Test
    void testGetNextItem_null() {
        final AtomicLoopedItemSequence sequence = new AtomicLoopedItemSequence();
        final List<Integer> list = null;

        final Optional<Integer> optItem = sequence.getNextItem(list);
        Assertions.assertThat(optItem)
                .isEmpty();
    }

    @Test
    void testGetNextItem_single() {
        final AtomicLoopedItemSequence sequence = new AtomicLoopedItemSequence();
        final List<Integer> list = List.of(123);

        final Optional<Integer> optItem = sequence.getNextItem(list);
        Assertions.assertThat(optItem)
                .isPresent();
        Assertions.assertThat(optItem.get())
                .isEqualTo(123);
    }

    @Test
    void testGetNextItem_changingListSize() {
        final AtomicLoopedItemSequence sequence = new AtomicLoopedItemSequence();
        final List<Integer> list = new ArrayList<>(List.of(1, 2, 3));

        Optional<Integer> optItem;
        optItem = sequence.getNextItem(list);
        Assertions.assertThat(optItem.get())
                .isEqualTo(1);

        list.add(4);

        optItem = sequence.getNextItem(list);
        Assertions.assertThat(optItem.get())
                .isEqualTo(2);

        list.add(5);

        optItem = sequence.getNextItem(list);
        Assertions.assertThat(optItem.get())
                .isEqualTo(3);

        list.add(6);

        optItem = sequence.getNextItem(list);
        Assertions.assertThat(optItem.get())
                .isEqualTo(4);

        optItem = sequence.getNextItem(list);
        Assertions.assertThat(optItem.get())
                .isEqualTo(5);

        optItem = sequence.getNextItem(list);
        Assertions.assertThat(optItem.get())
                .isEqualTo(6);

        optItem = sequence.getNextItem(list);
        Assertions.assertThat(optItem.get())
                .isEqualTo(1);
    }
}


text:
package com.bluesunshine.douban4droid.model.subject;

import com.bluesunshine.douban4droid.model.IDoubanObject;
import com.google.api.client.util.Key;
import java.util.List;

/**
 *
 * @author Zhibo Wei <uglytroll@dongxuexidu.com>
 */
public class DoubanSubjectFeedObj implements IDoubanObject{

  @Key
  private String title;

  @Key("opensearch:itemsPerPage")
  private int itemsPerPage;

  @Key("opensearch:startIndex")
  private int startIndex;

  @Key("opensearch:totalResults")
  private int totalResult;

  @Key("entry")
  private List<DoubanSubjectObj> subjects;

  @Override
  public String getObjName() {
    return "subjectfeed";
  }

  /**
   * @return the title
   */
  public String getTitle() {
    return title;
  }

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

  /**
   * @return the itemsPerPage
   */
  public int getItemsPerPage() {
    return itemsPerPage;
  }

  /**
   * @param itemsPerPage the itemsPerPage to set
   */
  public void setItemsPerPage(int itemsPerPage) {
    this.itemsPerPage = itemsPerPage;
  }

  /**
   * @return the startIndex
   */
  public int getStartIndex() {
    return startIndex;
  }

  /**
   * @param startIndex the startIndex to set
   */
  public void setStartIndex(int startIndex) {
    this.startIndex = startIndex;
  }

  /**
   * @return the totalResult
   */
  public int getTotalResult() {
    return totalResult;
  }

  /**
   * @param totalResult the totalResult to set
   */
  public void setTotalResult(int totalResult) {
    this.totalResult = totalResult;
  }

  /**
   * @return the subjects
   */
  public List<DoubanSubjectObj> getSubjects() {
    return subjects;
  }

  /**
   * @param subjects the subjects to set
   */
  public void setSubjects(List<DoubanSubjectObj> subjects) {
    this.subjects = subjects;
  }

}

redpajama_set_name: RedPajamaGithub


text:
Template.createTemplate.events({
	'click #btnCreate': function(e) {
		e.preventDefault();

		//call the meteor method createItemTemplate
		Meteor.call("createItemTemplate", {
			name: txtTemplateName.value,
			properties: taProperties.value.split("\n")
			},
			function(error, id) {
				if(error)
					Meteor.Errors.throw(error.reason);
				else
					Meteor.Router.to("viewItemTemplate", id);
			}
		);
	}
});


text:
package main

import (
	"./mbus"
	"bytes"
	"encoding/hex"
	"fmt"
	"github.com/ziutek/serial"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// Send data to the serial sending device, this function takes care
// of the binary encoding of the passed data.
// The data should be in format FF FF FF FF
func sendDataToSniffer(data string) {
	// Initialize the sender port
	var err error
	senderPort, err := serial.Open(*sniffingTTY)
	if err != nil {
		log.Fatal("Error: " + err.Error())
	}
	if err != nil {
		log.Fatal(err)
	}

	strippedData := strings.Split(data, " ")
	var checkSum uint64
	hexLiteral := []byte{}
	for index := range strippedData {
		actualByte, _ := strconv.ParseUint(strippedData[index], 16, 10)
		hexLiteral = append(hexLiteral, byte(actualByte))
		checkSum = checkSum ^ actualByte
	}

	// Append checksum
	hexLiteral = append(hexLiteral, byte(checkSum))
	senderPort.Write(hexLiteral)
	senderPort.Close()

	time.Sleep(time.Millisecond * 100)
}

// Reads continous the data from the connected serial device
func readData() {
	s, err := serial.Open(*sniffingTTY)
	if err != nil {
		log.Fatal("Error: " + err.Error())
	}
	snifferActive = true

	var buf []byte

	//	Reset the device
	sendDataToSniffer("FF 05 00")

	for {
		newData := make([]byte, 1000000)
		n, err := s.Read(newData)
		if n > 0 {
			// Sprintf is used here to prevent interpreting the bytes (e.g. 0x13 as newline character)
			buf = append(buf, fmt.Sprintf("%s", hex.EncodeToString(newData[:n]))...)
			if err != nil {
				log.Fatal(err)
			}

			if bytes.Count(buf, []byte("ff03")) > 0 && snifferActive {
				frames := strings.Split(fmt.Sprintf("%s", buf), "ff03")

				for i := range frames {
					// Only proceed if we received the length byte as we will only read until there
					if len(frames[i]) > 2 {
						decodedString, err := hex.DecodeString(fmt.Sprintf("%s", frames[i][:2]))

						if err == nil {
							// The sniffer appends +1 to the length byte, therefore we have to decrement the value
							lengthByte, err := strconv.Atoi(fmt.Sprintf("%d", decodedString[0]))
							if err == nil {
								lengthByte = lengthByte - 1
								newLength := fmt.Sprintf("%#x", lengthByte)

								// Only read if the length is correct
								if len(frames[i]) >= (lengthByte*2)+2 && lengthByte > 10 {
									frame, _ := mbus.NewFrame(fmt.Sprintf("%s", strings.ToUpper(newLength[2:]+frames[i][2:(lengthByte*2)+2])))
									// HACK: Only sniff encrypted frames
									if frame.Configuration() != "0000" && frame.Configuration() != "" {
										go addFrameToDB(frame)
									}

									buf = []byte(strings.Join(frames[i+1:], ""))
								}
							}
						}

					}
				}

				// Just drop everything if the sniffer is not active
				if !snifferActive {
					buf = []byte("")
				}
			}
		}
	}
}

// Contains the current sniffer state (active/stopped)
var snifferActive bool

// Disable or enable the sniffer
func statusSnifferHandler(w http.ResponseWriter, r *http.Request) {
	if r.FormValue("status") == "stop" {
		snifferActive = false
	} else {
		snifferActive = true
	}
}


text:
package org.elasticsearch.xpack.security.action.service;

import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xpack.core.security.action.service.GetServiceAccountRequest;
import org.elasticsearch.xpack.core.security.action.service.GetServiceAccountResponse;
import org.elasticsearch.xpack.security.authc.support.HttpTlsRuntimeCheck;
import org.junit.Before;

import java.util.Collections;

import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;

public class TransportGetServiceAccountActionTests extends ESTestCase {

    private HttpTlsRuntimeCheck httpTlsRuntimeCheck;
    private TransportGetServiceAccountAction transportGetServiceAccountAction;

    @Before
    public void init() {
        httpTlsRuntimeCheck = mock(HttpTlsRuntimeCheck.class);
        transportGetServiceAccountAction = new TransportGetServiceAccountAction(
            mock(TransportService.class), new ActionFilters(Collections.emptySet()), httpTlsRuntimeCheck);

        doAnswer(invocationOnMock -> {
            final Object[] arguments = invocationOnMock.getArguments();
            ((Runnable) arguments[2]).run();
            return null;
        }).when(httpTlsRuntimeCheck).checkTlsThenExecute(any(), any(), any());
    }

    public void testDoExecute() {
        final GetServiceAccountRequest request1 = randomFrom(
            new GetServiceAccountRequest(null, null),
            new GetServiceAccountRequest("elastic", null),
            new GetServiceAccountRequest("elastic", "fleet-server"));
        final PlainActionFuture<GetServiceAccountResponse> future1 = new PlainActionFuture<>();
        transportGetServiceAccountAction.doExecute(mock(Task.class), request1, future1);
        final GetServiceAccountResponse getServiceAccountResponse1 = future1.actionGet();
        assertThat(getServiceAccountResponse1.getServiceAccountInfos().length, equalTo(1));
        assertThat(getServiceAccountResponse1.getServiceAccountInfos()[0].getPrincipal(), equalTo("elastic/fleet-server"));

        final GetServiceAccountRequest request2 = randomFrom(
            new GetServiceAccountRequest("foo", null),
            new GetServiceAccountRequest("elastic", "foo"),
            new GetServiceAccountRequest("foo", "bar"));
        final PlainActionFuture<GetServiceAccountResponse> future2 = new PlainActionFuture<>();
        transportGetServiceAccountAction.doExecute(mock(Task.class), request2, future2);
        final GetServiceAccountResponse getServiceAccountResponse2 = future2.actionGet();
        assertThat(getServiceAccountResponse2.getServiceAccountInfos().length, equalTo(0));
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Package com.wfemmer.sinkmap
</TITLE>

<META NAME="date" CONTENT="2010-11-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
com.wfemmer.sinkmap

Classes in com.wfemmer.sinkmap used by com.wfemmer.sinkmap

DimensionMethods

Dimensions

Indicators

          An enumeration of pre-collapse indicators for a subsidence event.

LandUses

Shapes

Sinkhole

          A class representing a sinkhole.

SubsidenceRates

          An enumeration of the rates at which subsidence may have occurred.

Topologies

Triggers

          An enumeration of the possible triggers related
 to a subsidence event.

YesNo

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (C) 2013-2015 by Michael Hombre Brinkmann
  -->

<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com" xsi:schemaLocation="http://www.zeroturnaround.com http://www.zeroturnaround.com/alderaan/rebel-2_0.xsd">

	<classpath>
		<dir name="/home/hombre/Projekte/twibs-parent/twibs-form-test-webapp/target/classes">
		</dir>
        <dir name="/home/hombre/Projekte/twibs-parent/twibs-util/target/classes">
        </dir>
        <dir name="/home/hombre/Projekte/twibs-parent/twibs-web/target/classes">
        </dir>
        <dir name="/home/hombre/Projekte/twibs-parent/twibs-form/target/classes">
        </dir>
	</classpath>

	<web>
		<link target="/">
			<dir name="/home/hombre/Projekte/twibs-parent/twibs-form-test-webapp/src/main/webapp">
			</dir>
		</link>
	</web>

</application>


text:
package nats_output

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net"
	"strings"
	"sync"
	"text/template"
	"time"

	"github.com/google/uuid"
	"github.com/nats-io/nats.go"
	"github.com/openconfig/gnmic/formatters"
	"github.com/openconfig/gnmic/outputs"
	"github.com/openconfig/gnmic/types"
	"github.com/openconfig/gnmic/utils"
	"github.com/prometheus/client_golang/prometheus"
	"google.golang.org/protobuf/proto"
)

const (
	natsConnectWait         = 2 * time.Second
	natsReconnectBufferSize = 100 * 1024 * 1024
	defaultSubjectName      = "telemetry"
	defaultFormat           = "event"
	defaultNumWorkers       = 1
	defaultWriteTimeout     = 5 * time.Second
	defaultAddress          = "localhost:4222"
	loggingPrefix           = "[nats_output:%s] "
)

func init() {
	outputs.Register("nats", func() outputs.Output {
		return &NatsOutput{
			Cfg:    &Config{},
			wg:     new(sync.WaitGroup),
			logger: log.New(io.Discard, loggingPrefix, utils.DefaultLoggingFlags),
		}
	})
}

// NatsOutput //
type NatsOutput struct {
	Cfg      *Config
	ctx      context.Context
	cancelFn context.CancelFunc
	msgChan  chan *outputs.ProtoMsg
	wg       *sync.WaitGroup
	logger   *log.Logger
	mo       *formatters.MarshalOptions
	evps     []formatters.EventProcessor

	targetTpl *template.Template
	msgTpl    *template.Template
}

// Config //
type Config struct {
	Name               string        `mapstructure:"name,omitempty"`
	Address            string        `mapstructure:"address,omitempty"`
	SubjectPrefix      string        `mapstructure:"subject-prefix,omitempty"`
	Subject            string        `mapstructure:"subject,omitempty"`
	Username           string        `mapstructure:"username,omitempty"`
	Password           string        `mapstructure:"password,omitempty"`
	ConnectTimeWait    time.Duration `mapstructure:"connect-time-wait,omitempty"`
	Format             string        `mapstructure:"format,omitempty"`
	AddTarget          string        `mapstructure:"add-target,omitempty"`
	TargetTemplate     string        `mapstructure:"target-template,omitempty"`
	MsgTemplate        string        `mapstructure:"msg-template,omitempty"`
	OverrideTimestamps bool          `mapstructure:"override-timestamps,omitempty"`
	NumWorkers         int           `mapstructure:"num-workers,omitempty"`
	WriteTimeout       time.Duration `mapstructure:"write-timeout,omitempty"`
	Debug              bool          `mapstructure:"debug,omitempty"`
	EnableMetrics      bool          `mapstructure:"enable-metrics,omitempty"`
	EventProcessors    []string      `mapstructure:"event-processors,omitempty"`
}

func (n *NatsOutput) String() string {
	b, err := json.Marshal(n)
	if err != nil {
		return ""
	}
	return string(b)
}

func (n *NatsOutput) SetLogger(logger *log.Logger) {
	if logger != nil && n.logger != nil {
		n.logger.SetOutput(logger.Writer())
		n.logger.SetFlags(logger.Flags())
	}
}

func (n *NatsOutput) SetEventProcessors(ps map[string]map[string]interface{},
	logger *log.Logger,
	tcs map[string]*types.TargetConfig,
	acts map[string]map[string]interface{}) {
	for _, epName := range n.Cfg.EventProcessors {
		if epCfg, ok := ps[epName]; ok {
			epType := ""
			for k := range epCfg {
				epType = k
				break
			}
			if in, ok := formatters.EventProcessors[epType]; ok {
				ep := in()
				err := ep.Init(epCfg[epType],
					formatters.WithLogger(logger),
					formatters.WithTargets(tcs),
					formatters.WithActions(acts))
				if err != nil {
					n.logger.Printf("failed initializing event processor '%s' of type='%s': %v", epName, epType, err)
					continue
				}
				n.evps = append(n.evps, ep)
				n.logger.Printf("added event processor '%s' of type=%s to nats output", epName, epType)
				continue
			}
			n.logger.Printf("%q event processor has an unknown type=%q", epName, epType)
			continue
		}
		n.logger.Printf("%q event processor not found!", epName)
	}
}

// Init //
func (n *NatsOutput) Init(ctx context.Context, name string, cfg map[string]interface{}, opts ...outputs.Option) error {
	err := outputs.DecodeConfig(cfg, n.Cfg)
	if err != nil {
		return err
	}
	if n.Cfg.Name == "" {
		n.Cfg.Name = name
	}
	n.logger.SetPrefix(fmt.Sprintf(loggingPrefix, n.Cfg.Name))

	for _, opt := range opts {
		opt(n)
	}
	err = n.setDefaults()
	if err != nil {
		return err
	}

	n.msgChan = make(chan *outputs.ProtoMsg)
	initMetrics()
	n.mo = &formatters.MarshalOptions{
		Format:     n.Cfg.Format,
		OverrideTS: n.Cfg.OverrideTimestamps,
	}
	if n.Cfg.TargetTemplate == "" {
		n.targetTpl = outputs.DefaultTargetTemplate
	} else if n.Cfg.AddTarget != "" {
		n.targetTpl, err = utils.CreateTemplate("target-template", n.Cfg.TargetTemplate)
		if err != nil {
			return err
		}
		n.targetTpl = n.targetTpl.Funcs(outputs.TemplateFuncs)
	}

	if n.Cfg.MsgTemplate != "" {
		n.msgTpl, err = utils.CreateTemplate("msg-template", n.Cfg.MsgTemplate)
		if err != nil {
			return err
		}
		n.msgTpl = n.msgTpl.Funcs(outputs.TemplateFuncs)
	}

	n.ctx, n.cancelFn = context.WithCancel(ctx)
	n.wg.Add(n.Cfg.NumWorkers)
	for i := 0; i < n.Cfg.NumWorkers; i++ {
		cfg := *n.Cfg
		cfg.Name = fmt.Sprintf("%s-%d", cfg.Name, i)
		go n.worker(ctx, i, &cfg)
	}

	go func() {
		<-ctx.Done()
		n.Close()
	}()
	return nil
}

func (n *NatsOutput) setDefaults() error {
	if n.Cfg.Format == "" {
		n.Cfg.Format = defaultFormat
	}
	if !(n.Cfg.Format == "event" || n.Cfg.Format == "protojson" || n.Cfg.Format == "proto" || n.Cfg.Format == "json") {
		return fmt.Errorf("unsupported output format '%s' for output type NATS", n.Cfg.Format)
	}
	if n.Cfg.Address == "" {
		n.Cfg.Address = defaultAddress
	}
	if n.Cfg.ConnectTimeWait <= 0 {
		n.Cfg.ConnectTimeWait = natsConnectWait
	}
	if n.Cfg.Subject == "" && n.Cfg.SubjectPrefix == "" {
		n.Cfg.Subject = defaultSubjectName
	}
	if n.Cfg.Name == "" {
		n.Cfg.Name = "gnmic-" + uuid.New().String()
	}
	if n.Cfg.NumWorkers <= 0 {
		n.Cfg.NumWorkers = defaultNumWorkers
	}
	if n.Cfg.WriteTimeout <= 0 {
		n.Cfg.WriteTimeout = defaultWriteTimeout
	}
	return nil
}

// Write //
func (n *NatsOutput) Write(ctx context.Context, rsp proto.Message, meta outputs.Meta) {
	if rsp == nil || n.mo == nil {
		return
	}

	wctx, cancel := context.WithTimeout(ctx, n.Cfg.WriteTimeout)
	defer cancel()

	select {
	case <-ctx.Done():
		return
	case n.msgChan <- outputs.NewProtoMsg(rsp, meta):
	case <-wctx.Done():
		if n.Cfg.Debug {
			n.logger.Printf("writing expired after %s, NATS output might not be initialized", n.Cfg.WriteTimeout)
		}
		if n.Cfg.EnableMetrics {
			NatsNumberOfFailSendMsgs.WithLabelValues(n.Cfg.Name, "timeout").Inc()
		}
		return
	}
}

func (n *NatsOutput) WriteEvent(ctx context.Context, ev *formatters.EventMsg) {}

// Close //
func (n *NatsOutput) Close() error {
	//	n.conn.Close()
	n.cancelFn()
	n.wg.Wait()
	return nil
}

// Metrics //
func (n *NatsOutput) RegisterMetrics(reg *prometheus.Registry) {
	if !n.Cfg.EnableMetrics {
		return
	}
	if err := registerMetrics(reg); err != nil {
		n.logger.Printf("failed to register metric: %+v", err)
	}
}

func (n *NatsOutput) createNATSConn(c *Config) (*nats.Conn, error) {
	opts := []nats.Option{
		nats.Name(c.Name),
		nats.SetCustomDialer(n),
		nats.ReconnectWait(n.Cfg.ConnectTimeWait),
		nats.ReconnectBufSize(natsReconnectBufferSize),
		nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
			n.logger.Printf("NATS error: %v", err)
		}),
		nats.DisconnectHandler(func(c *nats.Conn) {
			n.logger.Println("Disconnected from NATS")
		}),
		nats.ClosedHandler(func(c *nats.Conn) {
			n.logger.Println("NATS connection is closed")
		}),
	}
	if c.Username != "" && c.Password != "" {
		opts = append(opts, nats.UserInfo(c.Username, c.Password))
	}
	nc, err := nats.Connect(c.Address, opts...)
	if err != nil {
		return nil, err
	}
	return nc, nil
}

// Dial //
func (n *NatsOutput) Dial(network, address string) (net.Conn, error) {
	ctx, cancel := context.WithCancel(n.ctx)
	defer cancel()

	for {
		n.logger.Printf("attempting to connect to %s", address)
		if ctx.Err() != nil {
			return nil, ctx.Err()
		}

		select {
		case <-n.ctx.Done():
			return nil, n.ctx.Err()
		default:
			d := &net.Dialer{}
			if conn, err := d.DialContext(ctx, network, address); err == nil {
				n.logger.Printf("successfully connected to NATS server %s", address)
				return conn, nil
			}
			time.Sleep(n.Cfg.ConnectTimeWait)
		}
	}
}

func (n *NatsOutput) worker(ctx context.Context, i int, cfg *Config) {
	defer n.wg.Done()
	var natsConn *nats.Conn
	var err error
	workerLogPrefix := fmt.Sprintf("worker-%d", i)
	n.logger.Printf("%s starting", workerLogPrefix)
CRCONN:
	natsConn, err = n.createNATSConn(cfg)
	if err != nil {
		n.logger.Printf("%s failed to create connection: %v", workerLogPrefix, err)
		time.Sleep(n.Cfg.ConnectTimeWait)
		goto CRCONN
	}
	defer natsConn.Close()
	n.logger.Printf("%s initialized nats producer: %+v", workerLogPrefix, cfg)
	for {
		select {
		case <-ctx.Done():
			n.logger.Printf("%s flushing", workerLogPrefix)
			natsConn.FlushTimeout(time.Second)
			n.logger.Printf("%s shutting down", workerLogPrefix)
			return
		case m := <-n.msgChan:
			pmsg := m.GetMsg()
			pmsg, err = outputs.AddSubscriptionTarget(pmsg, m.GetMeta(), n.Cfg.AddTarget, n.targetTpl)
			if err != nil {
				n.logger.Printf("failed to add target to the response: %v", err)
			}
			b, err := n.mo.Marshal(pmsg, m.GetMeta(), n.evps...)
			if err != nil {
				if n.Cfg.Debug {
					n.logger.Printf("%s failed marshaling proto msg: %v", workerLogPrefix, err)
				}
				if n.Cfg.EnableMetrics {
					NatsNumberOfFailSendMsgs.WithLabelValues(cfg.Name, "marshal_error").Inc()
				}
				continue
			}

			if n.msgTpl != nil && len(b) > 0 {
				b, err = outputs.ExecTemplate(b, n.msgTpl)
				if err != nil {
					if n.Cfg.Debug {
						log.Printf("failed to execute template: %v", err)
					}
					NatsNumberOfFailSendMsgs.WithLabelValues(cfg.Name, "template_error").Inc()
					return
				}
			}

			subject := n.subjectName(cfg, m.GetMeta())
			var start time.Time
			if n.Cfg.EnableMetrics {
				start = time.Now()
			}
			err = natsConn.Publish(subject, b)
			if err != nil {
				if n.Cfg.Debug {
					n.logger.Printf("%s failed to write to nats subject '%s': %v", workerLogPrefix, subject, err)
				}
				if n.Cfg.EnableMetrics {
					NatsNumberOfFailSendMsgs.WithLabelValues(cfg.Name, "publish_error").Inc()
				}
				natsConn.Close()
				time.Sleep(cfg.ConnectTimeWait)
				goto CRCONN
			}
			if n.Cfg.EnableMetrics {
				NatsSendDuration.WithLabelValues(cfg.Name).Set(float64(time.Since(start).Nanoseconds()))
				NatsNumberOfSentMsgs.WithLabelValues(cfg.Name, subject).Inc()
				NatsNumberOfSentBytes.WithLabelValues(cfg.Name, subject).Add(float64(len(b)))
			}
		}
	}
}

func (n *NatsOutput) subjectName(c *Config, meta outputs.Meta) string {
	if c.SubjectPrefix != "" {
		ssb := strings.Builder{}
		ssb.WriteString(n.Cfg.SubjectPrefix)
		if s, ok := meta["source"]; ok {
			source := strings.ReplaceAll(s, ".", "-")
			source = strings.ReplaceAll(source, " ", "_")
			ssb.WriteString(".")
			ssb.WriteString(source)
		}
		if subname, ok := meta["subscription-name"]; ok {
			ssb.WriteString(".")
			ssb.WriteString(subname)
		}
		return strings.ReplaceAll(ssb.String(), " ", "_")
	}
	return strings.ReplaceAll(n.Cfg.Subject, " ", "_")
}

func (n *NatsOutput) SetName(name string) {
	sb := strings.Builder{}
	if name != "" {
		sb.WriteString(name)
		sb.WriteString("-")
	}
	sb.WriteString(n.Cfg.Name)
	sb.WriteString("-nats-pub")
	n.Cfg.Name = sb.String()
}

func (n *NatsOutput) SetClusterName(name string) {}

func (n *NatsOutput) SetTargetsConfig(map[string]*types.TargetConfig) {}


text:
package org.apache.jmeter.visualizers;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;

import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.gui.Searchable;
import org.apache.jmeter.gui.action.RawTextSearcher;
import org.apache.jmeter.gui.action.RegexpSearcher;
import org.apache.jmeter.gui.action.Searcher;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.gui.JLabeledTextField;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

/**
 * Panel used by {@link ViewResultsFullVisualizer} to search for data within the Tree
 * @since 3.0
 */
public class SearchTreePanel extends JPanel implements ActionListener {

    private static final long serialVersionUID = -4436834972710248247L;

    private static final Logger LOG = LoggingManager.getLoggerForClass();

    private static final Font FONT_DEFAULT = UIManager.getDefaults().getFont("TextField.font");

    private static final Font FONT_SMALL = new Font("SansSerif", Font.PLAIN, (int) Math.round(FONT_DEFAULT.getSize() * 0.8));

    private JButton searchButton;

    private JLabeledTextField searchTF;

    private JCheckBox isRegexpCB;

    private JCheckBox isCaseSensitiveCB;

    private JButton resetButton;

    private DefaultMutableTreeNode defaultMutableTreeNode;

    public SearchTreePanel(DefaultMutableTreeNode defaultMutableTreeNode) {
        super();
        init();
        this.defaultMutableTreeNode = defaultMutableTreeNode;
    }

    /**
     * @deprecated only for use by test code
     */
    @Deprecated
    public SearchTreePanel(){
//        log.warn("Constructor only intended for use in testing"); // $NON-NLS-1$
    }

    private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final)
        setLayout(new BorderLayout(10,10));

        searchTF = new JLabeledTextField(JMeterUtils.getResString("search_text_field"), 20); //$NON-NLS-1$
        isRegexpCB = new JCheckBox(JMeterUtils.getResString("search_text_chkbox_regexp"), false); //$NON-NLS-1$
        isCaseSensitiveCB = new JCheckBox(JMeterUtils.getResString("search_text_chkbox_case"), false); //$NON-NLS-1$

        isRegexpCB.setFont(FONT_SMALL);
        isCaseSensitiveCB.setFont(FONT_SMALL);

        searchButton = new JButton(JMeterUtils.getResString("search")); //$NON-NLS-1$
        searchButton.addActionListener(this);
        resetButton = new JButton(JMeterUtils.getResString("reset")); //$NON-NLS-1$
        resetButton.addActionListener(this);

        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

        searchPanel.add(searchTF);
        searchPanel.add(isCaseSensitiveCB);
        searchPanel.add(isRegexpCB);
        searchPanel.add(searchButton);
        searchPanel.add(resetButton);
        add(searchPanel);
    }

    /**
     * Do search
     * @param e {@link ActionEvent}
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == searchButton) {
            doSearch(e);
        } else if (e.getSource() == resetButton) {
            doResetSearch((SearchableTreeNode)defaultMutableTreeNode);
        }
    }

    /**
     * @param searchableTreeNode
     */
    private void doResetSearch(SearchableTreeNode searchableTreeNode) {
        searchableTreeNode.reset();
        searchableTreeNode.updateState();
        for (int i = 0; i < searchableTreeNode.getChildCount(); i++) {
            doResetSearch((SearchableTreeNode)searchableTreeNode.getChildAt(i));
        }
    }

    /**
     * @param e {@link ActionEvent}
     */
    private void doSearch(ActionEvent e) {
        String wordToSearch = searchTF.getText();
        if (StringUtils.isEmpty(wordToSearch)) {
            return;
        }
        Searcher searcher = null;
        if (isRegexpCB.isSelected()) {
            searcher = new RegexpSearcher(isCaseSensitiveCB.isSelected(), searchTF.getText());
        } else {
            searcher = new RawTextSearcher(isCaseSensitiveCB.isSelected(), searchTF.getText());
        }

        searchInNode(searcher, (SearchableTreeNode)defaultMutableTreeNode);
    }

    /**
     * @param searcher
     * @param node
     */
    private boolean searchInNode(Searcher searcher, SearchableTreeNode node) {
        node.reset();
        Object userObject = node.getUserObject();

        try {
            Searchable searchable = null;
            if(userObject instanceof Searchable) {
                searchable = (Searchable) userObject;
            } else {
                return false;
            }
            if(searcher.search(searchable.getSearchableTokens())) {
                node.setNodeHasMatched(true);
            }
            boolean foundInChildren = false;
            for (int i = 0; i < node.getChildCount(); i++) {
                searchInNode(searcher, (SearchableTreeNode)node.getChildAt(i));
                foundInChildren =
                        searchInNode(searcher, (SearchableTreeNode)node.getChildAt(i))
                        || foundInChildren; // Must be the last in condition
            }
            if(!node.isNodeHasMatched()) {
                node.setChildrenNodesHaveMatched(foundInChildren);
            }
            node.updateState();
            return node.isNodeHasMatched() || node.isChildrenNodesHaveMatched();
        } catch (Exception e) {
            LOG.error("Error extracting data from tree node");
            return false;
        }
    }
}


text:
*************************
linear programming
*************************

Linear programming [LP]_ is a technique for the optimization of a linear objective function, subject to linear equality and linear inequality constraints such as:

.. math::

    \begin{align} & \text{maximize} && \mathbf{c}^\mathrm{T} \mathbf{x}\\
    & \text{subject to} && A \mathbf{x} \leq \mathbf{b} \\
    & \text{and} && \mathbf{x} \ge \mathbf{0} \end{align}

where ``x`` represents the vector of variables (to be determined), ``c`` and ``b`` are vectors of (known) coefficients, ``A`` is a (known) matrix of coefficients.

openMVG linear programming tools
---------------------------------

openMVG provides tools to:

- configure Linear programs (LP container),
- solve Linear Programs (convex or quasi convex ones).

It results in a collection of L infinity based solver for computer vision problems.

.. toctree::
  :maxdepth: 1

  linfinityCV.rst

openMVG linear program container
---------------------------------

openMVG provides a generic container for LP (Linear Programming problems) that can be dense of sparse.

.. code-block:: c++

  // Dense LP
  LP_Constraints
  // Sparse LP
  LP_Constraints_Sparse

It allows to embed:

- objective function ``c`` and the problem type (minimization or maximization),
- constraints (coefficients ``A``, Sign, objective value ``b``),
- bounds over ``x`` parameters (<=, =, >=).

openMVG linear program solvers
---------------------------------

openMVG provide access to different solvers (not exhaustive):

- OSI_CLP (COIN-OR) project,
- MOSEK commercial, free in a research context.

Those solver have been choosen due to the stability of their results and ability to handle large problems without numerical stability (LPSolve and GPLK have been discarded after extensive experiments).

I refer the reader to openMVG/src/openMVG/linearProgramming/linear_programming_test.cpp to know more.

openMVG linear programming module usage
-------------------------------------------

The linear programming module of openMVG can be used for:

- solve classical linear problem (optimization),
- test the feasibility of linear problem,
- optimize upper bound of feasible problem (quasi-convex linear programs).

**classical linear problem solving (optimization)**

Here an example of usage of the framework:

.. code-block:: c++

  // Setup the LP (fill A,b,c and the constraint over x)
  LP_Constraints cstraint;
  BuildLinearProblem(cstraint);

  // Solve the LP with the solver of your choice
  std::vector<double> vec_solution(2);
  #if OPENMVG_HAVE_MOSEK
    MOSEK_SolveWrapper solver(2);
  #else
    OSI_CLP_SolverWrapper solver(2);
  #endif
  // Send constraint to the LP solver
  solver.setup(cstraint);

  // If LP have a solution
  if (solver.solve())
    // Get back estimated parameters
    solver.getSolution(vec_solution);

**Linear programming, feasible problem**

openMVG can be use also to test only the feasibility of a given LP

.. math::

    \begin{align} & \text{find} && \mathbf{x}\\
    & \text{subject to} && A \mathbf{x} \leq \mathbf{b} \\
    & \text{and} && \mathbf{x} \ge \mathbf{0} \end{align}

**Linear programming, quasi convex optimization**

openMVG used a lot of L infinity minimisation formulation.
Often the posed problems are quasi-convex and dependent of an external parameter that we are looking for (i.e the maximal re-projection error for which the set of contraint is still feasible).

Optimization of this upper bound parameter can be done by iterating over all the possible value or by using a bisection that reduce the search range at each iteration.

.. code-block:: c++

  Require: gammaLow, gammUp (Low and upper bound of the parameter to optimize)
  Require: the LP problem (cstraintBuilder)
  Ensure: the optimal gamma value, or return infeasibility of the contraints set.

  BisectionLP(
    LP_Solver & solver,
    ConstraintBuilder & cstraintBuilder,
    double gammaUp  = 1.0,  // Upper bound
    double gammaLow = 0.0,  // lower bound
    double eps      = 1e-8, // precision that stop dichotomy
    const int maxIteration = 20) // max number of iteration
  {
    ConstraintType constraint;
    do
    {
      ++k; // One more iteration

      double gamma = (gammaLow + gammaUp) / 2.0;

      //-- Setup constraint and solver
      cstraintBuilder.Build(gamma, constraint);
      solver.setup( constraint );

      //-- Solving
      bool bFeasible = solver.solve();

      //-- According feasibility update the corresponding bound
      //-> Feasible, update the upper bound
      //-> Not feasible, update the lower bound
      (bFeasible) ? gammaUp = gamma; : gammaLow = gamma;

    } while (k < maxIteration && gammaUp - gammaLow > eps);
  }


text:
// Copyright (c) 2012 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.

#include "pong_input.h"

#include <stdlib.h>

namespace {

// Input event key codes.  PPAPI uses Windows Virtual key codes.
const uint32_t kUpArrow = 0x26;
const uint32_t kDownArrow = 0x28;

/** When the distance between the ball and the center of the paddle is within
 * kPaddleAIDeadZone pixels, don't move the paddle. This keeps the paddle from
 * bouncing if it can move faster than the ball.
 */
const int kPaddleAIDeadZone = 20;

}

PongInputKeyboard::PongInputKeyboard(PongInputKeyboardDelegate* delegate)
    : delegate_(delegate) {}

MoveDirection PongInputKeyboard::GetMove(const PongModel& model,
                                         bool is_left_paddle) {
  if (delegate_->IsKeyDown(kUpArrow))
    return MOVE_UP;
  else if (delegate_->IsKeyDown(kDownArrow))
    return MOVE_DOWN;
  else
    return MOVE_NONE;
}

MoveDirection PongInputAI::GetMove(const PongModel& model,
                                   bool is_left_paddle) {
  // A highly advanced AI algorithm that moves the paddle toward the y position
  // of the ball.
  const PaddleModel& paddle =
      is_left_paddle ? model.left_paddle() : model.right_paddle();
  int ball_center_y = model.ball().rect.CenterPoint().y();
  int paddle_center_y = paddle.rect.CenterPoint().y();
  int distance_y = labs(paddle_center_y - ball_center_y);

  if (distance_y < kPaddleAIDeadZone)
    return MOVE_NONE;
  else if (paddle_center_y > ball_center_y)
    return MOVE_UP;
  else
    return MOVE_DOWN;
}


text:
package nano

import (
	"image/color"

	"github.com/spf13/cobra"

	"github.com/yesnault/blinkstick"
	"github.com/yesnault/blinkstick/cli/blink/internal"
)

var (
	top        string
	bottom     string
	brightness int
	serial     string
	blink      bool
	duration   int
	repeats    int
)

func init() {
	cmdNanoColor.PersistentFlags().StringVarP(&top, "top", "", "", "Color for top led: blink nano color red")
	cmdNanoColor.PersistentFlags().StringVarP(&bottom, "bottom", "", "", "Color for botton led")
	cmdNanoColor.PersistentFlags().IntVarP(&brightness, "brightness", "", 1, "Limit the brightness of the color 0..100")
	cmdNanoColor.PersistentFlags().StringVarP(&serial, "serial", "", "", "Select device by serial number. If unspecified, action will be performed on all BlinkSticks Strip")
	cmdNanoColor.PersistentFlags().BoolVarP(&blink, "blink", "", false, "Blink LED")
	cmdNanoColor.PersistentFlags().IntVarP(&duration, "duration", "", 100, "Set duration of transition in milliseconds (use with --blink)")
	cmdNanoColor.PersistentFlags().IntVarP(&repeats, "repeats", "", 10, "Number of repetitions (use with --blink)")
}

var cmdNanoColor = &cobra.Command{
	Use:   "color",
	Short: "Color a blinkstick nano: blink nano color [<color>] [--brightness=n] [--top=<color>] [--bottom=<color>] [--serial=s] [--duration=n] [--repeats=n] [--blink]",
	Long: `Color a blinkstick nano:

Set the same color for both led with 50% brightness :
  blink nano color orange --brightness 50

Set a color for bottom Led and another for top Led:
  blink nano color --bottom red --top green

Examples:
 blink nano color --top purple --brightness 1
 blink nano color --bottom red --brightness 100
 blink nano color green --brightness 12
 blink nano color --serial BS008173-3.0 --duration=500 --repeats=10 --brightness 30 --blink --bottom red

Turn off light:
  blink nano color black

	`,
	Run: func(cmd *cobra.Command, args []string) {

		if (len(args) == 0 || args[0] == "") && top == "" && bottom == "" {
			cmd.Help()
			return
		}
		gcolor := ""
		if len(args) > 0 {
			gcolor = args[0]
		}

		var colorColor, colorTop, colorBottom color.Color
		var err error

		if gcolor != "" {
			colorColor, err = blinkstick.GetColor(gcolor, brightness)
			internal.Check(err)
		}
		if top != "" {
			colorTop, err = blinkstick.GetColor(top, brightness)
			internal.Check(err)
		}
		if bottom != "" {
			colorBottom, err = blinkstick.GetColor(bottom, brightness)
			internal.Check(err)
		}

		b := blinkstick.Nano{}
		devices := b.List()
		for _, d := range devices {
			if serial == "" || d.GetDeviceInfo().SerialNumber == serial {
				if gcolor != "" {
					if blink {
						internal.Check(d.Blink(colorColor, duration, repeats))
					} else {
						internal.Check(d.SetColor(colorColor))
					}
				}
				if blink {
					if top != "" {
						internal.Check(blinkstick.SetBlinkOnLed(d, colorTop, 0, duration, repeats))
					}
					if bottom != "" {
						internal.Check(blinkstick.SetBlinkOnLed(d, colorBottom, 1, duration, repeats))
					}
				} else {
					if top != "" {
						internal.Check(d.(blinkstick.Nano).SetColorTop(colorTop))
					}
					if bottom != "" {
						internal.Check(d.(blinkstick.Nano).SetColorBottom(colorBottom))
					}
				}

			}
		}

	},
}


text:
require "xdrgen/version"
require "active_support/all"
require 'memoist'

module Xdrgen
  extend ActiveSupport::Autoload

  autoload :Compilation
  autoload :AST
  autoload :CLI
  autoload :Generators
  autoload :Parser
  autoload :Util

  autoload :Output
  autoload :OutputFile

  class ParseError < StandardError ; end

  class GenerateError < StandardError ; end
  class DuplicateFileError < GenerateError ; end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This XCCDF document was auto generated by the Recommendation Tracker. -->
<Benchmark xmlns="http://checklists.nist.gov/xccdf/1.1"
           xmlns:dc="http://purl.org/dc/elements/1.1/"
           xmlns:cdf="http://checklists.nist.gov/xccdf/1.1"
           xmlns:cpe="http://cpe.mitre.org/dictionary/2.0"
           xmlns:dsig="http://w3.org/2000/09/xmldsig#"
           xmlns:xhtml="http://www.w3.org/1999/xhtml"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://checklists.nist.gov/xccdf/1.1 http://nvd.nist.gov/schema/xccdf-1.1.4.xsd"
           id="Passwd">
<!-- Review the status value. -->
<status date="2010-06-11">draft</status>
   <title>PasswordFilePermissions</title>
   <!-- Consider adding front-matter. -->

<!-- Consider adding rear-matter. -->
<!-- Consider adding a reference for the benchamrk. -->
<!-- Consider adding application wide plafrom information. -->

<!-- Review version information. -->
<version>1.0</version>
   <!-- Consider adding scoring model information. -->
<Value id="Passwd-V-2-2" type="string" operator="equals">
      <title>PasswdOwner</title>
      <description/>
      <value>0</value>
   </Value>
   <Value id="Passwd-V-2-4" type="string" operator="equals">
      <title>PasswdGroup</title>
      <description/>
      <value>0</value>
   </Value>
   <Value id="Passwd-V-2-6" type="boolean" operator="equals">
      <title>PasswdOwnerExec</title>
      <description/>
      <value>0</value>
   </Value>
   <Value id="Passwd-V-2-8" type="boolean" operator="equals">
      <title>PasswdGroupWrite</title>
      <description/>
      <value>0</value>
   </Value>
   <Value id="Passwd-V-2-10" type="boolean" operator="equals">
      <title>PasswdGroupExec</title>
      <description/>
      <value>0</value>
   </Value>
   <Value id="Passwd-V-2-12" type="boolean" operator="equals">
      <title>PasswdOtherWrite</title>
      <description/>
      <value>0</value>
   </Value>
   <Value id="Passwd-V-2-14" type="boolean" operator="equals">
      <title>PasswdOtherExec</title>
      <description/>
      <value>0</value>
   </Value>
      <Rule id="Passwd-R-2-1">
      <title>Passwd_Ownership</title>
      <description>/etc/passwd should be owned by root</description>
      <rationale>Who Cares</rationale>
      <fixtext>Change the owner to root</fixtext>
      <check system="http://oval.mitre.org/XMLSchema/oval-definitions-5">
         <check-export value-id="Passwd-V-2-2" export-name="oval:com.tresys.oval.passwd:var:1004"/>
         <check-content-ref href="2-15Passwd.xml" name="oval:com.tresys.com.passwd:def:1000"/>
      </check>
   </Rule>
   <Rule id="Passwd-R-2-2">
      <title>Passwd_Group_Ownership</title>
      <description>/etc/passwd should be owned by root</description>
      <rationale>Who Cares</rationale>
      <fixtext>Change the owner to root</fixtext>
      <check system="http://oval.mitre.org/XMLSchema/oval-definitions-5">
         <check-export value-id="Passwd-V-2-4" export-name="oval:com.tresys.oval.passwd:var:1005"/>
         <check-content-ref href="2-15Passwd.xml" name="oval:com.tresys.com.passwd:def:1001"/>
      </check>
   </Rule>
   <Rule id="Passwd-R-2-3">
      <title>Passwd_Mode</title>
      <description>/etc/passwd should be 644 or less</description>
      <rationale>Who Cares</rationale>
      <fixtext>Change the mode to 644</fixtext>
      <check system="http://oval.mitre.org/XMLSchema/oval-definitions-5">
         <check-export value-id="Passwd-V-2-6" export-name="oval:com.tresys.oval.passwd:var:1006"/>
         <check-export value-id="Passwd-V-2-8" export-name="oval:com.tresys.oval.passwd:var:1007"/>
         <check-export value-id="Passwd-V-2-10" export-name="oval:com.tresys.oval.passwd:var:1008"/>
         <check-export value-id="Passwd-V-2-12" export-name="oval:com.tresys.oval.passwd:var:1009"/>
         <check-export value-id="Passwd-V-2-14" export-name="oval:com.tresys.oval.passwd:var:1010"/>
         <check-content-ref href="2-15Passwd.xml" name="oval:com.tresys.com.passwd:def:1002"/>
      </check>
   </Rule>
</Benchmark>


text:
<?php

namespace Doctrine\DBAL\Schema;

use Doctrine\DBAL\Schema\Visitor\CreateSchemaSqlCollector;
use Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector;
use Doctrine\DBAL\Schema\Visitor\Visitor;

/**
 * Object representation of a database schema
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 */
class Schema extends AbstractAsset
{
    /**
     * @var array
     */
    protected $_tables = array();

    /**
     * @var array
     */
    protected $_sequences = array();

    /**
     * @var SchemaConfig
     */
    protected $_schemaConfig = false;

    /**
     * @param array $tables
     * @param array $sequences
     * @param array $views
     * @param array $triggers
     * @param SchemaConfig $schemaConfig
     */
    public function __construct(array $tables=array(), array $sequences=array(), SchemaConfig $schemaConfig=null)
    {
        if ($schemaConfig == null) {
            $schemaConfig = new SchemaConfig();
        }
        $this->_schemaConfig = $schemaConfig;

        foreach ($tables AS $table) {
            $this->_addTable($table);
        }
        foreach ($sequences AS $sequence) {
            $this->_addSequence($sequence);
        }
    }

    /**
     * @return bool
     */
    public function hasExplicitForeignKeyIndexes()
    {
        return $this->_schemaConfig->hasExplicitForeignKeyIndexes();
    }

    /**
     * @param Table $table
     */
    protected function _addTable(Table $table)
    {
        $tableName = strtolower($table->getName());
        if(isset($this->_tables[$tableName])) {
            throw SchemaException::tableAlreadyExists($tableName);
        }

        $this->_tables[$tableName] = $table;
        $table->setSchemaConfig($this->_schemaConfig);
    }

    /**
     * @param Sequence $sequence
     */
    protected function _addSequence(Sequence $sequence)
    {
        $seqName = strtolower($sequence->getName());
        if (isset($this->_sequences[$seqName])) {
            throw SchemaException::sequenceAlreadyExists($seqName);
        }
        $this->_sequences[$seqName] = $sequence;
    }

    /**
     * Get all tables of this schema.
     *
     * @return array
     */
    public function getTables()
    {
        return $this->_tables;
    }

    /**
     * @param string $tableName
     * @return Table
     */
    public function getTable($tableName)
    {
        $tableName = strtolower($tableName);
        if (!isset($this->_tables[$tableName])) {
            throw SchemaException::tableDoesNotExist($tableName);
        }

        return $this->_tables[$tableName];
    }

    /**
     * Does this schema have a table with the given name?
     *
     * @param  string $tableName
     * @return Schema
     */
    public function hasTable($tableName)
    {
        $tableName = strtolower($tableName);
        return isset($this->_tables[$tableName]);
    }

    /**
     * @param  string $sequenceName
     * @return bool
     */
    public function hasSequence($sequenceName)
    {
        $sequenceName = strtolower($sequenceName);
        return isset($this->_sequences[$sequenceName]);
    }

    /**
     * @throws SchemaException
     * @param  string $sequenceName
     * @return Doctrine\DBAL\Schema\Sequence
     */
    public function getSequence($sequenceName)
    {
        $sequenceName = strtolower($sequenceName);
        if(!$this->hasSequence($sequenceName)) {
            throw SchemaException::sequenceDoesNotExist($sequenceName);
        }
        return $this->_sequences[$sequenceName];
    }

    /**
     * @return Doctrine\DBAL\Schema\Sequence[]
     */
    public function getSequences()
    {
        return $this->_sequences;
    }

    /**
     * Create a new table
     *
     * @param  string $tableName
     * @return Table
     */
    public function createTable($tableName)
    {
        $table = new Table($tableName,array(),array(),array(),0,array('charset'=>'utf8','collate'=>'utf8_general_ci'));
        $this->_addTable($table);
        return $table;
    }

    /**
     * Rename a table
     *
     * @param string $oldTableName
     * @param string $newTableName
     * @return Schema
     */
    public function renameTable($oldTableName, $newTableName)
    {
        $table = $this->getTable($oldTableName);
        $table->_setName($newTableName);

        $this->dropTable($oldTableName);
        $this->_addTable($table);
        return $this;
    }

    /**
     * Drop a table from the schema.
     *
     * @param string $tableName
     * @return Schema
     */
    public function dropTable($tableName)
    {
        $tableName = strtolower($tableName);
        $table = $this->getTable($tableName);
        unset($this->_tables[$tableName]);
        return $this;
    }

    /**
     * Create a new sequence
     *
     * @param  string $sequenceName
     * @param  int $allocationSize
     * @param  int $initialValue
     * @return Sequence
     */
    public function createSequence($sequenceName, $allocationSize=1, $initialValue=1)
    {
        $seq = new Sequence($sequenceName, $allocationSize, $initialValue);
        $this->_addSequence($seq);
        return $seq;
    }

    /**
     * @param string $sequenceName
     * @return Schema
     */
    public function dropSequence($sequenceName)
    {
        $sequenceName = strtolower($sequenceName);
        unset($this->_sequences[$sequenceName]);
        return $this;
    }

    /**
     * Return an array of necessary sql queries to create the schema on the given platform.
     *
     * @param AbstractPlatform $platform
     * @return array
     */
    public function toSql(\Doctrine\DBAL\Platforms\AbstractPlatform $platform)
    {
        $sqlCollector = new CreateSchemaSqlCollector($platform);
        $this->visit($sqlCollector);

        return $sqlCollector->getQueries();
    }

    /**
     * Return an array of necessary sql queries to drop the schema on the given platform.
     *
     * @param AbstractPlatform $platform
     * @return array
     */
    public function toDropSql(\Doctrine\DBAL\Platforms\AbstractPlatform $platform)
    {
        $dropSqlCollector = new DropSchemaSqlCollector($platform);
        $this->visit($dropSqlCollector);

        return $dropSqlCollector->getQueries();
    }

    /**
     * @param Schema $toSchema
     * @param AbstractPlatform $platform
     */
    public function getMigrateToSql(Schema $toSchema, \Doctrine\DBAL\Platforms\AbstractPlatform $platform)
    {
        $comparator = new Comparator();
        $schemaDiff = $comparator->compare($this, $toSchema);
        return $schemaDiff->toSql($platform);
    }

    /**
     * @param Schema $fromSchema
     * @param AbstractPlatform $platform
     */
    public function getMigrateFromSql(Schema $fromSchema, \Doctrine\DBAL\Platforms\AbstractPlatform $platform)
    {
        $comparator = new Comparator();
        $schemaDiff = $comparator->compare($fromSchema, $this);
        return $schemaDiff->toSql($platform);
    }

    /**
     * @param Visitor $visitor
     */
    public function visit(Visitor $visitor)
    {
        $visitor->acceptSchema($this);

        foreach ($this->_tables AS $table) {
            $table->visit($visitor);
        }
        foreach ($this->_sequences AS $sequence) {
            $sequence->visit($visitor);
        }
    }

    /**
     * Cloning a Schema triggers a deep clone of all related assets.
     *
     * @return void
     */
    public function __clone()
    {
        foreach ($this->_tables AS $k => $table) {
            $this->_tables[$k] = clone $table;
        }
        foreach ($this->_sequences AS $k => $sequence) {
            $this->_sequences[$k] = clone $sequence;
        }
    }
}


text:
<?php

namespace Ticket\Model;

 use Zend\Db\TableGateway\TableGateway;

 class TicketTable
 {
     protected $tableGateway;

     public function __construct(TableGateway $tableGateway)
     {
         $this->tableGateway = $tableGateway;
     }

     public function fetchAll()
     {
         $resultSet = $this->tableGateway->select();
         return $resultSet;
     }

     public function getTicket($id)
     {
         $id  = (int) $id;
         $rowset = $this->tableGateway->select(array('id' => $id));
         $row = $rowset->current();
         if (!$row) {
             throw new \Exception("Could not find row $id");
         }
         return $row;
     }

     public function saveTicket(Ticket $ticket)
     {
         $data = array(
             'user_id' => $ticket->userId,
             'title'  => $ticket->title,
         );

         $id = (int) $ticket->id;
         if ($id == 0) {
             $this->tableGateway->insert($data);
         } else {
             if ($this->getTicket($id)) {
                 $this->tableGateway->update($data, array('id' => $id));
             } else {
                 throw new \Exception('Album id does not exist');
             }
         }
     }

     public function deleteTicket($id)
     {
         $this->tableGateway->delete(array('id' => (int) $id));
     }
 }


text:
/*
Theme Name: Nimbus Custom
Description: Your Custom made theme by nimbus media
Author: Nimbus Media
Author URI: http://nimbus.digital
License: GNU General Public License v2.0
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
/* No Styles here, because it's 2015 we have SASS and we're gonna use it. */


text:
#ifndef __SORTTAB_H__
#define __SORTTAB_H__

#include "dbmain.h"

#include "..\inc\zsorttab.h"

#ifndef ACRX_DECLARE_MEMBERS
#define ACRX_DECLARE_MEMBERS		ZCRX_DECLARE_MEMBERS
#endif //#ifndef ACRX_DECLARE_MEMBERS

#ifndef AcDbAuditInfo
#define AcDbAuditInfo		ZcDbAuditInfo
#endif //#ifndef AcDbAuditInfo

#ifndef AcDbDwgFiler
#define AcDbDwgFiler		ZcDbDwgFiler
#endif //#ifndef AcDbDwgFiler

#ifndef AcDbDxfFiler
#define AcDbDxfFiler		ZcDbDxfFiler
#endif //#ifndef AcDbDxfFiler

#ifndef AcDbHandle
#define AcDbHandle		ZcDbHandle
#endif //#ifndef AcDbHandle

#ifndef AcDbImpSortentsTable
#define AcDbImpSortentsTable		ZcDbImpSortentsTable
#endif //#ifndef AcDbImpSortentsTable

#ifndef AcDbObject
#define AcDbObject		ZcDbObject
#endif //#ifndef AcDbObject

#ifndef AcDbObjectId
#define AcDbObjectId		ZcDbObjectId
#endif //#ifndef AcDbObjectId

#ifndef AcDbObjectIdArray
#define AcDbObjectIdArray		ZcDbObjectIdArray
#endif //#ifndef AcDbObjectIdArray

#ifndef AcDbSortentsTable
#define AcDbSortentsTable		ZcDbSortentsTable
#endif //#ifndef AcDbSortentsTable

#ifndef AcDbSystemInternals
#define AcDbSystemInternals		ZcDbSystemInternals
#endif //#ifndef AcDbSystemInternals

#ifndef AcRxClass
#define AcRxClass		ZcRxClass
#endif //#ifndef AcRxClass

#ifndef Acad
#define Acad		Zcad
#endif //#ifndef Acad

#ifndef Adesk
#define Adesk		ZSoft
#endif //#ifndef Adesk

#endif //#ifndef __SORTTAB_H__


text:
ACCEPTED

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

#### Published in
Verh. K. Akad. Vet. Amsterdam 51(3): 103 (1957)

#### Original name
Gloeosporium meinersii R. Sprague, 1949

### Remarks
null


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/types.h>

#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "string_m.h"

/*
 * Counts the number of occurrences of one string that appear in the source
 * string. Return value is the total count.
 *
 * An example use would be if you need to know how large a block of memory
 * needs to be for a replaceall() series.
 */
unsigned int
strcount(const char *source, const char *find)
{
	const char *p = source;
	size_t flen;
	unsigned int n = 0;

	/* Both parameters are required */
	if (source == NULL || find == NULL)
		return (0);

	/* Cache the length of find element */
	flen = strlen(find);
	if (strlen(source) == 0 || flen == 0)
		return (0);

	/* Loop until the end of the string */
	while (*p != '\0') {
		if (strncmp(p, find, flen) == 0) { /* found an instance */
			p += flen;
			n++;
		} else
			p++;
	}

	return (n);
}

/*
 * Replaces all occurrences of `find' in `source' with `replace'.
 *
 * You should not pass a string constant as the first parameter, it needs to be
 * a pointer to an allocated block of memory. The block of memory that source
 * points to should be large enough to hold the result. If the length of the
 * replacement string is greater than the length of the find string, the result
 * will be larger than the original source string. To allocate enough space for
 * the result, use the function strcount() declared above to determine the
 * number of occurrences and how much larger the block size needs to be.
 *
 * If source is not large enough, the application will crash. The return value
 * is the length (in bytes) of the result.
 *
 * When an error occurs, -1 is returned and the global variable errno is set
 * accordingly. Returns zero on success.
 */
int
replaceall(char *source, const char *find, const char *replace)
{
	char *p;
	char *t;
	char *temp;
	size_t flen;
	size_t rlen;
	size_t slen;
	uint32_t n = 0;

	errno = 0; /* reset global error number */

	/* Check that we have non-null parameters */
	if (source == NULL)
		return (0);
	if (find == NULL)
		return (strlen(source));

	/* Cache the length of the strings */
	slen = strlen(source);
	flen = strlen(find);
	rlen = replace ? strlen(replace) : 0;

	/* Cases where no replacements need to be made */
	if (slen == 0 || flen == 0 || slen < flen)
		return (slen);

	/* If replace is longer than find, we'll need to create a temp copy */
	if (rlen > flen) {
		temp = malloc(slen + 1);
		if (errno != 0) /* could not allocate memory */
			return (-1);
		strcpy(temp, source);
	} else
		temp = source;

	/* Reconstruct the string with the replacements */
	p = source; t = temp; /* position elements */

	while (*t != '\0') {
		if (strncmp(t, find, flen) == 0) {
			/* found an occurrence */
			for (n = 0; replace && replace[n]; n++)
				*p++ = replace[n];
			t += flen;
		} else
			*p++ = *t++; /* copy character and increment */
	}

	/* Terminate the string */
	*p = '\0';

	/* Free the temporary allocated memory */
	if (temp != source)
		free(temp);

	/* Return the length of the completed string */
	return (strlen(source));
}

/*
 * Expands escape sequences in a buffer pointed to by `source'. This function
 * steps through each character, and converts escape sequences such as "\n",
 * "\r", "\t" and others into their respective meanings.
 *
 * You should not pass a string constant or literal to this function or the
 * program will likely segmentation fault when it tries to modify the data.
 *
 * The string length will either shorten or stay the same depending on whether
 * any escape sequences were converted but the amount of memory allocated does
 * not change.
 *
 * Interpreted sequences are:
 *
 * 	\0NNN	character with octal value NNN (0 to 3 digits)
 * 	\N	character with octal value N (0 thru 7)
 * 	\a	alert (BEL)
 * 	\b	backslash
 * 	\f	form feed
 * 	\n	new line
 * 	\r	carriage return
 * 	\t	horizontal tab
 * 	\v	vertical tab
 * 	\xNN	byte with hexadecimal value NN (1 to 2 digits)
 *
 * All other sequences are unescaped (ie. '\"' and '\#').
 */
void strexpand(char *source)
{
	uint8_t c;
	char *chr;
	char *pos;
	char d[4];

	/* Initialize position elements */
	pos = chr = source;

	/* Loop until we hit the end of the string */
	while (*pos != '\0') {
		if (*chr != '\\') {
			*pos = *chr; /* copy character to current offset */
			pos++;
			chr++;
			continue;
		}

		/* Replace the backslash with the correct character */
		switch (*++chr) {
		case 'a': *pos = '\a'; break; /* bell/alert (BEL) */
		case 'b': *pos = '\b'; break; /* backspace */
		case 'f': *pos = '\f'; break; /* form feed */
		case 'n': *pos = '\n'; break; /* new line */
		case 'r': *pos = '\r'; break; /* carriage return */
		case 't': *pos = '\t'; break; /* horizontal tab */
		case 'v': *pos = '\v'; break; /* vertical tab */
		case 'x': /* hex value (1 to 2 digits)(\xNN) */
			d[2] = '\0'; /* pre-terminate the string */

			/* verify next two characters are hex */
			d[0] = isxdigit(*(chr+1)) ? *++chr : '\0';
			if (d[0] != '\0')
				d[1] = isxdigit(*(chr+1)) ? *++chr : '\0';

			/* convert the characters to decimal */
			c = (uint8_t)strtoul(d, 0, 16);

			/* assign the converted value */
			*pos = (c != 0 || d[0] == '0') ? c : *++chr;
			break;
		case '0': /* octal value (0 to 3 digits)(\0NNN) */
			d[3] = '\0'; /* pre-terminate the string */

			/* verify next three characters are octal */
			d[0] = (isdigit(*(chr+1)) && *(chr+1) < '8') ?
			    *++chr : '\0';
			if (d[0] != '\0')
				d[1] = (isdigit(*(chr+1)) && *(chr+1) < '8') ?
				    *++chr : '\0';
			if (d[1] != '\0')
				d[2] = (isdigit(*(chr+1)) && *(chr+1) < '8') ?
				    *++chr : '\0';

			/* convert the characters to decimal */
			c = (uint8_t)strtoul(d, 0, 8);

			/* assign the converted value */
			*pos = c;
			break;
		default: /* single octal (\0..7) or unknown sequence */
			if (isdigit(*chr) && *chr < '8') {
				d[0] = *chr;
				d[1] = '\0';
				*pos = (uint8_t)strtoul(d, 0, 8);
			} else
				*pos = *chr;
		}

		/* Increment to next offset, possible next escape sequence */
		pos++;
		chr++;
	}
}

/*
 * Expand only the escaped newlines in a buffer pointed to by `source'. This
 * function steps through each character, and converts the "\n" sequence into
 * a literal newline and the "\\n" sequence into "\n".
 *
 * You should not pass a string constant or literal to this function or the
 * program will likely segmentation fault when it tries to modify the data.
 *
 * The string length will either shorten or stay the same depending on whether
 * any escaped newlines were converted but the amount of memory allocated does
 * not change.
 */
void strexpandnl(char *source)
{
	uint8_t backslash = 0;
	char *cp1;
	char *cp2;

	/* Replace '\n' with literal in dprompt */
	cp1 = cp2 = source;
	while (*cp2 != '\0') {
		*cp1 = *cp2;
		if (*cp2 == '\\')
			backslash++;
		else if (*cp2 != 'n')
			backslash = 0;
		else if (backslash > 0) {
			*(--cp1) = (backslash & 1) == 1 ? '\n' : 'n';
			backslash = 0;
		}
		cp1++;
		cp2++;
	}
	*cp1 = *cp2;
}

/*
 * Convert a string to lower case. You should not pass a string constant to
 * this function. Only pass pointers to allocated memory with null terminated
 * string data.
 */
void
strtolower(char *source)
{
	char *p = source;

	if (source == NULL)
		return;

	while (*p != '\0') {
		*p = tolower(*p);
		p++; /* would have just used `*p++' but gcc 3.x warns */
	}
}


text:
package Action::passageMediaDelete;

use UrlConstants;
use PassageMedia;

sub run {

  our $q = shift;
  our $dbh = shift;

  our %in = map { $_ => $q->param($_) } $q->param;

  local $passage_media = from_db PassageMedia($in{pm_id});

  my $psgi_out = '';

  if ( defined $in{action} && $in{action} eq 'delete' ) {
    # TODO consider removing tag from html file in case user does not select save
    eval { $passage_media->delete(); };

    if ($@) {
      $psgi_out = &print_delete_error($@);
    } else {
      $psgi_out = &print_delete();
    }
  } else {
    $psgi_out = &print_preview();
  }

  return [ $q->psgi_header(
             -type          => 'text/html',
             -pragma        => 'nocache',
             -cache_control => 'no-cache, must-revalidate'),
           [ $psgi_out ]];
}
### ALL DONE! ###

sub print_preview {

  return <<END_HERE;
<!DOCTYPE html>

  <meta charset=utf-8 />
    <title>Delete Media</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <link href="${orcaUrl}style/text.css" rel="stylesheet" type="text/css">

    <form name="actionForm" action="${orcaUrl}cgi-bin/passageMediaDelete.pl" method="POST">
      <input type="hidden" name="pm_id" value="$in{pm_id}" />
      <input type="hidden" name="action" value="delete" />
    </form>

Delete Media

          Confirm deletion of media file:

          Filename: @{[$passage_media->get_client_filename()]}

          Description: @{[$passage_media->get_description()]}

          Warning: This action is immediate and cannot be undone.

    <input type="button" value="Delete" onClick="document.actionForm.submit(); return true;" />
    <input type="button" value="Cancel" onClick="window.close(); return true;" />

END_HERE

}

sub print_delete() {
  use PassageMediaTable;
  my $passage_media_table = new PassageMediaTable();

  return <<END_HERE;
<!DOCTYPE html>

  <meta charset=utf-8 />
    <title>SBAC CDE Delete Media</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <link href="${orcaUrl}style/text.css" rel="stylesheet" type="text/css">

Media Deleted

          Filename: @{[$passage_media->get_client_filename()]}

          Description: @{[$passage_media->get_description()]}

    <input type="button" value="Close" onClick="window.close(); return true;" />

END_HERE

}

sub print_delete_error() {
  my $message = shift;

  return <<END_HERE;
<!DOCTYPE html>

  <meta charset=utf-8 />
    <title>SBAC CDE Delete Media</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <link href="${orcaUrl}style/text.css" rel="stylesheet" type="text/c

Delete Media

          $message

          Filename: @{[$passage_media->get_client_filename()]}

          Description: @{[$passage_media->get_description()]}

    <input type="button" value="Close" onClick="window.close(); return true;" />

END_HERE
}
1;


text:
package thrift

import (
	"crypto/tls"
	"net"
	"time"
)

type TSSLSocket struct {
	conn    net.Conn
	addr    net.Addr
	timeout time.Duration
	cfg     *tls.Config
}

// NewTSSLSocket creates a net.Conn-backed TTransport, given a host and port and tls Configuration
//
// Example:
// 	trans, err := thrift.NewTSocket("localhost:9090")
func NewTSSLSocket(hostPort string, cfg *tls.Config) (*TSSLSocket, error) {
	return NewTSSLSocketTimeout(hostPort, cfg, 0)
}

// NewTSSLSocketTimeout creates a net.Conn-backed TTransport, given a host and port
// it also accepts a tls Configuration and a timeout as a time.Duration
func NewTSSLSocketTimeout(hostPort string, cfg *tls.Config, timeout time.Duration) (*TSSLSocket, error) {
	//conn, err := net.DialTimeout(network, address, timeout)
	addr, err := net.ResolveTCPAddr("tcp", hostPort)
	if err != nil {
		return nil, err
	}
	return NewTSSLSocketFromAddrTimeout(addr, cfg, timeout), nil
}

// Creates a TSSLSocket from a net.Addr
func NewTSSLSocketFromAddrTimeout(addr net.Addr, cfg *tls.Config, timeout time.Duration) *TSSLSocket {
	return &TSSLSocket{addr: addr, timeout: timeout, cfg: cfg}
}

// Creates a TSSLSocket from an existing net.Conn
func NewTSSLSocketFromConnTimeout(conn net.Conn, cfg *tls.Config, timeout time.Duration) *TSSLSocket {
	return &TSSLSocket{conn: conn, addr: conn.RemoteAddr(), timeout: timeout, cfg: cfg}
}

// Sets the socket timeout
func (p *TSSLSocket) SetTimeout(timeout time.Duration) error {
	p.timeout = timeout
	return nil
}

func (p *TSSLSocket) pushDeadline(read, write bool) {
	var t time.Time
	if p.timeout > 0 {
		t = time.Now().Add(time.Duration(p.timeout))
	}
	if read && write {
		p.conn.SetDeadline(t)
	} else if read {
		p.conn.SetReadDeadline(t)
	} else if write {
		p.conn.SetWriteDeadline(t)
	}
}

// Connects the socket, creating a new socket object if necessary.
func (p *TSSLSocket) Open() error {
	if p.IsOpen() {
		return NewTTransportException(ALREADY_OPEN, "Socket already connected.")
	}
	if p.addr == nil {
		return NewTTransportException(NOT_OPEN, "Cannot open nil address.")
	}
	if len(p.addr.Network()) == 0 {
		return NewTTransportException(NOT_OPEN, "Cannot open bad network name.")
	}
	if len(p.addr.String()) == 0 {
		return NewTTransportException(NOT_OPEN, "Cannot open bad address.")
	}
	var err error
	if p.conn, err = tls.Dial(p.addr.Network(), p.addr.String(), p.cfg); err != nil {
		return NewTTransportException(NOT_OPEN, err.Error())
	}
	return nil
}

// Retreive the underlying net.Conn
func (p *TSSLSocket) Conn() net.Conn {
	return p.conn
}

// Returns true if the connection is open
func (p *TSSLSocket) IsOpen() bool {
	if p.conn == nil {
		return false
	}
	return true
}

// Closes the socket.
func (p *TSSLSocket) Close() error {
	// Close the socket
	if p.conn != nil {
		err := p.conn.Close()
		if err != nil {
			return err
		}
		p.conn = nil
	}
	return nil
}

func (p *TSSLSocket) Read(buf []byte) (int, error) {
	if !p.IsOpen() {
		return 0, NewTTransportException(NOT_OPEN, "Connection not open")
	}
	p.pushDeadline(true, false)
	n, err := p.conn.Read(buf)
	return n, NewTTransportExceptionFromError(err)
}

func (p *TSSLSocket) Write(buf []byte) (int, error) {
	if !p.IsOpen() {
		return 0, NewTTransportException(NOT_OPEN, "Connection not open")
	}
	p.pushDeadline(false, true)
	return p.conn.Write(buf)
}

func (p *TSSLSocket) Peek() bool {
	return p.IsOpen()
}

func (p *TSSLSocket) Flush() error {
	return nil
}

func (p *TSSLSocket) Interrupt() error {
	if !p.IsOpen() {
		return nil
	}
	return p.conn.Close()
}


text:
<?php require_once("includes/functions.php"); ?>
<?php
		// Four steps to closing a session
		// (i.e. logging out)

		// 1. Find the session
		session_start();

		// 2. Unset all the session variables
		$_SESSION = array();

		// 3. Destroy the session cookie
		if(isset($_COOKIE[session_name()])) {
			setcookie(session_name(), '', time()-42000, '/');
		}

		// 4. Destroy the session
		session_destroy();

		redirect_to("index.php?logout=1");
?>


text:
module Api

  module V1

    class PaginationPresenter

      def initialize(current_url:, per_page:, total_items:, current_page: 1)
        @url = current_url
        @per_page = per_page
        @total_items = total_items
        @page = current_page
      end

      def url_without_pagination
        return nil unless @url.present? && @url.is_a?(String)

        url = @url.gsub(/per_page=\d+/, "")
                  .gsub(/page=\d+/, "")
                  .gsub(/(&)+$/, "").gsub(/\?$/, "")

        (url.include?("?") ? "#{url}&" : "#{url}?")
      end

      def prev_page?
        total_pages > 1 && @page != 1
      end

      def next_page?
        total_pages > 1 && @page < total_pages
      end

      def prev_page_link
        "#{url_without_pagination}page=#{@page - 1}&per_page=#{@per_page}"
      end

      def next_page_link
        "#{url_without_pagination}page=#{@page + 1}&per_page=#{@per_page}"
      end

      private

      def total_pages
        return 1 unless @total_items.present? && @per_page.present? &&
                        @total_items.positive? && @per_page.positive?

        (@total_items.to_f / @per_page).ceil
      end

    end

  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>fishingmate</artifactId>
        <groupId>com.5151pic.fishing</groupId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>fishingmate-infrastructure</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.jtds</groupId>
            <artifactId>jtds</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.sgroschupf</groupId>
            <artifactId>zkclient</artifactId>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson2-provider</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>el-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
        </dependency>
        <dependency>
            <groupId>com.ymatou</groupId>
            <artifactId>performancemonitorclient</artifactId>
        </dependency>
        <dependency>
            <groupId>com.ymatou.errorreporter</groupId>
            <artifactId>errorreporter-logback</artifactId>
        </dependency>
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
        </dependency>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpasyncclient</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>**/logback.xml</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
/**
 * NotFoundPage
 *
 * This is the page we show when the user visits a url that doesn't have a route
 *
 * NOTE: while this component should technically be a stateless functional
 * component (SFC), hot reloading does not currently support SFCs. If hot
 * reloading is not a necessity for you then you can refactor it and remove
 * the linting exception.
 */

import React from 'react';
import { FormattedMessage } from 'react-intl';

import Typography from 'material-ui/Typography';

import messages from './messages';

export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
  render() {
    const rootStyle = {
      opacity: 0.6,
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      height: '100%',
      alignItems: 'center',
    };

    return (
      <div style={rootStyle}>
        <Typography type="headline" ><FormattedMessage {...messages.header} /></Typography>
        <Typography type="headline" style={{ fontSize: 90, lineHeight: '100px', fontWeight: 200 }}>404</Typography>
      </div>
    );
  }
}


text:
package com.yermoon.dao;

import java.sql.ResultSet;

//自定义接口
public interface ResultSetHandler<T> {
    public T callback(ResultSet rs);
}


text:
=begin

Copyright 2012-2013 inBloom, Inc. and its affiliates.

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

# Be sure to restart your server when you modify this file.

# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
#   inflect.plural /^(ox)$/i, '\1en'
#   inflect.singular /^(ox)en/i, '\1'
#   inflect.irregular 'person', 'people'
#   inflect.uncountable %w( fish sheep )
# end


text:
shell-test command, rel ne
--SKIPIF--
<?php
if (!getenv('PHP_PEAR_RUNTESTS')) {
    echo 'skip';
}
?>
--FILE--
<?php
require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'setup.php.inc';
$reg = $config->getRegistry();
$pkg = &new PEAR_PackageFile($config);
$info = $pkg->fromPackageFile(dirname(__FILE__) . DIRECTORY_SEPARATOR .
    DIRECTORY_SEPARATOR . 'packagefiles' . DIRECTORY_SEPARATOR . 'package2.xml',
    PEAR_VALIDATE_NORMAL);
$reg->addPackage2($info);
$e = $command->run('shell-test', array(), array('PEAR', 'ne', '1.3.9'));
$phpunit->assertNoErrors('ok 1');
$e = $command->run('shell-test', array(), array('PEAR', 'ne', '1.4.0a2'));
$phpunit->assertNoErrors('ok 2');
echo 'tests done';
?>
--CLEAN--
<?php
require_once dirname(dirname(__FILE__)) . '/teardown.php.inc';
?>
--RETURNS--
0
--EXPECT--
tests done


text:
#include <stdlib.h>
#include <ipmi.h>
#include <lock.h>
#include <opal.h>
#include <device.h>
#include <timer.h>
#include <timebase.h>
#include <pool.h>
#include <skiboot.h>

#define TIMER_USE_DONT_LOG	0x80
#define TIMER_USE_DONT_STOP	0x40
#define TIMER_USE_POST		0x02

/* WDT expiration actions */
#define WDT_PRETIMEOUT_SMI	0x10
#define WDT_RESET_ACTION 	0x01
#define WDT_NO_ACTION		0x00

/* IPMI defined custom completion codes for the watchdog */
#define WDT_CC_OK		0x00
#define WDT_CC_NOT_INITIALIZED	0x80

/* Flags used for IPMI callbacks */
#define WDT_SET_DO_RESET	0x01
#define WDT_RESET_NO_REINIT	0x01

/* How long to set the overall watchdog timeout for. In units of
 * 100ms. If the timer is not reset within this time the watchdog
 * expiration action will occur. */
#define WDT_TIMEOUT		600

/* How often to reset the timer using schedule_timer(). Too short and
we risk accidentally resetting the system due to opal_run_pollers() not
being called in time, too short and we waste time resetting the wdt
more frequently than necessary. */
#define WDT_MARGIN		300

static struct timer wdt_timer;
static bool wdt_stopped;
static bool wdt_ticking;

/* Saved values from the last watchdog set action */
static uint8_t last_action;
static uint16_t last_count;
static uint8_t last_pretimeout;

static void reset_wdt(struct timer *t, void *data, uint64_t now);

static void set_wdt_complete(struct ipmi_msg *msg)
{
	const uintptr_t flags = (uintptr_t)msg->user_data;

	if (flags & WDT_SET_DO_RESET) {
		/* Make sure the reset action does not create a loop and
		 * perform a reset in the case where the BMC send an
		 * uninitialized error. */
		reset_wdt(NULL, (void *)WDT_RESET_NO_REINIT, 0);
	}

	ipmi_free_msg(msg);
}

static void set_wdt(uint8_t action, uint16_t count, uint8_t pretimeout,
		bool dont_stop, bool do_reset)
{
	struct ipmi_msg *ipmi_msg;
	uintptr_t completion_flags = 0;

	if (do_reset)
		completion_flags |= WDT_SET_DO_RESET;

	/* Save the values prior to issuing the set operation so that we can
	 * re-initialize the watchdog in error cases. */
	last_action = action;
	last_count = count;
	last_pretimeout = pretimeout;

	ipmi_msg = ipmi_mkmsg(IPMI_DEFAULT_INTERFACE, IPMI_SET_WDT,
			      set_wdt_complete, NULL, NULL, 6, 0);
	if (!ipmi_msg) {
		prerror("Unable to allocate set wdt message\n");
		return;
	}
	ipmi_msg->error = set_wdt_complete;
	ipmi_msg->user_data = (void *)completion_flags;
	ipmi_msg->data[0] = TIMER_USE_POST |
		TIMER_USE_DONT_LOG |
		(dont_stop ? TIMER_USE_DONT_STOP : 0);
	ipmi_msg->data[1] = action;			/* Timer Actions */
	ipmi_msg->data[2] = pretimeout;			/* Pre-timeout Interval */
	ipmi_msg->data[3] = 0;				/* Timer Use Flags */
	ipmi_msg->data[4] = count & 0xff;		/* Initial countdown (lsb) */
	ipmi_msg->data[5] = (count >> 8) & 0xff;	/* Initial countdown (msb) */
	ipmi_queue_msg(ipmi_msg);
}

static void reset_wdt_complete(struct ipmi_msg *msg)
{
	const uintptr_t flags = (uintptr_t)msg->user_data;
	uint64_t reset_delay_ms = (WDT_TIMEOUT - WDT_MARGIN) * 100;

	if (msg->cc == WDT_CC_NOT_INITIALIZED &&
			!(flags & WDT_RESET_NO_REINIT)) {
		/* If our timer was not initialized on the BMC side, we should
		 * perform a single attempt to set it up again. */
		set_wdt(last_action, last_count, last_pretimeout, true, true);
	} else if (msg->cc != WDT_CC_OK) {
		/* Use a short (10s) timeout before performing the next reset
		 * if we encounter an unknown error. This makes sure that we
		 * are able to reset and re-initialize the timer since it might
		 * expire. */
		reset_delay_ms = 10 * 1000;
	}

	/* If we are inside of skiboot we need to periodically restart the
	 * timer. Reschedule a reset so it happens before the timeout. */
	if (wdt_ticking)
		schedule_timer(&wdt_timer, msecs_to_tb(reset_delay_ms));

	ipmi_free_msg(msg);
}

static struct ipmi_msg *wdt_reset_mkmsg(void)
{
	struct ipmi_msg *ipmi_msg;

	ipmi_msg = ipmi_mkmsg(IPMI_DEFAULT_INTERFACE, IPMI_RESET_WDT,
			      reset_wdt_complete, NULL, NULL, 0, 0);
	if (!ipmi_msg) {
		prerror("Unable to allocate reset wdt message\n");
		return NULL;
	}
	ipmi_msg->error = reset_wdt_complete;

	return ipmi_msg;
}

static void sync_reset_wdt(void)
{
	struct ipmi_msg *ipmi_msg;

	if ((ipmi_msg = wdt_reset_mkmsg()))
		ipmi_queue_msg_sync(ipmi_msg);
}

static void reset_wdt(struct timer *t __unused, void *data,
		      uint64_t now __unused)
{
	struct ipmi_msg *ipmi_msg;

	if ((ipmi_msg = wdt_reset_mkmsg())) {
		ipmi_msg->user_data = data;
		ipmi_queue_msg_head(ipmi_msg);
	}
}

void ipmi_wdt_stop(void)
{
	if (!wdt_stopped) {
		/* Make sure the background reset timer is disabled before
		 * stopping the watchdog. If we issue a reset after disabling
		 * the timer, it will be re-enabled. */
		wdt_ticking = false;
		cancel_timer(&wdt_timer);

		/* Configure the watchdog to be disabled and do no action
		 * in case the underlying implementation is buggy and times
		 * out anyway. */
		wdt_stopped = true;
		set_wdt(WDT_NO_ACTION, 100, 0, false, false);
	}
}

void ipmi_wdt_final_reset(void)
{
	/* We can safely stop the timer prior to setting up our final
	 * watchdog timeout since we have enough margin before the
	 * timeout. */
	wdt_ticking = false;
	cancel_timer(&wdt_timer);

	/*
	 * We're going to wait a little while before requiring
	 * BOOTKERNEL to have IPMI watchdog support so that people
	 * can catch up in their development environments.
	 * If you still read this after 2018, send a patch!
	 */
#if 0
	/* Configure the watchdog and make sure it is still enabled */
	set_wdt(WDT_RESET_ACTION | WDT_PRETIMEOUT_SMI, WDT_TIMEOUT,
		WDT_MARGIN/10, true, true);
	sync_reset_wdt();
#else
	set_wdt(WDT_NO_ACTION, 100, 0, false, false);
#endif
	ipmi_set_boot_count();
}

void ipmi_wdt_init(void)
{
	init_timer(&wdt_timer, reset_wdt, NULL);
	set_wdt(WDT_RESET_ACTION, WDT_TIMEOUT, 0, true, false);

	/* Start the WDT. We do it synchronously to make sure it has
	 * started before skiboot continues booting. Otherwise we
	 * could crash before the wdt has actually been started. */
	wdt_ticking = true;
	sync_reset_wdt();

	return;
}