text:
package sarama

import (
	"crypto/tls"
	"encoding/binary"
	"fmt"
	"io"
	"net"
	"strconv"
	"sync"
	"sync/atomic"
	"time"

	"github.com/rcrowley/go-metrics"
)

// Broker represents a single Kafka broker connection. All operations on this object are entirely concurrency-safe.
type Broker struct {
	id   int32
	addr string

	conf          *Config
	correlationID int32
	conn          net.Conn
	connErr       error
	lock          sync.Mutex
	opened        int32

	responses chan responsePromise
	done      chan bool

	incomingByteRate       metrics.Meter
	requestRate            metrics.Meter
	requestSize            metrics.Histogram
	requestLatency         metrics.Histogram
	outgoingByteRate       metrics.Meter
	responseRate           metrics.Meter
	responseSize           metrics.Histogram
	brokerIncomingByteRate metrics.Meter
	brokerRequestRate      metrics.Meter
	brokerRequestSize      metrics.Histogram
	brokerRequestLatency   metrics.Histogram
	brokerOutgoingByteRate metrics.Meter
	brokerResponseRate     metrics.Meter
	brokerResponseSize     metrics.Histogram
}

type responsePromise struct {
	requestTime   time.Time
	correlationID int32
	packets       chan []byte
	errors        chan error
}

// NewBroker creates and returns a Broker targeting the given host:port address.
// This does not attempt to actually connect, you have to call Open() for that.
func NewBroker(addr string) *Broker {
	return &Broker{id: -1, addr: addr}
}

// Open tries to connect to the Broker if it is not already connected or connecting, but does not block
// waiting for the connection to complete. This means that any subsequent operations on the broker will
// block waiting for the connection to succeed or fail. To get the effect of a fully synchronous Open call,
// follow it by a call to Connected(). The only errors Open will return directly are ConfigurationError or
// AlreadyConnected. If conf is nil, the result of NewConfig() is used.
func (b *Broker) Open(conf *Config) error {
	if !atomic.CompareAndSwapInt32(&b.opened, 0, 1) {
		return ErrAlreadyConnected
	}

	if conf == nil {
		conf = NewConfig()
	}

	err := conf.Validate()
	if err != nil {
		return err
	}

	b.lock.Lock()

	go withRecover(func() {
		defer b.lock.Unlock()

		dialer := net.Dialer{
			Timeout:   conf.Net.DialTimeout,
			KeepAlive: conf.Net.KeepAlive,
		}

		if conf.Net.TLS.Enable {
			b.conn, b.connErr = tls.DialWithDialer(&dialer, "tcp", b.addr, conf.Net.TLS.Config)
		} else {
			b.conn, b.connErr = dialer.Dial("tcp", b.addr)
		}
		if b.connErr != nil {
			Logger.Printf("Failed to connect to broker %s: %s\n", b.addr, b.connErr)
			b.conn = nil
			atomic.StoreInt32(&b.opened, 0)
			return
		}
		b.conn = newBufConn(b.conn)

		b.conf = conf

		// Create or reuse the global metrics shared between brokers
		b.incomingByteRate = metrics.GetOrRegisterMeter("incoming-byte-rate", conf.MetricRegistry)
		b.requestRate = metrics.GetOrRegisterMeter("request-rate", conf.MetricRegistry)
		b.requestSize = getOrRegisterHistogram("request-size", conf.MetricRegistry)
		b.requestLatency = getOrRegisterHistogram("request-latency-in-ms", conf.MetricRegistry)
		b.outgoingByteRate = metrics.GetOrRegisterMeter("outgoing-byte-rate", conf.MetricRegistry)
		b.responseRate = metrics.GetOrRegisterMeter("response-rate", conf.MetricRegistry)
		b.responseSize = getOrRegisterHistogram("response-size", conf.MetricRegistry)
		// Do not gather metrics for seeded broker (only used during bootstrap) because they share
		// the same id (-1) and are already exposed through the global metrics above
		if b.id >= 0 {
			b.brokerIncomingByteRate = getOrRegisterBrokerMeter("incoming-byte-rate", b, conf.MetricRegistry)
			b.brokerRequestRate = getOrRegisterBrokerMeter("request-rate", b, conf.MetricRegistry)
			b.brokerRequestSize = getOrRegisterBrokerHistogram("request-size", b, conf.MetricRegistry)
			b.brokerRequestLatency = getOrRegisterBrokerHistogram("request-latency-in-ms", b, conf.MetricRegistry)
			b.brokerOutgoingByteRate = getOrRegisterBrokerMeter("outgoing-byte-rate", b, conf.MetricRegistry)
			b.brokerResponseRate = getOrRegisterBrokerMeter("response-rate", b, conf.MetricRegistry)
			b.brokerResponseSize = getOrRegisterBrokerHistogram("response-size", b, conf.MetricRegistry)
		}

		if conf.Net.SASL.Enable {
			b.connErr = b.sendAndReceiveSASLPlainAuth()
			if b.connErr != nil {
				err = b.conn.Close()
				if err == nil {
					Logger.Printf("Closed connection to broker %s\n", b.addr)
				} else {
					Logger.Printf("Error while closing connection to broker %s: %s\n", b.addr, err)
				}
				b.conn = nil
				atomic.StoreInt32(&b.opened, 0)
				return
			}
		}

		b.done = make(chan bool)
		b.responses = make(chan responsePromise, b.conf.Net.MaxOpenRequests-1)

		if b.id >= 0 {
			Logger.Printf("Connected to broker at %s (registered as #%d)\n", b.addr, b.id)
		} else {
			Logger.Printf("Connected to broker at %s (unregistered)\n", b.addr)
		}
		go withRecover(b.responseReceiver)
	})

	return nil
}

// Connected returns true if the broker is connected and false otherwise. If the broker is not
// connected but it had tried to connect, the error from that connection attempt is also returned.
func (b *Broker) Connected() (bool, error) {
	b.lock.Lock()
	defer b.lock.Unlock()

	return b.conn != nil, b.connErr
}

func (b *Broker) Close() error {
	b.lock.Lock()
	defer b.lock.Unlock()

	if b.conn == nil {
		return ErrNotConnected
	}

	close(b.responses)
	<-b.done

	err := b.conn.Close()

	b.conn = nil
	b.connErr = nil
	b.done = nil
	b.responses = nil

	if err == nil {
		Logger.Printf("Closed connection to broker %s\n", b.addr)
	} else {
		Logger.Printf("Error while closing connection to broker %s: %s\n", b.addr, err)
	}

	atomic.StoreInt32(&b.opened, 0)

	return err
}

// ID returns the broker ID retrieved from Kafka's metadata, or -1 if that is not known.
func (b *Broker) ID() int32 {
	return b.id
}

// Addr returns the broker address as either retrieved from Kafka's metadata or passed to NewBroker.
func (b *Broker) Addr() string {
	return b.addr
}

func (b *Broker) GetMetadata(request *MetadataRequest) (*MetadataResponse, error) {
	response := new(MetadataResponse)

	err := b.sendAndReceive(request, response)

	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) GetConsumerMetadata(request *ConsumerMetadataRequest) (*ConsumerMetadataResponse, error) {
	response := new(ConsumerMetadataResponse)

	err := b.sendAndReceive(request, response)

	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) GetAvailableOffsets(request *OffsetRequest) (*OffsetResponse, error) {
	response := new(OffsetResponse)

	err := b.sendAndReceive(request, response)

	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) Produce(request *ProduceRequest) (*ProduceResponse, error) {
	var response *ProduceResponse
	var err error

	if request.RequiredAcks == NoResponse {
		err = b.sendAndReceive(request, nil)
	} else {
		response = new(ProduceResponse)
		err = b.sendAndReceive(request, response)
	}

	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) Fetch(request *FetchRequest) (*FetchResponse, error) {
	response := new(FetchResponse)

	err := b.sendAndReceive(request, response)

	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) CommitOffset(request *OffsetCommitRequest) (*OffsetCommitResponse, error) {
	response := new(OffsetCommitResponse)

	err := b.sendAndReceive(request, response)

	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) FetchOffset(request *OffsetFetchRequest) (*OffsetFetchResponse, error) {
	response := new(OffsetFetchResponse)

	err := b.sendAndReceive(request, response)

	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) JoinGroup(request *JoinGroupRequest) (*JoinGroupResponse, error) {
	response := new(JoinGroupResponse)

	err := b.sendAndReceive(request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) SyncGroup(request *SyncGroupRequest) (*SyncGroupResponse, error) {
	response := new(SyncGroupResponse)

	err := b.sendAndReceive(request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) LeaveGroup(request *LeaveGroupRequest) (*LeaveGroupResponse, error) {
	response := new(LeaveGroupResponse)

	err := b.sendAndReceive(request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) Heartbeat(request *HeartbeatRequest) (*HeartbeatResponse, error) {
	response := new(HeartbeatResponse)

	err := b.sendAndReceive(request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) ListGroups(request *ListGroupsRequest) (*ListGroupsResponse, error) {
	response := new(ListGroupsResponse)

	err := b.sendAndReceive(request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) DescribeGroups(request *DescribeGroupsRequest) (*DescribeGroupsResponse, error) {
	response := new(DescribeGroupsResponse)

	err := b.sendAndReceive(request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) ApiVersions(request *ApiVersionsRequest) (*ApiVersionsResponse, error) {
	response := new(ApiVersionsResponse)

	err := b.sendAndReceive(request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

func (b *Broker) send(rb protocolBody, promiseResponse bool) (*responsePromise, error) {
	b.lock.Lock()
	defer b.lock.Unlock()

	if b.conn == nil {
		if b.connErr != nil {
			return nil, b.connErr
		}
		return nil, ErrNotConnected
	}

	if !b.conf.Version.IsAtLeast(rb.requiredVersion()) {
		return nil, ErrUnsupportedVersion
	}

	req := &request{correlationID: b.correlationID, clientID: b.conf.ClientID, body: rb}
	buf, err := encode(req, b.conf.MetricRegistry)
	if err != nil {
		return nil, err
	}

	err = b.conn.SetWriteDeadline(time.Now().Add(b.conf.Net.WriteTimeout))
	if err != nil {
		return nil, err
	}

	requestTime := time.Now()
	bytes, err := b.conn.Write(buf)
	b.updateOutgoingCommunicationMetrics(bytes)
	if err != nil {
		return nil, err
	}
	b.correlationID++

	if !promiseResponse {
		// Record request latency without the response
		b.updateRequestLatencyMetrics(time.Since(requestTime))
		return nil, nil
	}

	promise := responsePromise{requestTime, req.correlationID, make(chan []byte), make(chan error)}
	b.responses <- promise

	return &promise, nil
}

func (b *Broker) sendAndReceive(req protocolBody, res versionedDecoder) error {
	promise, err := b.send(req, res != nil)

	if err != nil {
		return err
	}

	if promise == nil {
		return nil
	}

	select {
	case buf := <-promise.packets:
		return versionedDecode(buf, res, req.version())
	case err = <-promise.errors:
		return err
	}
}

func (b *Broker) decode(pd packetDecoder) (err error) {
	b.id, err = pd.getInt32()
	if err != nil {
		return err
	}

	host, err := pd.getString()
	if err != nil {
		return err
	}

	port, err := pd.getInt32()
	if err != nil {
		return err
	}

	b.addr = net.JoinHostPort(host, fmt.Sprint(port))
	if _, _, err := net.SplitHostPort(b.addr); err != nil {
		return err
	}

	return nil
}

func (b *Broker) encode(pe packetEncoder) (err error) {

	host, portstr, err := net.SplitHostPort(b.addr)
	if err != nil {
		return err
	}
	port, err := strconv.Atoi(portstr)
	if err != nil {
		return err
	}

	pe.putInt32(b.id)

	err = pe.putString(host)
	if err != nil {
		return err
	}

	pe.putInt32(int32(port))

	return nil
}

func (b *Broker) responseReceiver() {
	var dead error
	header := make([]byte, 8)
	for response := range b.responses {
		if dead != nil {
			response.errors <- dead
			continue
		}

		err := b.conn.SetReadDeadline(time.Now().Add(b.conf.Net.ReadTimeout))
		if err != nil {
			dead = err
			response.errors <- err
			continue
		}

		bytesReadHeader, err := io.ReadFull(b.conn, header)
		requestLatency := time.Since(response.requestTime)
		if err != nil {
			b.updateIncomingCommunicationMetrics(bytesReadHeader, requestLatency)
			dead = err
			response.errors <- err
			continue
		}

		decodedHeader := responseHeader{}
		err = decode(header, &decodedHeader)
		if err != nil {
			b.updateIncomingCommunicationMetrics(bytesReadHeader, requestLatency)
			dead = err
			response.errors <- err
			continue
		}
		if decodedHeader.correlationID != response.correlationID {
			b.updateIncomingCommunicationMetrics(bytesReadHeader, requestLatency)
			// TODO if decoded ID < cur ID, discard until we catch up
			// TODO if decoded ID > cur ID, save it so when cur ID catches up we have a response
			dead = PacketDecodingError{fmt.Sprintf("correlation ID didn't match, wanted %d, got %d", response.correlationID, decodedHeader.correlationID)}
			response.errors <- dead
			continue
		}

		buf := make([]byte, decodedHeader.length-4)
		bytesReadBody, err := io.ReadFull(b.conn, buf)
		b.updateIncomingCommunicationMetrics(bytesReadHeader+bytesReadBody, requestLatency)
		if err != nil {
			dead = err
			response.errors <- err
			continue
		}

		response.packets <- buf
	}
	close(b.done)
}

func (b *Broker) sendAndReceiveSASLPlainHandshake() error {
	rb := &SaslHandshakeRequest{"PLAIN"}
	req := &request{correlationID: b.correlationID, clientID: b.conf.ClientID, body: rb}
	buf, err := encode(req, b.conf.MetricRegistry)
	if err != nil {
		return err
	}

	err = b.conn.SetWriteDeadline(time.Now().Add(b.conf.Net.WriteTimeout))
	if err != nil {
		return err
	}

	requestTime := time.Now()
	bytes, err := b.conn.Write(buf)
	b.updateOutgoingCommunicationMetrics(bytes)
	if err != nil {
		Logger.Printf("Failed to send SASL handshake %s: %s\n", b.addr, err.Error())
		return err
	}
	b.correlationID++
	//wait for the response
	header := make([]byte, 8) // response header
	_, err = io.ReadFull(b.conn, header)
	if err != nil {
		Logger.Printf("Failed to read SASL handshake header : %s\n", err.Error())
		return err
	}
	length := binary.BigEndian.Uint32(header[:4])
	payload := make([]byte, length-4)
	n, err := io.ReadFull(b.conn, payload)
	if err != nil {
		Logger.Printf("Failed to read SASL handshake payload : %s\n", err.Error())
		return err
	}
	b.updateIncomingCommunicationMetrics(n+8, time.Since(requestTime))
	res := &SaslHandshakeResponse{}
	err = versionedDecode(payload, res, 0)
	if err != nil {
		Logger.Printf("Failed to parse SASL handshake : %s\n", err.Error())
		return err
	}
	if res.Err != ErrNoError {
		Logger.Printf("Invalid SASL Mechanism : %s\n", res.Err.Error())
		return res.Err
	}
	Logger.Print("Successful SASL handshake")
	return nil
}

// Kafka 0.10.0 plans to support SASL Plain and Kerberos as per PR #812 (KIP-43)/(JIRA KAFKA-3149)
// Some hosted kafka services such as IBM Message Hub already offer SASL/PLAIN auth with Kafka 0.9
//
// In SASL Plain, Kafka expects the auth header to be in the following format
// Message format (from https://tools.ietf.org/html/rfc4616):
//
//   message   = [authzid] UTF8NUL authcid UTF8NUL passwd
//   authcid   = 1*SAFE ; MUST accept up to 255 octets
//   authzid   = 1*SAFE ; MUST accept up to 255 octets
//   passwd    = 1*SAFE ; MUST accept up to 255 octets
//   UTF8NUL   = %x00 ; UTF-8 encoded NUL character
//
//   SAFE      = UTF1 / UTF2 / UTF3 / UTF4
//                  ;; any UTF-8 encoded Unicode character except NUL
//
// When credentials are valid, Kafka returns a 4 byte array of null characters.
// When credentials are invalid, Kafka closes the connection. This does not seem to be the ideal way
// of responding to bad credentials but thats how its being done today.
func (b *Broker) sendAndReceiveSASLPlainAuth() error {
	if b.conf.Net.SASL.Handshake {
		handshakeErr := b.sendAndReceiveSASLPlainHandshake()
		if handshakeErr != nil {
			Logger.Printf("Error while performing SASL handshake %s\n", b.addr)
			return handshakeErr
		}
	}
	length := 1 + len(b.conf.Net.SASL.User) + 1 + len(b.conf.Net.SASL.Password)
	authBytes := make([]byte, length+4) //4 byte length header + auth data
	binary.BigEndian.PutUint32(authBytes, uint32(length))
	copy(authBytes[4:], []byte("\x00"+b.conf.Net.SASL.User+"\x00"+b.conf.Net.SASL.Password))

	err := b.conn.SetWriteDeadline(time.Now().Add(b.conf.Net.WriteTimeout))
	if err != nil {
		Logger.Printf("Failed to set write deadline when doing SASL auth with broker %s: %s\n", b.addr, err.Error())
		return err
	}

	requestTime := time.Now()
	bytesWritten, err := b.conn.Write(authBytes)
	b.updateOutgoingCommunicationMetrics(bytesWritten)
	if err != nil {
		Logger.Printf("Failed to write SASL auth header to broker %s: %s\n", b.addr, err.Error())
		return err
	}

	header := make([]byte, 4)
	n, err := io.ReadFull(b.conn, header)
	b.updateIncomingCommunicationMetrics(n, time.Since(requestTime))
	// If the credentials are valid, we would get a 4 byte response filled with null characters.
	// Otherwise, the broker closes the connection and we get an EOF
	if err != nil {
		Logger.Printf("Failed to read response while authenticating with SASL to broker %s: %s\n", b.addr, err.Error())
		return err
	}

	Logger.Printf("SASL authentication successful with broker %s:%v - %v\n", b.addr, n, header)
	return nil
}

func (b *Broker) updateIncomingCommunicationMetrics(bytes int, requestLatency time.Duration) {
	b.updateRequestLatencyMetrics(requestLatency)
	b.responseRate.Mark(1)
	if b.brokerResponseRate != nil {
		b.brokerResponseRate.Mark(1)
	}
	responseSize := int64(bytes)
	b.incomingByteRate.Mark(responseSize)
	if b.brokerIncomingByteRate != nil {
		b.brokerIncomingByteRate.Mark(responseSize)
	}
	b.responseSize.Update(responseSize)
	if b.brokerResponseSize != nil {
		b.brokerResponseSize.Update(responseSize)
	}
}

func (b *Broker) updateRequestLatencyMetrics(requestLatency time.Duration) {
	requestLatencyInMs := int64(requestLatency / time.Millisecond)
	b.requestLatency.Update(requestLatencyInMs)
	if b.brokerRequestLatency != nil {
		b.brokerRequestLatency.Update(requestLatencyInMs)
	}
}

func (b *Broker) updateOutgoingCommunicationMetrics(bytes int) {
	b.requestRate.Mark(1)
	if b.brokerRequestRate != nil {
		b.brokerRequestRate.Mark(1)
	}
	requestSize := int64(bytes)
	b.outgoingByteRate.Mark(requestSize)
	if b.brokerOutgoingByteRate != nil {
		b.brokerOutgoingByteRate.Mark(requestSize)
	}
	b.requestSize.Update(requestSize)
	if b.brokerRequestSize != nil {
		b.brokerRequestSize.Update(requestSize)
	}
}


text:
@implementation MWZGeometryFactory

+ (MWZGeometry*) geometryWithDictionary:(NSDictionary*) dictionary {

    NSString* type = dictionary[@"type"];
    if ([type isEqualToString:@"Polygon"]) {
        return [[MWZGeometryPolygon alloc] initWithDictionary:dictionary];
    }
    else if ([type isEqualToString:@"Point"]) {
        return [[MWZGeometryPoint alloc] initWithDictionary:dictionary];
    }
    else {
        return nil;
    }

}

@end

redpajama_set_name: RedPajamaGithub


text:
package com.behase.remin.webconfig;

import com.behase.remin.interceptor.AddResponseHeaderInterceptor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.fluentd.logger.FluentLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Protocol;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import static com.behase.remin.config.NoticeConfig.NoticeMailConfig;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private AddResponseHeaderInterceptor addResponseHeaderInterceptor;

    @Value("${auth.enabled}")
    private boolean authEnabled;

    @Value("${redis.host}")
    private String redisHost;

    @Value("${redis.port}")
    private int redisPort;

    @Value("${redis.password}")
    private String redisPassword;

    @Value("${notice.mail.host}")
    private String noticeMailHost;

    @Value("${notice.mail.port}")
    private int noticeMailPort;

    @Value("${notice.mail.charset}")
    private String noticeMailCharset;

    @Value("${notice.mail.user}")
    private String noticeMailUser;

    @Value("${notice.mail.password}")
    private String noticeMailPassword;

    @Value("${outputMetrics.fluentd.enabled}")
    private boolean outputMetricsFluentdEnabled;

    @Value("${outputMetrics.fluentd.host}")
    private String outputMetricsFluentdHost;

    @Value("${outputMetrics.fluentd.port}")
    private int outputMetricsFluentdPort;

    @Value("${outputMetrics.fluentd.timeout}")
    private int outputMetricsFluentdTimeout;

    @Value("${outputMetrics.fluentd.bufferCapacity}")
    private int outputMetricsFluentdBufferCapacity;

    @Value("${outputMetrics.fluentd.tag}")
    private String outputMetricsFluentdTag;

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.registerModule(new AfterburnerModule());
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
        format.setTimeZone(TimeZone.getTimeZone("UTC"));
        objectMapper.setDateFormat(format);

        return objectMapper;
    }

    @Bean
    public FilterRegistrationBean characterEncodingFilterRegistrationBean() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);

        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(0);

        return registrationBean;
    }

    @Bean(name = "datastoreRedis", destroyMethod = "destroy")
    public JedisPool jedisPool() {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(10);
        config.setMaxIdle(10);
        config.setMinIdle(5);
        config.setMaxWaitMillis(3000L);
        config.setTestOnBorrow(true);

        JedisPool pool;
        if (StringUtils.isBlank(redisPassword)) {
            pool = new JedisPool(config, redisHost, redisPort, Protocol.DEFAULT_TIMEOUT);
        } else {
            pool = new JedisPool(config, redisHost, redisPort, Protocol.DEFAULT_TIMEOUT, redisPassword);
        }

        return pool;
    }

    @Bean
    public MailSender JavaMailSenderImpl() {
        boolean notNotifyByMail = StringUtils.isBlank(noticeMailHost) || noticeMailPort == 0;
        if (notNotifyByMail) {
            return null;
        }

        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(noticeMailHost);
        mailSender.setPort(noticeMailPort);
        mailSender.setDefaultEncoding(StringUtils.defaultString(noticeMailCharset, NoticeMailConfig.DEFAULT_CHARSET));
        if (StringUtils.isNotBlank(noticeMailUser)) {
            mailSender.setUsername(noticeMailUser);
            mailSender.setPassword(noticeMailPassword);
        }
        return mailSender;
    }

    @Bean(destroyMethod = "close")
    public FluentLogger clusterFluentLogger() {
        if (!outputMetricsFluentdEnabled || StringUtils.isBlank(outputMetricsFluentdHost)
                || outputMetricsFluentdPort == 0) {
            return null;
        }

        return FluentLogger.getLogger(
                outputMetricsFluentdTag, outputMetricsFluentdHost,
                outputMetricsFluentdPort, outputMetricsFluentdTimeout,
                outputMetricsFluentdBufferCapacity);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(addResponseHeaderInterceptor);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        if (authEnabled) {
            registry.addViewController("/login").setViewName("login");
        }
    }
}


text:
import React from 'react';
import renderer from 'react-test-renderer';

import TitleBar from '.';

let name;
let component;

describe(`TitleBar component`, () => {
  beforeEach(() => {
    name = `test@testing.net`;
  });

  it(`renders correctly`, () => {
    component = renderer.create(
      <TitleBar name={name} />
    ).toJSON();
    expect(component).toMatchSnapshot();
  });

});


text:
let current_filter;

exports.reset_current_filter = function () {
    current_filter = undefined;
};

exports.set_current_filter = function (filter) {
    current_filter = filter;
};

exports.active = function () {
    return current_filter !== undefined;
};

exports.filter = function () {
    return current_filter;
};

exports.operators = function () {
    if (current_filter === undefined) {
        return new Filter(page_params.narrow).operators();
    }
    return current_filter.operators();
};

exports.update_email = function (user_id, new_email) {
    if (current_filter !== undefined) {
        current_filter.update_email(user_id, new_email);
    }
};

/* Operators we should send to the server. */
exports.public_operators = function () {
    if (current_filter === undefined) {
        return;
    }
    return current_filter.public_operators();
};

exports.search_string = function () {
    return Filter.unparse(exports.operators());
};

// Collect operators which appear only once into an object,
// and discard those which appear more than once.
function collect_single(operators) {
    const seen   = new Map();
    const result = new Map();

    for (const elem of operators) {
        const key = elem.operator;
        if (seen.has(key)) {
            result.delete(key);
        } else {
            result.set(key, elem.operand);
            seen.set(key, true);
        }
    }

    return result;
}

// Modify default compose parameters (stream etc.) based on
// the current narrowed view.
//
// This logic is here and not in the 'compose' module because
// it will get more complicated as we add things to the narrow
// operator language.
exports.set_compose_defaults = function () {
    const opts = {};
    const single = collect_single(exports.operators());

    // Set the stream, topic, and/or PM recipient if they are
    // uniquely specified in the narrow view.

    if (single.has('stream')) {
        opts.stream = stream_data.get_name(single.get('stream'));
    }

    if (single.has('topic')) {
        opts.topic = single.get('topic');
    }

    if (single.has('pm-with')) {
        const private_message_recipient = single.get('pm-with');
        if (people.is_valid_bulk_emails_for_compose(private_message_recipient.split(','))) {
            opts.private_message_recipient = private_message_recipient;
        }
    }
    return opts;
};

exports.stream = function () {
    if (current_filter === undefined) {
        return;
    }
    const stream_operands = current_filter.operands("stream");
    if (stream_operands.length === 1) {
        const name = stream_operands[0];

        // Use get_name() to get the most current stream
        // name (considering renames and capitalization).
        return stream_data.get_name(name);
    }
    return;
};

exports.stream_sub = function () {
    if (current_filter === undefined) {
        return;
    }
    const stream_operands = current_filter.operands("stream");
    if (stream_operands.length !== 1) {
        return;
    }

    const name = stream_operands[0];
    const sub = stream_data.get_sub_by_name(name);

    return sub;
};

exports.stream_id = function () {
    const sub = exports.stream_sub();

    if (!sub) {
        return;
    }

    return sub.stream_id;
};

exports.topic = function () {
    if (current_filter === undefined) {
        return;
    }
    const operands = current_filter.operands("topic");
    if (operands.length === 1) {
        return operands[0];
    }
    return;
};

exports.pm_string = function () {
    // If you are narrowed to a PM conversation
    // with users 4, 5, and 99, this will return "4,5,99"

    if (current_filter === undefined) {
        return;
    }

    const operands = current_filter.operands("pm-with");
    if (operands.length !== 1) {
        return;
    }

    const emails_string = operands[0];

    if (!emails_string) {
        return;
    }

    const user_ids_string = people.reply_to_to_user_ids_string(emails_string);

    return user_ids_string;
};

exports.get_first_unread_info = function () {
    if (current_filter === undefined) {
        // we don't yet support the all-messages view
        blueslip.error('unexpected call to get_first_unread_info');
        return {
            flavor: 'cannot_compute',
        };
    }

    if (!current_filter.can_apply_locally()) {
        // For things like search queries, where the server has info
        // that the client isn't privvy to, we need to wait for the
        // server to give us a definitive list of messages before
        // deciding where we'll move the selection.
        return {
            flavor: 'cannot_compute',
        };
    }

    const unread_ids = exports._possible_unread_message_ids();

    if (unread_ids === undefined) {
        // _possible_unread_message_ids() only works for certain narrows
        return {
            flavor: 'cannot_compute',
        };
    }

    const msg_id = current_filter.first_valid_id_from(unread_ids);

    if (msg_id === undefined) {
        return {
            flavor: 'not_found',
        };
    }

    return {
        flavor: 'found',
        msg_id: unread_ids[0],
    };
};

exports._possible_unread_message_ids = function () {
    // This function currently only returns valid results for
    // certain types of narrows, mostly left sidebar narrows.
    // For more complicated narrows we may return undefined.
    //
    // If we do return a result, it will be a subset of unread
    // message ids but possibly a superset of unread message ids
    // that match our filter.
    if (current_filter === undefined) {
        return;
    }

    let stream_id;
    let topic_name;
    let pm_string;

    if (current_filter.can_bucket_by('stream', 'topic')) {
        stream_id = exports.stream_id();
        if (stream_id === undefined) {
            return [];
        }
        topic_name = exports.topic();
        return unread.get_msg_ids_for_topic(stream_id, topic_name);
    }

    if (current_filter.can_bucket_by('stream')) {
        stream_id = exports.stream_id();
        if (stream_id === undefined) {
            return [];
        }
        return unread.get_msg_ids_for_stream(stream_id);
    }

    if (current_filter.can_bucket_by('pm-with')) {
        pm_string = exports.pm_string();
        if (pm_string === undefined) {
            return [];
        }
        return unread.get_msg_ids_for_person(pm_string);
    }

    if (current_filter.can_bucket_by('is-private')) {
        return unread.get_msg_ids_for_private();
    }

    if (current_filter.can_bucket_by('is-mentioned')) {
        return unread.get_msg_ids_for_mentions();
    }

    if (current_filter.can_bucket_by('is-starred')) {
        return unread.get_msg_ids_for_starred();
    }

    if (current_filter.can_bucket_by('sender')) {
        // TODO: see #9352 to make this more efficient
        return unread.get_all_msg_ids();
    }

    if (current_filter.can_apply_locally()) {
        return unread.get_all_msg_ids();
    }

    return;
};

// Are we narrowed to PMs: all PMs or PMs with particular people.
exports.narrowed_to_pms = function () {
    if (current_filter === undefined) {
        return false;
    }
    return current_filter.has_operator("pm-with") ||
            current_filter.has_operand("is", "private");
};

exports.narrowed_by_pm_reply = function () {
    if (current_filter === undefined) {
        return false;
    }
    const operators = current_filter.operators();
    return operators.length === 1 &&
            current_filter.has_operator('pm-with');
};

exports.narrowed_by_topic_reply = function () {
    if (current_filter === undefined) {
        return false;
    }
    const operators = current_filter.operators();
    return operators.length === 2 &&
            current_filter.operands("stream").length === 1 &&
            current_filter.operands("topic").length === 1;
};

// We auto-reply under certain conditions, namely when you're narrowed
// to a PM (or huddle), and when you're narrowed to some stream/topic pair
exports.narrowed_by_reply = function () {
    return exports.narrowed_by_pm_reply() ||
            exports.narrowed_by_topic_reply();
};

exports.narrowed_by_stream_reply = function () {
    if (current_filter === undefined) {
        return false;
    }
    const operators = current_filter.operators();
    return operators.length === 1 &&
            current_filter.operands("stream").length === 1;
};

exports.narrowed_to_topic = function () {
    if (current_filter === undefined) {
        return false;
    }
    return current_filter.has_operator("stream") &&
            current_filter.has_operator("topic");
};

exports.narrowed_to_search = function () {
    return current_filter !== undefined && current_filter.is_search();
};

exports.narrowed_to_starred = function () {
    if (current_filter === undefined) {
        return false;
    }
    return current_filter.has_operand("is", "starred");
};

exports.muting_enabled = function () {
    return !exports.narrowed_to_topic() && !exports.narrowed_to_search() &&
            !exports.narrowed_to_pms() && !exports.narrowed_to_starred();
};

exports.is_for_stream_id = function (stream_id) {
    // This is not perfect, since we still track narrows by
    // name, not id, but at least the interface is good going
    // forward.
    const narrow_stream_id = exports.stream_id();

    if (narrow_stream_id === undefined) {
        return false;
    }

    return stream_id === narrow_stream_id;
};

window.narrow_state = exports;


text:
<?php

namespace DbEtreeOrg\Controller;
use Zend\Mvc\Controller\AbstractActionController
    , Zend\View\Model\ViewModel
    , Zend\Form\Annotation\AnnotationBuilder
    , Db\Entity\Performance as PerformanceEntity
    , Db\Entity\PerformerPerformance as PerformerPerformanceEntity
    ;

class PerformanceController extends AbstractActionController
{
    public function indexAction()
    {
        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
        $performances = $em->getRepository('Db\Entity\Performance')->findBy(array(), array('performanceDate' => 'DESC', 'name' => 'ASC'));

        return array(
            'performances' => $performances,
        );
    }

    public function detailAction()
    {
        $id = $this->getRequest()->getQuery()->get('id');
        if (!$id)
            return $this->plugin('redirect')->toUrl('/performance');

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
        $performance = $em->getRepository('Db\Entity\Performance')->find($id);

        if (!$performance)
            throw new \Exception("Performance $id not found");

        $menu = $this->getServiceLocator()->get('menu');
        $menu->addRecent('performances', $performance->getId());

        return array(
            'performance' => $performance
        );
    }

    public function createAction()
    {
        if (!$this->getServiceLocator()->get('zfcuser_auth_service')->hasIdentity())
            return $this->plugin('redirect')->toUrl('/user/login');

        $performance = new PerformanceEntity();
        $builder = new AnnotationBuilder();
        $form = $builder->createForm($performance);

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

        $id = $this->getRequest()->getQuery()->get('id');
        $lineup = $em->getRepository('Db\Entity\Lineup')->find($id);

        if ($this->getRequest()->isPost()) {
            $valid = true;
            $form->setData($this->getRequest()->getPost()->toArray());
            $form->setUseInputFilterDefaults(false);
            $form->setInputFilter($performance->getInputFilter());

            $venue_id = $this->getRequest()->getPost()->get('venue_id');
            $venue = $em->getRepository('Db\Entity\Venue')->find($venue_id);
            if (!$venue) $valid = false;

            $event_id = $this->getRequest()->getPost()->get('event_id');
            $event = ($event_id) ? $em->getRepository('Db\Entity\Event')->find($event_id): null;

            if ($valid and $form->isValid()) {
                $data = $form->getData();
                $performance->exchangeArray($form->getData());
                $performance->setLineup($lineup);
                $performance->setVenue($venue);
                if ($event) $performance->setEvent($event);

                $em->persist($performance);
                $em->flush();

                return $this->plugin('redirect')->toUrl('/performance/detail?id=' . $performance->getId());
            }
        }

        return array(
            'form' => $form,
            'lineup' => $lineup,
        );
    }

    public function editAction()
    {
        if (!$this->getServiceLocator()->get('zfcuser_auth_service')->hasIdentity())
            return $this->plugin('redirect')->toUrl('/user/login');

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

        $id = $this->getRequest()->getQuery()->get('id');
        $performance = $em->getRepository('Db\Entity\Performance')->find($id);

        if (!$performance)
            throw new \Exception("Performance $id not found");

        $builder = new AnnotationBuilder();
        $form = $builder->createForm($performance);
        $form->setData($performance->getArrayCopy());

        if ($this->getRequest()->isPost()) {
            $form->setData($this->getRequest()->getPost()->toArray());
            $form->setUseInputFilterDefaults(false);
            $form->setInputFilter($performance->getInputFilter());

            if ($form->isValid()) {
                $data = $form->getData();
                $performance->exchangeArray($form->getData());

                $em->persist($performance);
                $em->flush();

                die();
            }
        }

        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        $viewModel->setVariable('form', $form);
        $viewModel->setVariable('performance', $performance);
        return $viewModel;
    }

    public function deleteAction()
    {
        if (!$this->getServiceLocator()->get('zfcuser_auth_service')->hasIdentity())
            return $this->plugin('redirect')->toUrl('/user/login');

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

        $id = $this->getRequest()->getQuery()->get('id');
        $performance = $em->getRepository('Db\Entity\Performance')->find($id);
        if (!$performance)
            return $this->plugin('redirect')->toUrl('/');

        if (!sizeof($performance->getAliases())
            and !sizeof($performance->getPerformances())
            and !sizeof($performance->getPerformances())
            and !sizeof($performance->getLinks())
            and !sizeof($performance->getComments()))
        {
            $em->remove($performance);
            $em->flush();
        }

        return $this->plugin('redirect')->toUrl('/');
    }

    public function addSetAction()
    {
        $id = $this->getRequest()->getPost()->get('id');
        $performerId = $this->getRequest()->getPost()->get('performer_id');
        $returnUrl = $this->getRequest()->getPost()->get('returnUrl');

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

        $performance = $em->getRepository('Db\Entity\Performance')->find($id);
        $performer = $em->getRepository('Db\Entity\Performer')->find($performerId);

        $performance->getPerformers()->add($performer);
        $performer->getPerformances()->add($performance);

        $em->flush();

        return $this->plugin('redirect')->toUrl($returnUrl);
    }

    public function addPerformerAction()
    {
        $id = $this->getRequest()->getPost()->get('id');
        $note = $this->getRequest()->getPost()->get('note');
        $performerId = $this->getRequest()->getPost()->get('performer_id');

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

        $performance = $em->getRepository('Db\Entity\Performance')->find($id);
        $performer = $em->getRepository('Db\Entity\Performer')->find($performerId);
        $performerPerformance = new PerformerPerformanceEntity;

        $performerPerformance->setPerformer($performer);
        $performerPerformance->setPerformance($performance);
        $performerPerformance->setNote($note);

        $em->persist($performerPerformance);
        $em->flush();

        return $this->plugin('redirect')->toUrl('/performance/detail?id=' . $id);
    }

    public function removePerformerAction()
    {
        $id = $this->getRequest()->getPost()->get('id');
        $performerId = $this->getRequest()->getPost()->get('performer_id');

        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

        $performance = $em->getRepository('Db\Entity\Performance')->find($id);
        $performer = $em->getRepository('Db\Entity\Performer')->find($performerId);

        $performerPerformance = $em->getRepository('Db\Entity\PerformerPerformance')->findOneBy(array(
            'performer' => $performer,
            'performance' => $performance,
        ));

        $em->remove($performerPerformance);
        $em->flush();

        return $this->plugin('redirect')->toUrl('/performance/detail?id=' . $id);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@color/splash_background">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/imgpsh_fullsize"/>

</LinearLayout>


text:
package com.compositesw.services.system.admin.execute;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for executeNativeSqlResponse complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="executeNativeSqlResponse">
 *   <complexContent>
 *     <extension base="{http://www.compositesw.com/services/system/admin/execute}baseExecuteSqlResponse">
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "executeNativeSqlResponse")
public class ExecuteNativeSqlResponse
    extends BaseExecuteSqlResponse
{

}


text:
package com.cadyyan.levels.utils;

import com.cadyyan.levels.Levels;
import org.apache.logging.log4j.*;
import org.apache.logging.log4j.message.Message;

// Inspired by Pahimar's LogHelper class
// https://github.com/pahimar/Equivalent-Exchange-3/blob/master/src/main/java/com/pahimar/ee3/util/LogHelper.java

public class LogUtility
{
	public static final Marker MOD_MARKER = MarkerManager.getMarker(Levels.MOD_ID);
	public static final Logger LOGGER = LogManager.getLogger(Levels.MOD_ID);

	// Generic logging

	public static void log(Level level, Marker marker, Message message)
	{
		LOGGER.log(level, marker, message);
	}

	public static void log(Level level, Marker marker, Object object)
	{
		LOGGER.log(level, marker, object);
	}

	public static void log(Level level, Marker marker, String message)
	{
		LOGGER.log(level, marker, message);
	}

	public static void log(Level level, Marker marker, String format, Object... params)
	{
		LOGGER.log(level, marker, format, params);
	}

	// Mod specific logging

	public static void log(Level level, Message message)
	{
		log(level, MOD_MARKER, message);
	}

	public static void log(Level level, Object object)
	{
		log(level, MOD_MARKER, object);
	}

	public static void log(Level level, String message)
	{
		log(level, MOD_MARKER, message);
	}

	public static void log(Level level, String format, Object... params)
	{
		log(level, MOD_MARKER, format, params);
	}

	// All level logging

	public static void all(Marker marker, Message message)
	{
		log(Level.ALL, marker, message);
	}

	public static void all(Marker marker, Object object)
	{
		log(Level.ALL, marker, object);
	}

	public static void all(Marker marker, String message)
	{
		log(Level.ALL, marker, message);
	}

	public static void all(Marker marker, String format, Object... params)
	{
		log(Level.ALL, marker, format, params);
	}

	public static void all(Message message)
	{
		log(Level.ALL, message);
	}

	public static void all(Object object)
	{
		log(Level.ALL, object);
	}

	public static void all(String message)
	{
		log(Level.ALL, message);
	}

	public static void all(String format, Object... params)
	{
		log(Level.ALL, format, params);
	}

	// Debug level logging

	public static void debug(Marker marker, Message message)
	{
		log(Level.DEBUG, marker, message);
	}

	public static void debug(Marker marker, Object object)
	{
		log(Level.DEBUG, marker, object);
	}

	public static void debug(Marker marker, String message)
	{
		log(Level.DEBUG, marker, message);
	}

	public static void debug(Marker marker, String format, Object... params)
	{
		log(Level.DEBUG, marker, format, params);
	}

	public static void debug(Message message)
	{
		log(Level.DEBUG, message);
	}

	public static void debug(Object object)
	{
		log(Level.DEBUG, object);
	}

	public static void debug(String message)
	{
		log(Level.DEBUG, message);
	}

	public static void debug(String format, Object... params)
	{
		log(Level.DEBUG, format, params);
	}

	// Error level logging

	public static void error(Marker marker, Message message)
	{
		log(Level.ERROR, marker, message);
	}

	public static void error(Marker marker, Object object)
	{
		log(Level.ERROR, marker, object);
	}

	public static void error(Marker marker, String message)
	{
		log(Level.ERROR, marker, message);
	}

	public static void error(Marker marker, String format, Object... params)
	{
		log(Level.ERROR, marker, format, params);
	}

	public static void error(Message message)
	{
		log(Level.ERROR, message);
	}

	public static void error(Object object)
	{
		log(Level.ERROR, object);
	}

	public static void error(String message)
	{
		log(Level.ERROR, message);
	}

	public static void error(String format, Object... params)
	{
		log(Level.ERROR, format, params);
	}

	// Fatal level logging

	public static void fatal(Marker marker, Message message)
	{
		log(Level.FATAL, marker, message);
	}

	public static void fatal(Marker marker, Object object)
	{
		log(Level.FATAL, marker, object);
	}

	public static void fatal(Marker marker, String message)
	{
		log(Level.FATAL, marker, message);
	}

	public static void fatal(Marker marker, String format, Object... params)
	{
		log(Level.FATAL, marker, format, params);
	}

	public static void fatal(Message message)
	{
		log(Level.FATAL, message);
	}

	public static void fatal(Object object)
	{
		log(Level.FATAL, object);
	}

	public static void fatal(String message)
	{
		log(Level.FATAL, message);
	}

	public static void fatal(String format, Object... params)
	{
		log(Level.FATAL, format, params);
	}

	// Info level logging

	public static void info(Marker marker, Message message)
	{
		log(Level.INFO, marker, message);
	}

	public static void info(Marker marker, Object object)
	{
		log(Level.INFO, marker, object);
	}

	public static void info(Marker marker, String message)
	{
		log(Level.INFO, marker, message);
	}

	public static void info(Marker marker, String format, Object... params)
	{
		log(Level.INFO, marker, format, params);
	}

	public static void info(Message message)
	{
		log(Level.INFO, message);
	}

	public static void info(Object object)
	{
		log(Level.INFO, object);
	}

	public static void info(String message)
	{
		log(Level.INFO, message);
	}

	public static void info(String format, Object... params)
	{
		log(Level.INFO, format, params);
	}

	// Off level logging

	public static void off(Marker marker, Message message)
	{
		log(Level.OFF, marker, message);
	}

	public static void off(Marker marker, Object object)
	{
		log(Level.OFF, marker, object);
	}

	public static void off(Marker marker, String message)
	{
		log(Level.OFF, marker, message);
	}

	public static void off(Marker marker, String format, Object... params)
	{
		log(Level.OFF, marker, format, params);
	}

	public static void off(Message message)
	{
		log(Level.OFF, message);
	}

	public static void off(Object object)
	{
		log(Level.OFF, object);
	}

	public static void off(String message)
	{
		log(Level.OFF, message);
	}

	public static void off(String format, Object... params)
	{
		log(Level.OFF, format, params);
	}

	// Trace level logging

	public static void trace(Marker marker, Message message)
	{
		log(Level.TRACE, marker, message);
	}

	public static void trace(Marker marker, Object object)
	{
		log(Level.TRACE, marker, object);
	}

	public static void trace(Marker marker, String message)
	{
		log(Level.TRACE, marker, message);
	}

	public static void trace(Marker marker, String format, Object... params)
	{
		log(Level.TRACE, marker, format, params);
	}

	public static void trace(Message message)
	{
		log(Level.TRACE, message);
	}

	public static void trace(Object object)
	{
		log(Level.TRACE, object);
	}

	public static void trace(String message)
	{
		log(Level.TRACE, message);
	}

	public static void trace(String format, Object... params)
	{
		log(Level.TRACE, format, params);
	}

	// Warn level logging

	public static void warn(Marker marker, Message message)
	{
		log(Level.TRACE, marker, message);
	}

	public static void warn(Marker marker, Object object)
	{
		log(Level.TRACE, marker, object);
	}

	public static void warn(Marker marker, String message)
	{
		log(Level.TRACE, marker, message);
	}

	public static void warn(Marker marker, String format, Object... params)
	{
		log(Level.TRACE, marker, format, params);
	}

	public static void warn(Message message)
	{
		log(Level.TRACE, message);
	}

	public static void warn(Object object)
	{
		log(Level.TRACE, object);
	}

	public static void warn(String message)
	{
		log(Level.TRACE, message);
	}

	public static void warn(String format, Object... params)
	{
		log(Level.TRACE, format, params);
	}

	private LogUtility()
	{
	}
}


text:
import goldenrod
import datetime, time

def execute(parser, bot, user, args):
    if not parser.checkPerms(bot, user, "broadcaster"):
        return
    bot.execQueryModify("UPDATE channels SET joinIfLive = ?, lastChange = ? WHERE channel = ?", (False, int(time.time()), bot.factory.channel))
    goldenrod.leaveChannel(bot.factory.channel, "Leaving at broadcaster's request, bye all!")

def requiredPerm():
    return "broadcaster"

def canUseByWhisper():
    return False


text:
/* ###
 * IP: GHIDRA
 *
 * 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.
 */
package agent.dbgeng.jna.dbgeng.io;

import com.sun.jna.platform.win32.COM.IUnknownCallback;

public interface CallbackIDebugOutputCallbacksWide
		extends IDebugOutputCallbacksWide, IUnknownCallback {
}


text:
struct ifa_msghdr;

struct iface_addr {
  unsigned system : 1;		/* System alias ? */
  struct ncprange ifa;		/* local address/mask */
  struct ncpaddr peer;		/* peer address */
};

struct iface {
  char *name;			/* Interface name (malloc'd) */
  int index;			/* Interface index */
  int flags;			/* Interface flags (IFF_*) */
  unsigned long mtu;		/* struct tuninfo MTU */

  unsigned addrs;		/* How many in_addr's */
  struct iface_addr *addr;	/* Array of addresses (malloc'd) */
};

#define IFACE_CLEAR_ALL		0	/* Nuke 'em all */
#define IFACE_CLEAR_ALIASES	1	/* Leave the NCP address */

#define IFACE_ADD_LAST		0	/* Just another alias */
#define IFACE_ADD_FIRST		1	/* The IPCP address */
#define IFACE_FORCE_ADD		2	/* OR'd with IFACE_ADD_{FIRST,LAST} */

#define IFACE_SYSTEM		4	/* Set/clear SYSTEM entries */

extern struct iface *iface_Create(const char *name);
extern void iface_Clear(struct iface *, struct ncp *, int, int);
extern int iface_Add(struct iface *, struct ncp *, const struct ncprange *,
                     const struct ncpaddr *, int);
extern int iface_Delete(struct iface *, struct ncp *, const struct ncpaddr *);
extern int iface_Show(struct cmdargs const *);
extern int iface_SetFlags(const char *, int);
extern int iface_ClearFlags(const char *, int);
extern void iface_Destroy(struct iface *);
extern void iface_ParseHdr(struct ifa_msghdr *, struct sockaddr *[RTAX_MAX]);


text:
require 'spec_helper'

describe UsersHelper do
  let(:user) { double('User') }

  before :each do
    user.stub(:gravatar_user_hash).and_return('b6694c75d95b8c1571f0ea8d732e6866')
    user.stub(:facebook_username).and_return('jose.a.padilla')
    user.stub(:twitter_username).and_return('JonahBinario')
    user.stub(:linkedin_username).and_return('joseapadilla')
    user.stub(:github_username).and_return('jonahoffline')
    user.stub(:flickr_username).and_return('99104748@N07')
    user.stub(:dribbble_username).and_return('toxinide')
    user.stub(:website_url).and_return('http://www.pixelhipsters.com')
    user.stub(:facebook_username?).and_return(true)
    user.stub(:twitter_username?).and_return(true)
    user.stub(:linkedin_username?).and_return(true)
    user.stub(:github_username?).and_return(true)
    user.stub(:flickr_username?).and_return(true)
    user.stub(:dribbble_username?).and_return(true)
    user.stub(:website_url?).and_return(true)
  end

  describe '#gravatar_for' do
    it 'returns gravatar url with default size' do
      expect(helper.gravatar_for(user))
        .to eq('http://gravatar.com/avatar/b6694c75d95b8c1571f0ea8d732e6866.png?s=140')
    end

    it 'returns gravatar url with custom size' do
      expect(helper.gravatar_for(user, { size: 300 }))
        .to eq('http://gravatar.com/avatar/b6694c75d95b8c1571f0ea8d732e6866.png?s=300')
    end
  end

  describe '#facebook_url' do
    it 'returns facebook url for username' do
      expect(helper.facebook_url(user))
      .to eq('https://facebook.com/jose.a.padilla')
    end
  end

  describe '#twitter_url' do
    it 'returns twitter url for username' do
      expect(helper.twitter_url(user))
      .to eq('https://twitter.com/JonahBinario')
    end
  end

  describe '#linkedin_url' do
    it 'returns linkedin url for username' do
      expect(helper.linkedin_url(user))
      .to eq('http://www.linkedin.com/in/joseapadilla')
    end
  end

  describe '#github_url' do
    it 'returns github url for username' do
      expect(helper.github_url(user))
      .to eq('https://github.com/jonahoffline')
    end
  end
  describe '#flickr_url' do
    it 'returns flickr url for username' do
      expect(helper.flickr_url(user))
      .to eq('http://www.flickr.com/people/99104748@N07/')
    end
  end

  describe '#dribbble_url' do
    it 'returns dribbble url for username' do
      expect(helper.dribbble_url(user))
      .to eq('http://dribbble.com/toxinide')
    end
  end

  describe '#facebook_icon_link' do
    it 'returns facebook icon in an  tag nested inside an anchor link' do
      expect(helper.facebook_icon_link(user))
      .to eq("")
    end
  end

  describe '#twitter_icon_link' do
    it 'returns twitter icon in an  tag nested inside an anchor link' do
      expect(helper.twitter_icon_link(user))
      .to eq("")
    end
  end

  describe '#linkedin_icon_link' do
    it 'returns linkedin icon in an  tag nested inside an anchor link' do
      expect(helper.linkedin_icon_link(user))
      .to eq("")
    end
  end

  describe '#github_icon_link' do
    it 'returns github icon in an  tag nested inside an anchor link' do
      expect(helper.github_icon_link(user))
      .to eq("")
    end
  end

  describe '#flickr_icon_link' do
    it 'returns flickr icon in an  tag nested inside an anchor link' do
      expect(helper.flickr_icon_link(user))
      .to eq("")
    end
  end
  describe '#dribbble_icon_link' do
    it 'returns dribbble icon in an  tag nested inside an anchor link' do
      expect(helper.dribbble_icon_link(user))
      .to eq("")
    end
  end

  describe '#website_icon_link' do
    it 'returns website icon in an  tag nested inside an anchor link' do
      expect(helper.website_icon_link(user))
      .to eq("")
    end
  end

  describe '#social_icon_links' do
    context 'when all social profiles are available' do
      it 'returns unsorted list with social icons for all accounts' do
        expect(helper.social_icon_links(user))
        .to eq("

")
      end
    end
  end

end


text:
peacock
=======

a lightweight image sharing webapp


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
MonitoredOutputStream
</TITLE>

<META NAME="keywords" CONTENT="tot.upload.MonitoredOutputStream class">

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

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造函数 | 方法

详细信息: 字段 | 构造函数 | 方法

tot.upload

类 MonitoredOutputStream

java.lang.Object
  java.io.OutputStream
      tot.upload.MonitoredOutputStream

所有已实现的接口:
java.io.Closeable, java.io.Flushable

public class MonitoredOutputStream
extends java.io.OutputStream

构造函数摘要

MonitoredOutputStream(java.io.OutputStream target,
                      OutputStreamListener listener)

方法摘要

 void
close()

 void
flush()

 void
write(byte[] b)

 void
write(byte[] b,
      int off,
      int len)

 void
write(int b)

从类 java.lang.Object 继承的方法

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

构造函数详细信息

MonitoredOutputStream

public MonitoredOutputStream(java.io.OutputStream target,
                             OutputStreamListener listener)

方法详细信息

write

public void write(byte[] b,
                  int off,
                  int len)
           throws java.io.IOException

覆盖:
类 java.io.OutputStream 中的 write

抛出:

java.io.IOException

write

public void write(byte[] b)
           throws java.io.IOException

覆盖:
类 java.io.OutputStream 中的 write

抛出:

java.io.IOException

write

public void write(int b)
           throws java.io.IOException

指定者:
类 java.io.OutputStream 中的 write

抛出:

java.io.IOException

close

public void close()
           throws java.io.IOException

指定者:
接口 java.io.Closeable 中的 close
覆盖:
类 java.io.OutputStream 中的 close

抛出:

java.io.IOException

flush

public void flush()
           throws java.io.IOException

指定者:
接口 java.io.Flushable 中的 flush
覆盖:
类 java.io.OutputStream 中的 flush

抛出:

java.io.IOException

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造函数 | 方法

详细信息: 字段 | 构造函数 | 方法


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

require 'date'

require_relative '../lib/Shared/date_interval'
require_relative '../lib/Shared/date_utility'
require_relative '../lib/Shared/EntityClasses/enum/GradeLevelType'
require_relative '../lib/Shared/EntityClasses/enum/SchoolTerm'
require_relative '../lib/Shared/EntityClasses/session'
require_relative '../lib/Shared/util'
require_relative '../lib/WorldDefinition/gradebook_entry_factory'
require_relative 'spec_helper'

# specifications for the grade book entry factory
describe "GradebookEntryFactory" do
  describe "--> requesting gradebook entries" do
    let(:random)         { Random.new(1234567890) }
    let(:year)           { 2012 }
    let(:start_date)     { Date.new(year, 12, 3) }
    let(:end_date)       { Date.new(year, 12, 28) }
    let(:interval)       { DateInterval.create_using_start_and_end_dates(random, start_date, end_date) }
    let(:grading_period) { {"interval" => interval, "year" => year} }
    let(:session)        { {"interval" => interval, "grading_periods" => [grading_period]} }
    let(:section)        { {:ed_org_id => "school123", :unique_section_code => 1} }

    let(:scenario) { {'GRADEBOOK_ENTRIES_BY_GRADE' => {
        "First grade" => { "Homework" => {"min" => 8, "max" => 16} },
        "Second grade" => { "Homework" => {"min" => 12, "max" => 24}, "Quiz" => {"min" => 2, "max" => 4} }
      }}
    }
    let(:factory) { GradebookEntryFactory.new(scenario) }

    it "will create the specified number of gradebook entry work orders within the session for the requested grade" do
      grade           = :SECOND_GRADE
      orders          = factory.generate_entries(random, grade, session, section)
      homework_orders = orders.select { |order| order[:gbe_type] == "Homework" }
      quiz_orders     = orders.select { |order| order[:gbe_type] == "Quiz" }
      out_of_bounds   = orders.select { |order| order[:date_assigned] < start_date or order[:date_assigned] > end_date }

      orders.size.should eq(21)
      homework_orders.size.should eq(17)
      quiz_orders.size.should eq(4)
      out_of_bounds.size.should eq(0)
    end

    it "will not create gradebook entry work orders that fall on holidays" do
      grade          = :SECOND_GRADE
      orders         = factory.generate_entries(random, grade, session, section)
      holiday_orders = orders.select { |order| order[:date_assigned] == Date.new(2012, 12, 24) || order[:date_assigned] == Date.new(2012, 12, 25) }

      orders.size.should eq(21)
      holiday_orders.size.should eq(0)
    end

    it "will not create unspecified gradebook entry work orders (specifically when a grade does not have Quiz, there should be no Quiz entries)" do
      grade           = :FIRST_GRADE
      orders          = factory.generate_entries(random, grade, session, section)
      homework_orders = orders.select { |order| order[:gbe_type] == "Homework" }
      quiz_orders     = orders.select { |order| order[:gbe_type] == "Quiz" }
      out_of_bounds   = orders.select { |order| order[:date_assigned] < start_date or order[:date_assigned] > end_date }

      orders.size.should eq(13)
      homework_orders.size.should eq(orders.size)
      quiz_orders.size.should eq(0)
      out_of_bounds.size.should eq(0)
    end
  end

  describe "--> requesting (edge case) gradebook entries" do
    let(:random)         { Random.new(1234567890) }
    let(:year)           { 2012 }
    let(:start_date)     { Date.new(year, 12, 3) }
    let(:end_date)       { Date.new(year, 12, 28) }
    let(:interval)       { DateInterval.create_using_start_and_end_dates(random, start_date, end_date) }
    let(:grading_period) { {"interval" => interval, "year" => year} }
    let(:session)        { {"interval" => interval, "grading_periods" => [grading_period]} }
    let(:section)        { {:ed_org_id => "school123", :unique_section_code => 1} }

    let(:scenario) { {'GRADEBOOK_ENTRIES_BY_GRADE' => {
        "First grade" => { "Homework" => {"min" => 1, "max" => 1} },
        "Second grade" => { "Homework" => {"min" => 0, "max" => 0} }
      }}
    }
    let(:factory) { GradebookEntryFactory.new(scenario) }

    it "will handle the case where one gradebook entry is specified by returning end date of session" do
      grade           = :FIRST_GRADE
      orders          = factory.generate_entries(random, grade, session, section)
      homework_orders = orders.select { |order| order[:gbe_type] == "Homework" }
      out_of_bounds   = orders.select { |order| order[:date_assigned] < start_date or order[:date_assigned] > end_date }

      orders.size.should eq(1)
      homework_orders.size.should eq(orders.size)
      out_of_bounds.size.should eq(0)

      homework_order  = homework_orders.pop
      homework_order[:date_assigned].should eq(end_date)
    end

    it "will return an empty array when zero gradebook entries are specified" do
      grade           = :SECOND_GRADE
      orders          = factory.generate_entries(random, grade, session, section)
      orders.size.should eq(0)
    end
  end

  describe "--> when a property" do
    let(:grade) { :SECOND_GRADE }
    let(:random) { Random.new(1234567890) }
    let(:start_date) { Date.new(2012, 12, 3) }
    let(:end_date) { Date.new(2012, 12, 28) }
    let(:interval) { DateInterval.create_using_start_and_end_dates(random, start_date, end_date) }
    let(:session) { {"interval" => interval} }
    let(:section) { {:ed_org_id => "school123", :unique_section_code => 1} }

    it "(scenario) is missing --> raise error message" do
      scenario = nil
      factory  = GradebookEntryFactory.new(scenario)
      expect { factory.generate_entries(random, grade, session, section) }.to raise_exception(ArgumentError)
    end

    it "(gradebook entry breakdown) is missing --> raise error message" do
      scenario = {}
      factory  = GradebookEntryFactory.new(scenario)
      expect { factory.generate_entries(random, grade, session, section) }.to raise_exception(ArgumentError)
    end

    it "(requested grade) is missing --> raise error message" do
      scenario = { 'GRADEBOOK_ENTRIES_BY_GRADE' => {"Third grade" => { "Homework" => {"min" => 12, "max" => 24}}}}
      factory  = GradebookEntryFactory.new(scenario)
      expect { factory.generate_entries(random, grade, session, section) }.to raise_exception(ArgumentError)
    end

    it "(assignment key) is missing --> raise error message" do
      scenario = { 'GRADEBOOK_ENTRIES_BY_GRADE' => {"" => { "Homework" => {"min" => 12, "max" => 24}}}}
      factory  = GradebookEntryFactory.new(scenario)
      expect { factory.generate_entries(random, grade, session, section) }.to raise_exception(ArgumentError)
    end

    it "(minimum number of assignments) is missing --> raise error message" do
      scenario = { 'GRADEBOOK_ENTRIES_BY_GRADE' => {"Second grade" => { "Homework" => {"max" => 24}}}}
      factory  = GradebookEntryFactory.new(scenario)
      expect { factory.generate_entries(random, grade, session, section) }.to raise_exception(ArgumentError)
    end

    it "(maximum number of assignments) is missing --> raise error message" do
      scenario = { 'GRADEBOOK_ENTRIES_BY_GRADE' => {"Second grade" => { "Homework" => {"min" => 12}}}}
      factory  = GradebookEntryFactory.new(scenario)
      expect { factory.generate_entries(random, grade, session, section) }.to raise_exception(ArgumentError)
    end
  end
end


text:
gulp plugin for coffee-coverage. Compiles CoffeeScript into Javascript with coverage logic.

[![Build Status](https://travis-ci.org/WHenderson/gulp-coffee-coverage.svg?branch=master)](https://travis-ci.org/WHenderson/gulp-coffee-coverage)
[![Coverage Status](https://coveralls.io/repos/WHenderson/gulp-coffee-coverage/badge.svg?branch=master&service=github)](https://coveralls.io/github/WHenderson/gulp-coffee-coverage?branch=master)

## Usage

```javascript
var coverage = require('../');

gulp.task('coffee-coverage', function() {
    return gulp.src('src/*.coffee')
    .pipe(coverage({ bare: true }).on('error', gutil.log))
    .pipe(gulp.dest('dist'));
});
```

### Error handling

gulp-coffee-coverage will emit an error for cases such as invalid coffeescript syntax. If uncaught, the error will crash gulp.

You will need to attach a listener (i.e. `.on('error')`) for the error event emitted by gulp-coffee-coverage:

```javascript
var coverageStream = coverage({bare: true});

// Attach listener
coverageStream.on('error', function(err) {});
```

In addition, you may utilize [gulp-util](https://github.com/wearefractal/gulp-util)'s logging function:

```javascript
var gutil = require('gulp-util');

// ...

var coverageStream = coverage({bare: true});

// Attach listener
coverageStream.on('error', gutil.log);

```

Since `.on(...)` returns `this`, you can compact it as inline code:

```javascript

gulp.src('./src/*.coffee')
  .pipe(coverage({bare: true}).on('error', gutil.log))
  // ...
```

### Options

|name|type|description|
|----|----|-----------|
|bare|Boolean|Do not wrap files in an anonymous function|
|initfile|String|Generate an coverage initiation file|
|initfile|Object Literal|Generate an coverage initiation file. Options are used to initialise the vinyl-fs file added to the stream |
|instrumentor|String|Instrumentor to use with coffee-coverage. Either 'istanbul' or 'jscoverage'|

## Installation

```
npm install --save-dev gulp-coffee-coverage
```


text:
using System;
using System.Runtime.InteropServices;

namespace TwitchLeecher.Setup.Gui
{
    internal static class NativeMethods
    {
        [DllImport("Shell32.dll", SetLastError = false)]
        public static extern int SHGetStockIconInfo(SHSTOCKICONID siid, SHGSI uFlags, ref SHSTOCKICONINFO psii);

        public enum SHSTOCKICONID : uint
        {
            SIID_SHIELD = 77
        }

        [Flags]
        public enum SHGSI : uint
        {
            SHGSI_ICON = 0x000000100,
            SHGSI_SMALLICON = 0x000000001
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct SHSTOCKICONINFO
        {
            public uint cbSize;
            public IntPtr hIcon;
            public int iSysIconIndex;
            public int iIcon;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szPath;
        }
    }
}


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />

    <script src="../../../webcomponentsjs/webcomponents-lite.js"></script>
    <script src="../../../web-component-tester/browser.js"></script>

    <link rel="import" href="../../autocomplete/view.html" />
  </head>
  <body>
    <test-fixture id="autocomplete">
      <template>
        <autocomplete-clab>This is my note</autocomplete-clab>
      </template>
    </test-fixture>

    <script>
      describe('<autocomplete-clab>', function () {
        var autocomplete;

        beforeEach(function () {
          autocomplete = fixture('autocomplete');
          autocomplete.liHeight = 20;
        });

        context('Test Properties', function () {
          it('Default Properties', function (done) {
            expect(autocomplete.label).to.equal(null);
            expect(autocomplete.name).to.equal('auto complete');
            expect(autocomplete.disabled).to.equal(false);
            expect(autocomplete.hideHints).to.equal(false);
            expect(autocomplete.resultAsObj).to.equal(false);
            expect(autocomplete.minChar).to.equal(3);
            expect(autocomplete.maxInView).to.equal(6);
            expect(autocomplete.inputType).to.equal('');
            expect(autocomplete.noteType).to.be.undefined;
            expect(autocomplete.value).to.be.undefined;
            expect(autocomplete.options).to.be.undefined;
            expect(autocomplete.url).to.be.undefined;
            expect(autocomplete.results).to.be.an('array');
            expect(autocomplete.optionsFn).to.be.undefined;
            expect(autocomplete.placeholder).to.equal('Type..');

            done();
          });
        });

        context('Test DOM Bindings', function () {
          it('Check label', function (done) {
            var str = 'ciccio';
            autocomplete.name = str;

            setTimeout(function () {
              expect(autocomplete.querySelector('input-clab').name).to.equal(
                str
              );

              done();
            }, 50);
          });

          it('Check name', function (done) {
            var str = 'ciccio';
            autocomplete.label = str;

            setTimeout(function () {
              expect(autocomplete.querySelector('label')).to.not.be.undefined;

              done();
            }, 50);
          });

          it('Check inputType & noteType', function (done) {
            var str = 'ciccio';
            var str2 = 'ciccio2';
            autocomplete.label = str;
            autocomplete.inputType = str;
            autocomplete.noteType = str2;

            setTimeout(function () {
              expect(
                autocomplete.querySelector('label').classList.contains(str)
              ).to.equal(true);
              expect(
                autocomplete
                  .querySelector('input[type=text]')
                  .classList.contains(str)
              ).to.equal(true);
              expect(
                autocomplete
                  .querySelector('.input-note')
                  .classList.contains(str)
              ).to.equal(true);
              expect(
                autocomplete
                  .querySelector('.input-note')
                  .classList.contains(str2)
              ).to.equal(true);

              done();
            }, 50);
          });

          it('Check options', function (done) {
            var obj = [
              {value: 'A', label: 'Option 1'},
              {value: 'B', label: 'Option 2'},
              {value: 'C', label: 'Option 1'},
              {value: 'D', label: 'Option 2'}
            ];
            autocomplete.options = obj;

            setTimeout(function () {
              expect(
                autocomplete.querySelectorAll('.options-list li').length
              ).to.equal(obj.length);

              done();
            }, 50);
          });

          it('Check placeholder', function (done) {
            var str = 'ciccio';
            autocomplete.placeholder = str;

            setTimeout(function () {
              expect(
                autocomplete.querySelector('input-clab').placeholder
              ).to.equal(autocomplete.placeholder);

              done();
            }, 50);
          });

          it('Check disabled', function (done) {
            autocomplete.disabled = true;

            setTimeout(function () {
              expect(
                autocomplete.querySelector('input-clab').disabled
              ).to.equal(true);

              done();
            }, 50);
          });

          it('Check hideHints', function (done) {
            var evt = new Event('keyup');
            autocomplete.hideHints = true;
            autocomplete.inputString = 'opt';
            autocomplete.options = [
              {value: 'A', label: 'Option 1'},
              {value: 'B', label: 'Option 2'},
              {value: 'C', label: 'Option 1'},
              {value: 'D', label: 'Option 2'}
            ];
            autocomplete.querySelector('input-clab').dispatchEvent(evt);

            setTimeout(function () {
              expect(
                autocomplete
                  .querySelector('.options-list')
                  .classList.contains('active')
              ).to.equal(false);

              done();
            }, 50);
          });

          it('Check maxInView', function (done) {
            var evt = new Event('keyup');
            autocomplete.maxInView = 10;
            autocomplete.inputString = 'opt';
            autocomplete.options = [
              {value: 'A', label: 'Option 1'},
              {value: 'B', label: 'Option 2'},
              {value: 'C', label: 'Option 1'},
              {value: 'D', label: 'Option 2'}
            ];
            autocomplete.querySelector('input-clab').dispatchEvent(evt);

            setTimeout(function () {
              expect(
                autocomplete.querySelector('.options-list').clientHeight
              ).to.be.below(autocomplete.liHeight * autocomplete.maxInView + 1);

              done();
            }, 50);
          });

          it('Check minChar', function (done) {
            var evt = new Event('keyup');
            var typing = false;
            var listen = function () {
              typing = true;
            };
            autocomplete.minChar = 2;
            autocomplete.options = [
              {value: 'A', label: 'Option 1'},
              {value: 'B', label: 'Option 2'},
              {value: 'C', label: 'Option 1'},
              {value: 'D', label: 'Option 2'}
            ];
            autocomplete.inputString = 'op';
            autocomplete.querySelector('input-clab').dispatchEvent(evt);

            setTimeout(function () {
              autocomplete.addEventListener('typing', listen);
              expect(typing).to.equal(false);

              autocomplete.inputString = 'opt';
              autocomplete.querySelector('input-clab').dispatchEvent(evt);

              setTimeout(function () {
                expect(typing).to.equal(true);

                done();
              }, 100);
            }, 100);
          });
        });
      });
    </script>
  </body>
</html>


text:
import pytest

from appname.models import db, User

create_user = False

@pytest.mark.usefixtures("testapp")
class TestModels:
    def test_user_save(self, testapp):
        """ Test Saving the user model to the database """

        admin = User('admin', 'supersafepassword')
        db.session.add(admin)
        db.session.commit()

        user = User.query.filter_by(username="admin").first()
        assert user is not None

    def test_user_password(self, testapp):
        """ Test password hashing and checking """

        admin = User('admin', 'supersafepassword')

        assert admin.username == 'admin'
        assert admin.check_password('supersafepassword')


text:
class DatabaseInfo;
class OilTest : public FileSpawningTestCase
{
    Q_OBJECT

    DatabaseInfo dbinfo();
    QStringList filesToClean() const;

private slots:
    void testConstruction();
    void testStaticOil();
};


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Contributor do
  describe '#merge' do
    before do
      delete_everything

      @contributor = Contributor.make(
        :login => '',
        :contributions => [
          {
            'project'     => 123,
            'owner'       => true,
          },
          {
            'project'     => 321,
            'commits'     => 12,
            'started_at'  => 'January 1 2008',
            'stopped_at'  => 'January 1 2010'
          }
        ]
      )
    end

    describe 'with an existing contributor' do
      before do
        Contributor.make(
          :name => 'Alice',
          :login => 'al1ce',
          :contributions => [
            {
              'project' =>    321,
              'owner' =>      true,
              'commits' =>    3,
              'started_at' => 'January 1 2009'
            }
          ]
        )

        @contributor.merge 'al1ce'
        @merged_contributor = Contributor.find_by_login('al1ce')
      end

      it 'should delete the contributor' do
        Contributor.find(@contributor.id).should be_nil
      end

      it 'should add the contributions to the leading contributor' do
        @merged_contributor.contributions.length.should == 2
      end

      it 'should merge existing contributions' do
        contribution = @merged_contributor.contributions.last
        contribution['commits'].should_not be_nil
        contribution['started_at'].should_not be_nil
        contribution['stopped_at'].should_not be_nil
      end

      it 'should add up the commit count' do
        contribution = @merged_contributor.contributions.last
        contribution['commits'].should == 15
      end
    end

    describe 'with a contributor that does not exist yet' do
      before do
        @contributor.merge 'al1ce'
      end
      it 'should not delete the contributor' do
        contributor = Contributor.find(@contributor.id)
        contributor.should_not be_nil
        contributor.should be_instance_of Contributor
      end

      it 'should add the login' do
        contributor = Contributor.find(@contributor.id)
        contributor.login.should == 'al1ce'
      end
    end
  end
end


text:
layout:     page
title:      "Managing Your Notifications"
breadcrumb: "GitHub Notifications"
author:
status:
category:
contenttype:
tags:       Managing, Notifications, GitHub
---

{% include toc.html %}

## Introduction

GitHub provides notifications for changes to repositories which you are interested in.
These notifications are displayed on your GitHub page and may also be sent via email.

This section is intended to help you manage the volume of this information.

## Prerequisites

* GAIG GitHub account

## A strategy for cutting down the noise
By default the option to be notified for changes to any repository that you have access to is selected by default.
Unfortunately this results in a lot of notification traffic, including notifications from every single developer's forks.

Here's a strategy to narrow down the notification traffic that might work for you:

### Specify how you want to be notified about GitHub activity
 1. Login to github.gaig.com

 2. Click on your user Icon and select Settings
   ![](images/settingsNotification.png){: .image}

 3. Go to Notification Center
     ![](images/howYouReceiveNotifications.png){: .image}

 4. In "How you receive notifications", toggle off "Automatically watch repositories"
         ![](images/turnOffAutomaticWatching.png){: .image}

 5. Toggle email and web notifications to your preferences:
     a. **Participating** - for notifying when you are/have been mentioned (ie @jkohl2)
     b. **Watching** - for when any repositories of interest change

### Narrow down the Repositories
 1. From the same Notification Center, Click on the "repositories you're watching" link:
    ![](images/repositoriesWatchingLink.png){: .image}

 2. Select the Watching tab
    ![](images/watchedRepos.png){: .image}

 3. Click "Unwatch all"
     ![](images/unwatchAll.png){: .image}

 4. Now select the Repositories tab, and click on a link to a repository that you are interested in:
    ![](images/myRepositories.png){: .image}

 5. Click on the "Watch" button and select "Watching".
    ![](images/watchCubeResources.png){: .image}

 6. Repeat this for any other base repositories of interest:
   a. BUE/CubeU
   b. active sub-projects for n-cube or CUBE
   c. Team mate's forked repositories if you are directly collaborating with them

## Reduced Repository list
An additional benefit of reducing the list of repositories that you are watching includes
only getting those repositories that you are watching when you are creating a new project from version control,
rather than a list of every single person's forked repositories.

## Viewing Notifications
All the web notifications are easily found by clicking on the bell icon:
 ![](images/notificationCenter.png){: .image}

From there you can view unread notifications as well as view all notifications grouped by repository.
 ![](images/viewAllNotifications.png){: .image}

## Clearing Notifications
Generally a good thing to clear out the day's notifications once you've taken a quick look by marking all messages as read.
  ![](images/markAllAsRead.png){: .image}

## For Further Reading

* Links


text:
<?php
/* In this file we define default values for every valid param to have a value if we don't get one from URL.
 */

// Defining default values.
var $defaults = Array(
  "section" => "blog",
  "style" => []
  );

/**
 * Returns the default value for a param.
 * @param $param The parameter
 * @return
 */
function defaultParam($param){
  return $defaults[$param];
}


text:
package io.opencensus.trace;

import io.opencensus.common.Clock;
import io.opencensus.internal.DefaultVisibilityForTesting;
import io.opencensus.internal.Provider;
import io.opencensus.trace.config.TraceConfig;
import io.opencensus.trace.export.ExportComponent;
import io.opencensus.trace.propagation.PropagationComponent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;

/**
 * Class that manages a global instance of the {@link TraceComponent}.
 *
 * @since 0.5
 */
public final class Tracing {

  private static final Logger logger = Logger.getLogger(Tracing.class.getName());
  private static final TraceComponent traceComponent =
      loadTraceComponent(TraceComponent.class.getClassLoader());

  /**
   * Returns the global {@link Tracer}.
   *
   * @return the global {@code Tracer}.
   * @since 0.5
   */
  public static Tracer getTracer() {
    return traceComponent.getTracer();
  }

  /**
   * Returns the global {@link PropagationComponent}.
   *
   * @return the global {@code PropagationComponent}.
   * @since 0.5
   */
  public static PropagationComponent getPropagationComponent() {
    return traceComponent.getPropagationComponent();
  }

  /**
   * Returns the global {@link Clock}.
   *
   * @return the global {@code Clock}.
   * @since 0.5
   */
  public static Clock getClock() {
    return traceComponent.getClock();
  }

  /**
   * Returns the global {@link ExportComponent}.
   *
   * @return the global {@code ExportComponent}.
   * @since 0.5
   */
  public static ExportComponent getExportComponent() {
    return traceComponent.getExportComponent();
  }

  /**
   * Returns the global {@link TraceConfig}.
   *
   * @return the global {@code TraceConfig}.
   * @since 0.5
   */
  public static TraceConfig getTraceConfig() {
    return traceComponent.getTraceConfig();
  }

  // Any provider that may be used for TraceComponent can be added here.
  @DefaultVisibilityForTesting
  static TraceComponent loadTraceComponent(@Nullable ClassLoader classLoader) {
    try {
      // Call Class.forName with literal string name of the class to help shading tools.
      return Provider.createInstance(
          Class.forName(
              "io.opentelemetry.opencensusshim.OpenTelemetryTraceComponentImpl",
              /*initialize=*/ true,
              classLoader),
          TraceComponent.class);
    } catch (ClassNotFoundException e) {
      logger.log(
          Level.FINE,
          "Couldn't load full implementation for OpenTelemetry TraceComponent, now trying to load "
              + "original implementation.",
          e);
    }
    try {
      // Call Class.forName with literal string name of the class to help shading tools.
      return Provider.createInstance(
          Class.forName(
              "io.opencensus.impl.trace.TraceComponentImpl", /*initialize=*/ true, classLoader),
          TraceComponent.class);
    } catch (ClassNotFoundException e) {
      logger.log(
          Level.FINE,
          "Couldn't load full implementation for TraceComponent, now trying to load lite "
              + "implementation.",
          e);
    }
    try {
      // Call Class.forName with literal string name of the class to help shading tools.
      return Provider.createInstance(
          Class.forName(
              "io.opencensus.impllite.trace.TraceComponentImplLite",
              /*initialize=*/ true,
              classLoader),
          TraceComponent.class);
    } catch (ClassNotFoundException e) {
      logger.log(
          Level.FINE,
          "Couldn't load lite implementation for TraceComponent, now using "
              + "default implementation for TraceComponent.",
          e);
    }
    return TraceComponent.newNoopTraceComponent();
  }

  // No instance of this class.
  private Tracing() {}
}


text:
require 'test_helper'

class FolderTest < Test::Unit::TestCase
  context "ActiveMailbox::Folder" do
    setup do
      ActiveMailbox::Fixtures.create!
      @mailbox = ActiveMailbox::Mailbox.find('15183332220')
      @folder  = @mailbox.inbox
    end

    teardown do
      ActiveMailbox::Fixtures.destroy!
    end

    should "raise FolderNotFound with an invalid path" do
      assert_raise ActiveMailbox::Errors::FolderNotFound do
        ActiveMailbox::Folder.new('i am not real!', @mailbox)
      end
    end

    context "instance" do
      should "yield an array of Message objects" do
        assert @folder.messages.is_a?(Array)
        assert @folder.messages.first.is_a?(ActiveMailbox::Message)
      end

      should "destroy itself" do
        path = @folder.path
        @folder.destroy!
        assert File.exists?(path) == false
      end

      should "sort and rename messages by filename" do
        messages = @folder.messages.map(&:name)
        assert messages.size == @folder.size

        ActiveMailbox::Fixtures.simulate_unordered(@folder)
        assert messages.size > @folder.size

        names = messages.map { |m| "msg%04d" % m.match(/([0-9]{4})/)[1].to_i }
        check = (0..messages.size - 1).map { |i| "msg%04d" % i }
        assert_same_elements names, check
      end

      should "clean ghost messages" do
        ActiveMailbox::Fixtures.simulate_ghosts(@folder)
        count = @folder.size
        @folder.clean_ghosts!
        assert count > @folder.size
      end

      should "purge all messages" do
        @folder.purge!
        assert @folder.size == 0
      end

      should "clean stale messages" do
        count = @folder.size
        @folder.clean_stale!
        assert @folder.size < count
      end

      should "be compared to another instance by path" do
        mailbox = ActiveMailbox::Mailbox.find(@mailbox.mailbox)
        folder = ActiveMailbox::Folder.new(@folder.path, mailbox)
        assert folder == @folder
      end
    end
  end
end


text:
<!doctype html>

    <title>Code coverage report for lib/string.js</title>
    <meta charset="utf-8">

    <link rel="stylesheet" href="../prettify.css">

Code coverage report for lib/string.js

        Statements: 96.88% (31 / 32)

        Branches: 87.5% (7 / 8)

        Functions: 100% (13 / 13)

        Lines: 96.88% (31 / 32)

        Ignored: none

All files » lib/ » string.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150

1

1
2
2
16

2

1
1

1
1

1
1

1
1

1
1
2

1
2
4

1
1
1

1
6
1

5

1
4

4
18

/**
 * String utility module.
 * @module pudding/string
 * @author Taka Okunishi
 */
"use strict";

/**
 * String regex patterns.
 * @private
 * @type {object}
 */
var PATTERNS = {
    ZENKAKU: /[!-~]/g,
    HANKAKU: /[\!-\~]/g,
    HIRAGANA: /[ぁ-ん]/g,
    KATAKANA: /[ァ-ン]/g
};

/**
 * Pad zero for string.
 * @memberof module:pudding/string
 * @function padZero
 * @param {string|number} number - Numeric string to pad.
 * @param {number} digit - Digit count for padded.
 * @returns {string} - Padded numeric string.
 */
exports.padZero = function (number, digit) {
    var result = String(number);
    while (result.length < digit) {
        result = "0" + result;
    }
    return result;
};

/**
 * Convert string to japanese hira-gana.
 * @memberof module:pudding/string
 * @function toHiragana
 * @param {string} str - String to convert.
 * @returns {string} - Converted string.
 */
exports.toHiragana = function (str) {
    return exports._slideCharCodes(str, PATTERNS.KATAKANA, -0x60);
};

/**
 * Convert string to japanese kata-kana.
 * @memberof module:pudding/string
 * @function toKatakana
 * @param {string} str - String to convert.
 * @returns {string} - Converted string.
 */
exports.toKatakana = function (str) {
    return exports._slideCharCodes(str, PATTERNS.HIRAGANA, 0x60);
};

/**
 * Convert to japanese hankaku-string.
 * @memberof module:pudding/string
 * @function toHankaku
 * @param {string} str - string to convert.
 * @returns {string} - Converted string.
 */
exports.toHankaku = function (str) {
    return exports._slideCharCodes(str, PATTERNS.ZENKAKU, -0xFEE0);
};

/**
 * Convert to japanese zenkaku-string.
 * @memberof module:pudding/string
 * @function toZenkaku
 * @param {string} str - string to convert.
 * @returns {string} - Converted string.
 */
exports.toZenkaku = function (str) {
    return exports._slideCharCodes(str, PATTERNS.HANKAKU, +0xFEE0);
};

/**
 * Convert camels string to underscore joined string.
 * @memberof module:pudding/string
 * @function toUnderscore
 * @param {string} str - String to convert.
 * @returns {string} - Converted string.
 */
exports.toUnderscore = function (str) {
    return str && str.replace(/([A-Z])/g, function ($1) {
        return "_" + $1.toLowerCase();
    })
        .replace(/^_/, '');
};

/**
 * Convert to camel string.
 * @memberof module:pudding/string
 * @function toCamel
 * @param {string} str - String to convert.
 * @returns {string} - Converted string.
 */
exports.toCamel = function (str) {
    return  str && str.replace(/([_\-][a-z])/g, function ($1) {
        return $1.toUpperCase().replace(/[_\-]/, '');
    });
};

/**
 * Convert to pascal string;
 * @memberof module:pudding/string
 * @function toPascal
 * @param str
 * @returns {string|*}
 */
exports.toPascal = function (str) {
    var camelized = exports.toCamel(str);
    return exports.capitalize(camelized);
};

/**
 * Convert initial string to uppercase.
 * @memberof module:pudding/string
 * @function capitalize
 * @param {string} string - String to convert.
 * @returns {string} - converted string.
 */
exports.capitalize = function (string) {
    if (!string) {
        return string;
    }
    return string.substr(0, 1).toUpperCase() + string.substr(1);
};

/**
 * Slide char codes.
 * @param {string} str - String to convert.
 * @param {RegExp} pattern - Pattern to change char code.
 * @param {number} charCode - Char code to add.
 * @private
 */
exports._slideCharCodes = function (str, pattern, charCode) {
    Iif (!str) {
        return str;
    }
    return str.replace(pattern, function (s) {
        return String.fromCharCode(s.charCodeAt(0) + charCode);
    });
};

Generated by istanbul at Fri Oct 31 2014 08:34:54 GMT+0900 (JST)


text:
export const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT'

export function redirect(url: string): never {
  // eslint-disable-next-line no-throw-literal
  const error = new Error(REDIRECT_ERROR_CODE)
  ;(error as any).digest = REDIRECT_ERROR_CODE + ';' + url
  throw error
}


text:
<!DOCTYPE html>

 <meta charset="UTF-8">

<title>LoadCoilSetup—Wolfram Language Documentation</title>
<meta name="buildnumber" content="0000000" />
<meta name="historydata" content="{XX, , , }" />
<meta name="keywords" content="LoadCoilSetup" />

<meta name="description" content="LoadCoilSetup[file] load a very specific type of coil experiment, a dynmic scan with a setup of which the second dynamic is a noise measurement. The input file is the Nii file that conatins the individualy reconstruted coil images and the noise data. Internaly it uses CoilSNRCalc and SumOfSquares. Output is the coil data with coil noise data and snrmap based on the SumOfSquares addition, the SOS reconstruction and the SOS weights. {dataC, noiseC, sosC, snrC, sigmapC, weights, vox}." />

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<link rel="stylesheet" href="../css/reference.css" />

            <link rel="stylesheet" href="../css/clipboard.css" />

   Q M R I TOOLS PACKAGE SYMBOL

    Related Guides

      CoilTools

LoadCoilSetup

LoadCoilSetup[file]
load a very specific type of coil experiment, a dynmic scan with a setup of which the second dynamic is a noise measurement. The input file is the Nii file that conatins the individualy reconstruted coil images and the noise data. Internaly it uses CoilSNRCalc and SumOfSquares. Output is the coil data with coil noise data and snrmap based on the SumOfSquares addition, the SOS reconstruction and the SOS weights. {dataC, noiseC, sosC, snrC, sigmapC, weights, vox}.

Related GuidesRelated Guides

      CoilTools