/*
 *
 * Copyright 2018 gRPC authors.
 *
 * 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 channelz

import (
	"net"
	"sync"
	"sync/atomic"
	"time"

	"google.golang.org/grpc/connectivity"
	"google.golang.org/grpc/credentials"
)

// entry represents a node in the channelz database.
type entry interface {
	// addChild adds a child e, whose channelz id is id to child list
	addChild(id int64, e entry)
	// deleteChild deletes a child with channelz id to be id from child list
	deleteChild(id int64)
	// triggerDelete tries to delete self from channelz database. However, if child
	// list is not empty, then deletion from the database is on hold until the last
	// child is deleted from database.
	triggerDelete()
	// deleteSelfIfReady check whether triggerDelete() has been called before, and whether child
	// list is now empty. If both conditions are met, then delete self from database.
	deleteSelfIfReady()
	// getParentID returns parent ID of the entry. 0 value parent ID means no parent.
	getParentID() int64
}

// dummyEntry is a fake entry to handle entry not found case.
type dummyEntry struct {
	idNotFound int64
}

func (d *dummyEntry) addChild(id int64, e entry) {
	// Note: It is possible for a normal program to reach here under race condition.
	// For example, there could be a race between ClientConn.Close() info being propagated
	// to addrConn and http2Client. ClientConn.Close() cancel the context and result
	// in http2Client to error. The error info is then caught by transport monitor
	// and before addrConn.tearDown() is called in side ClientConn.Close(). Therefore,
	// the addrConn will create a new transport. And when registering the new transport in
	// channelz, its parent addrConn could have already been torn down and deleted
	// from channelz tracking, and thus reach the code here.
	logger.Infof("attempt to add child of type %T with id %d to a parent (id=%d) that doesn't currently exist", e, id, d.idNotFound)
}

func (d *dummyEntry) deleteChild(id int64) {
	// It is possible for a normal program to reach here under race condition.
	// Refer to the example described in addChild().
	logger.Infof("attempt to delete child with id %d from a parent (id=%d) that doesn't currently exist", id, d.idNotFound)
}

func (d *dummyEntry) triggerDelete() {
	logger.Warningf("attempt to delete an entry (id=%d) that doesn't currently exist", d.idNotFound)
}

func (*dummyEntry) deleteSelfIfReady() {
	// code should not reach here. deleteSelfIfReady is always called on an existing entry.
}

func (*dummyEntry) getParentID() int64 {
	return 0
}

// ChannelMetric defines the info channelz provides for a specific Channel, which
// includes ChannelInternalMetric and channelz-specific data, such as channelz id,
// child list, etc.
type ChannelMetric struct {
	// ID is the channelz id of this channel.
	ID int64
	// RefName is the human readable reference string of this channel.
	RefName string
	// ChannelData contains channel internal metric reported by the channel through
	// ChannelzMetric().
	ChannelData *ChannelInternalMetric
	// NestedChans tracks the nested channel type children of this channel in the format of
	// a map from nested channel channelz id to corresponding reference string.
	NestedChans map[int64]string
	// SubChans tracks the subchannel type children of this channel in the format of a
	// map from subchannel channelz id to corresponding reference string.
	SubChans map[int64]string
	// Sockets tracks the socket type children of this channel in the format of a map
	// from socket channelz id to corresponding reference string.
	// Note current grpc implementation doesn't allow channel having sockets directly,
	// therefore, this is field is unused.
	Sockets map[int64]string
	// Trace contains the most recent traced events.
	Trace *ChannelTrace
}

// SubChannelMetric defines the info channelz provides for a specific SubChannel,
// which includes ChannelInternalMetric and channelz-specific data, such as
// channelz id, child list, etc.
type SubChannelMetric struct {
	// ID is the channelz id of this subchannel.
	ID int64
	// RefName is the human readable reference string of this subchannel.
	RefName string
	// ChannelData contains subchannel internal metric reported by the subchannel
	// through ChannelzMetric().
	ChannelData *ChannelInternalMetric
	// NestedChans tracks the nested channel type children of this subchannel in the format of
	// a map from nested channel channelz id to corresponding reference string.
	// Note current grpc implementation doesn't allow subchannel to have nested channels
	// as children, therefore, this field is unused.
	NestedChans map[int64]string
	// SubChans tracks the subchannel type children of this subchannel in the format of a
	// map from subchannel channelz id to corresponding reference string.
	// Note current grpc implementation doesn't allow subchannel to have subchannels
	// as children, therefore, this field is unused.
	SubChans map[int64]string
	// Sockets tracks the socket type children of this subchannel in the format of a map
	// from socket channelz id to corresponding reference string.
	Sockets map[int64]string
	// Trace contains the most recent traced events.
	Trace *ChannelTrace
}

// ChannelInternalMetric defines the struct that the implementor of Channel interface
// should return from ChannelzMetric().
type ChannelInternalMetric struct {
	// current connectivity state of the channel.
	State connectivity.State
	// The target this channel originally tried to connect to.  May be absent
	Target string
	// The number of calls started on the channel.
	CallsStarted int64
	// The number of calls that have completed with an OK status.
	CallsSucceeded int64
	// The number of calls that have a completed with a non-OK status.
	CallsFailed int64
	// The last time a call was started on the channel.
	LastCallStartedTimestamp time.Time
}

// ChannelTrace stores traced events on a channel/subchannel and related info.
type ChannelTrace struct {
	// EventNum is the number of events that ever got traced (i.e. including those that have been deleted)
	EventNum int64
	// CreationTime is the creation time of the trace.
	CreationTime time.Time
	// Events stores the most recent trace events (up to $maxTraceEntry, newer event will overwrite the
	// oldest one)
	Events []*TraceEvent
}

// TraceEvent represent a single trace event
type TraceEvent struct {
	// Desc is a simple description of the trace event.
	Desc string
	// Severity states the severity of this trace event.
	Severity Severity
	// Timestamp is the event time.
	Timestamp time.Time
	// RefID is the id of the entity that gets referenced in the event. RefID is 0 if no other entity is
	// involved in this event.
	// e.g. SubChannel (id: 4[]) Created. --> RefID = 4, RefName = "" (inside [])
	RefID int64
	// RefName is the reference name for the entity that gets referenced in the event.
	RefName string
	// RefType indicates the referenced entity type, i.e Channel or SubChannel.
	RefType RefChannelType
}

// Channel is the interface that should be satisfied in order to be tracked by
// channelz as Channel or SubChannel.
type Channel interface {
	ChannelzMetric() *ChannelInternalMetric
}

type dummyChannel struct{}

func (d *dummyChannel) ChannelzMetric() *ChannelInternalMetric {
	return &ChannelInternalMetric{}
}

type channel struct {
	refName     string
	c           Channel
	closeCalled bool
	nestedChans map[int64]string
	subChans    map[int64]string
	id          int64
	pid         int64
	cm          *channelMap
	trace       *channelTrace
	// traceRefCount is the number of trace events that reference this channel.
	// Non-zero traceRefCount means the trace of this channel cannot be deleted.
	traceRefCount int32
}

func (c *channel) addChild(id int64, e entry) {
	switch v := e.(type) {
	case *subChannel:
		c.subChans[id] = v.refName
	case *channel:
		c.nestedChans[id] = v.refName
	default:
		logger.Errorf("cannot add a child (id = %d) of type %T to a channel", id, e)
	}
}

func (c *channel) deleteChild(id int64) {
	delete(c.subChans, id)
	delete(c.nestedChans, id)
	c.deleteSelfIfReady()
}

func (c *channel) triggerDelete() {
	c.closeCalled = true
	c.deleteSelfIfReady()
}

func (c *channel) getParentID() int64 {
	return c.pid
}

// deleteSelfFromTree tries to delete the channel from the channelz entry relation tree, which means
// deleting the channel reference from its parent's child list.
//
// In order for a channel to be deleted from the tree, it must meet the criteria that, removal of the
// corresponding grpc object has been invoked, and the channel does not have any children left.
//
// The returned boolean value indicates whether the channel has been successfully deleted from tree.
func (c *channel) deleteSelfFromTree() (deleted bool) {
	if !c.closeCalled || len(c.subChans)+len(c.nestedChans) != 0 {
		return false
	}
	// not top channel
	if c.pid != 0 {
		c.cm.findEntry(c.pid).deleteChild(c.id)
	}
	return true
}

// deleteSelfFromMap checks whether it is valid to delete the channel from the map, which means
// deleting the channel from channelz's tracking entirely. Users can no longer use id to query the
// channel, and its memory will be garbage collected.
//
// The trace reference count of the channel must be 0 in order to be deleted from the map. This is
// specified in the channel tracing gRFC that as long as some other trace has reference to an entity,
// the trace of the referenced entity must not be deleted. In order to release the resource allocated
// by grpc, the reference to the grpc object is reset to a dummy object.
//
// deleteSelfFromMap must be called after deleteSelfFromTree returns true.
//
// It returns a bool to indicate whether the channel can be safely deleted from map.
func (c *channel) deleteSelfFromMap() (delete bool) {
	if c.getTraceRefCount() != 0 {
		c.c = &dummyChannel{}
		return false
	}
	return true
}

// deleteSelfIfReady tries to delete the channel itself from the channelz database.
// The delete process includes two steps:
// 1. delete the channel from the entry relation tree, i.e. delete the channel reference from its
//    parent's child list.
// 2. delete the channel from the map, i.e. delete the channel entirely from channelz. Lookup by id
//    will return entry not found error.
func (c *channel) deleteSelfIfReady() {
	if !c.deleteSelfFromTree() {
		return
	}
	if !c.deleteSelfFromMap() {
		return
	}
	c.cm.deleteEntry(c.id)
	c.trace.clear()
}

func (c *channel) getChannelTrace() *channelTrace {
	return c.trace
}

func (c *channel) incrTraceRefCount() {
	atomic.AddInt32(&c.traceRefCount, 1)
}

func (c *channel) decrTraceRefCount() {
	atomic.AddInt32(&c.traceRefCount, -1)
}

func (c *channel) getTraceRefCount() int {
	i := atomic.LoadInt32(&c.traceRefCount)
	return int(i)
}

func (c *channel) getRefName() string {
	return c.refName
}

type subChannel struct {
	refName       string
	c             Channel
	closeCalled   bool
	sockets       map[int64]string
	id            int64
	pid           int64
	cm            *channelMap
	trace         *channelTrace
	traceRefCount int32
}

func (sc *subChannel) addChild(id int64, e entry) {
	if v, ok := e.(*normalSocket); ok {
		sc.sockets[id] = v.refName
	} else {
		logger.Errorf("cannot add a child (id = %d) of type %T to a subChannel", id, e)
	}
}

func (sc *subChannel) deleteChild(id int64) {
	delete(sc.sockets, id)
	sc.deleteSelfIfReady()
}

func (sc *subChannel) triggerDelete() {
	sc.closeCalled = true
	sc.deleteSelfIfReady()
}

func (sc *subChannel) getParentID() int64 {
	return sc.pid
}

// deleteSelfFromTree tries to delete the subchannel from the channelz entry relation tree, which
// means deleting the subchannel reference from its parent's child list.
//
// In order for a subchannel to be deleted from the tree, it must meet the criteria that, removal of
// the corresponding grpc object has been invoked, and the subchannel does not have any children left.
//
// The returned boolean value indicates whether the channel has been successfully deleted from tree.
func (sc *subChannel) deleteSelfFromTree() (deleted bool) {
	if !sc.closeCalled || len(sc.sockets) != 0 {
		return false
	}
	sc.cm.findEntry(sc.pid).deleteChild(sc.id)
	return true
}

// deleteSelfFromMap checks whether it is valid to delete the subchannel from the map, which means
// deleting the subchannel from channelz's tracking entirely. Users can no longer use id to query
// the subchannel, and its memory will be garbage collected.
//
// The trace reference count of the subchannel must be 0 in order to be deleted from the map. This is
// specified in the channel tracing gRFC that as long as some other trace has reference to an entity,
// the trace of the referenced entity must not be deleted. In order to release the resource allocated
// by grpc, the reference to the grpc object is reset to a dummy object.
//
// deleteSelfFromMap must be called after deleteSelfFromTree returns true.
//
// It returns a bool to indicate whether the channel can be safely deleted from map.
func (sc *subChannel) deleteSelfFromMap() (delete bool) {
	if sc.getTraceRefCount() != 0 {
		// free the grpc struct (i.e. addrConn)
		sc.c = &dummyChannel{}
		return false
	}
	return true
}

// deleteSelfIfReady tries to delete the subchannel itself from the channelz database.
// The delete process includes two steps:
// 1. delete the subchannel from the entry relation tree, i.e. delete the subchannel reference from
//    its parent's child list.
// 2. delete the subchannel from the map, i.e. delete the subchannel entirely from channelz. Lookup
//    by id will return entry not found error.
func (sc *subChannel) deleteSelfIfReady() {
	if !sc.deleteSelfFromTree() {
		return
	}
	if !sc.deleteSelfFromMap() {
		return
	}
	sc.cm.deleteEntry(sc.id)
	sc.trace.clear()
}

func (sc *subChannel) getChannelTrace() *channelTrace {
	return sc.trace
}

func (sc *subChannel) incrTraceRefCount() {
	atomic.AddInt32(&sc.traceRefCount, 1)
}

func (sc *subChannel) decrTraceRefCount() {
	atomic.AddInt32(&sc.traceRefCount, -1)
}

func (sc *subChannel) getTraceRefCount() int {
	i := atomic.LoadInt32(&sc.traceRefCount)
	return int(i)
}

func (sc *subChannel) getRefName() string {
	return sc.refName
}

// SocketMetric defines the info channelz provides for a specific Socket, which
// includes SocketInternalMetric and channelz-specific data, such as channelz id, etc.
type SocketMetric struct {
	// ID is the channelz id of this socket.
	ID int64
	// RefName is the human readable reference string of this socket.
	RefName string
	// SocketData contains socket internal metric reported by the socket through
	// ChannelzMetric().
	SocketData *SocketInternalMetric
}

// SocketInternalMetric defines the struct that the implementor of Socket interface
// should return from ChannelzMetric().
type SocketInternalMetric struct {
	// The number of streams that have been started.
	StreamsStarted int64
	// The number of streams that have ended successfully:
	// On client side, receiving frame with eos bit set.
	// On server side, sending frame with eos bit set.
	StreamsSucceeded int64
	// The number of streams that have ended unsuccessfully:
	// On client side, termination without receiving frame with eos bit set.
	// On server side, termination without sending frame with eos bit set.
	StreamsFailed int64
	// The number of messages successfully sent on this socket.
	MessagesSent     int64
	MessagesReceived int64
	// The number of keep alives sent.  This is typically implemented with HTTP/2
	// ping messages.
	KeepAlivesSent int64
	// The last time a stream was created by this endpoint.  Usually unset for
	// servers.
	LastLocalStreamCreatedTimestamp time.Time
	// The last time a stream was created by the remote endpoint.  Usually unset
	// for clients.
	LastRemoteStreamCreatedTimestamp time.Time
	// The last time a message was sent by this endpoint.
	LastMessageSentTimestamp time.Time
	// The last time a message was received by this endpoint.
	LastMessageReceivedTimestamp time.Time
	// The amount of window, granted to the local endpoint by the remote endpoint.
	// This may be slightly out of date due to network latency.  This does NOT
	// include stream level or TCP level flow control info.
	LocalFlowControlWindow int64
	// The amount of window, granted to the remote endpoint by the local endpoint.
	// This may be slightly out of date due to network latency.  This does NOT
	// include stream level or TCP level flow control info.
	RemoteFlowControlWindow int64
	// The locally bound address.
	LocalAddr net.Addr
	// The remote bound address.  May be absent.
	RemoteAddr net.Addr
	// Optional, represents the name of the remote endpoint, if different than
	// the original target name.
	RemoteName    string
	SocketOptions *SocketOptionData
	Security      credentials.ChannelzSecurityValue
}

// Socket is the interface that should be satisfied in order to be tracked by
// channelz as Socket.
type Socket interface {
	ChannelzMetric() *SocketInternalMetric
}

type listenSocket struct {
	refName string
	s       Socket
	id      int64
	pid     int64
	cm      *channelMap
}

func (ls *listenSocket) addChild(id int64, e entry) {
	logger.Errorf("cannot add a child (id = %d) of type %T to a listen socket", id, e)
}

func (ls *listenSocket) deleteChild(id int64) {
	logger.Errorf("cannot delete a child (id = %d) from a listen socket", id)
}

func (ls *listenSocket) triggerDelete() {
	ls.cm.deleteEntry(ls.id)
	ls.cm.findEntry(ls.pid).deleteChild(ls.id)
}

func (ls *listenSocket) deleteSelfIfReady() {
	logger.Errorf("cannot call deleteSelfIfReady on a listen socket")
}

func (ls *listenSocket) getParentID() int64 {
	return ls.pid
}

type normalSocket struct {
	refName string
	s       Socket
	id      int64
	pid     int64
	cm      *channelMap
}

func (ns *normalSocket) addChild(id int64, e entry) {
	logger.Errorf("cannot add a child (id = %d) of type %T to a normal socket", id, e)
}

func (ns *normalSocket) deleteChild(id int64) {
	logger.Errorf("cannot delete a child (id = %d) from a normal socket", id)
}

func (ns *normalSocket) triggerDelete() {
	ns.cm.deleteEntry(ns.id)
	ns.cm.findEntry(ns.pid).deleteChild(ns.id)
}

func (ns *normalSocket) deleteSelfIfReady() {
	logger.Errorf("cannot call deleteSelfIfReady on a normal socket")
}

func (ns *normalSocket) getParentID() int64 {
	return ns.pid
}

// ServerMetric defines the info channelz provides for a specific Server, which
// includes ServerInternalMetric and channelz-specific data, such as channelz id,
// child list, etc.
type ServerMetric struct {
	// ID is the channelz id of this server.
	ID int64
	// RefName is the human readable reference string of this server.
	RefName string
	// ServerData contains server internal metric reported by the server through
	// ChannelzMetric().
	ServerData *ServerInternalMetric
	// ListenSockets tracks the listener socket type children of this server in the
	// format of a map from socket channelz id to corresponding reference string.
	ListenSockets map[int64]string
}

// ServerInternalMetric defines the struct that the implementor of Server interface
// should return from ChannelzMetric().
type ServerInternalMetric struct {
	// The number of incoming calls started on the server.
	CallsStarted int64
	// The number of incoming calls that have completed with an OK status.
	CallsSucceeded int64
	// The number of incoming calls that have a completed with a non-OK status.
	CallsFailed int64
	// The last time a call was started on the server.
	LastCallStartedTimestamp time.Time
}

// Server is the interface to be satisfied in order to be tracked by channelz as
// Server.
type Server interface {
	ChannelzMetric() *ServerInternalMetric
}

type server struct {
	refName       string
	s             Server
	closeCalled   bool
	sockets       map[int64]string
	listenSockets map[int64]string
	id            int64
	cm            *channelMap
}

func (s *server) addChild(id int64, e entry) {
	switch v := e.(type) {
	case *normalSocket:
		s.sockets[id] = v.refName
	case *listenSocket:
		s.listenSockets[id] = v.refName
	default:
		logger.Errorf("cannot add a child (id = %d) of type %T to a server", id, e)
	}
}

func (s *server) deleteChild(id int64) {
	delete(s.sockets, id)
	delete(s.listenSockets, id)
	s.deleteSelfIfReady()
}

func (s *server) triggerDelete() {
	s.closeCalled = true
	s.deleteSelfIfReady()
}

func (s *server) deleteSelfIfReady() {
	if !s.closeCalled || len(s.sockets)+len(s.listenSockets) != 0 {
		return
	}
	s.cm.deleteEntry(s.id)
}

func (s *server) getParentID() int64 {
	return 0
}

type tracedChannel interface {
	getChannelTrace() *channelTrace
	incrTraceRefCount()
	decrTraceRefCount()
	getRefName() string
}

type channelTrace struct {
	cm          *channelMap
	createdTime time.Time
	eventCount  int64
	mu          sync.Mutex
	events      []*TraceEvent
}

func (c *channelTrace) append(e *TraceEvent) {
	c.mu.Lock()
	if len(c.events) == getMaxTraceEntry() {
		del := c.events[0]
		c.events = c.events[1:]
		if del.RefID != 0 {
			// start recursive cleanup in a goroutine to not block the call originated from grpc.
			go func() {
				// need to acquire c.cm.mu lock to call the unlocked attemptCleanup func.
				c.cm.mu.Lock()
				c.cm.decrTraceRefCount(del.RefID)
				c.cm.mu.Unlock()
			}()
		}
	}
	e.Timestamp = time.Now()
	c.events = append(c.events, e)
	c.eventCount++
	c.mu.Unlock()
}

func (c *channelTrace) clear() {
	c.mu.Lock()
	for _, e := range c.events {
		if e.RefID != 0 {
			// caller should have already held the c.cm.mu lock.
			c.cm.decrTraceRefCount(e.RefID)
		}
	}
	c.mu.Unlock()
}

// Severity is the severity level of a trace event.
// The canonical enumeration of all valid values is here:
// https://github.com/grpc/grpc-proto/blob/9b13d199cc0d4703c7ea26c9c330ba695866eb23/grpc/channelz/v1/channelz.proto#L126.
type Severity int

const (
	// CtUNKNOWN indicates unknown severity of a trace event.
	CtUNKNOWN Severity = iota
	// CtINFO indicates info level severity of a trace event.
	CtINFO
	// CtWarning indicates warning level severity of a trace event.
	CtWarning
	// CtError indicates error level severity of a trace event.
	CtError
)

// RefChannelType is the type of the entity being referenced in a trace event.
type RefChannelType int

const (
	// RefChannel indicates the referenced entity is a Channel.
	RefChannel RefChannelType = iota
	// RefSubChannel indicates the referenced entity is a SubChannel.
	RefSubChannel
)

func (c *channelTrace) dumpData() *ChannelTrace {
	c.mu.Lock()
	ct := &ChannelTrace{EventNum: c.eventCount, CreationTime: c.createdTime}
	ct.Events = c.events[:len(c.events)]
	c.mu.Unlock()
	return ct
}

{'repo_name': 'kubernetes-sigs/cri-tools', 'stars': '432', 'repo_language': 'Go', 'file_name': 'main_windows.go', 'mime_type': 'text/plain', 'hash': -6903387982477229521, 'source_dataset': 'data'}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Bonobo.Git.Server.Data.Update.Sqlite
{
    public class AddRepoPushColumn : IUpdateScript
    {
        public string Command
        {
            get
            {
                return string.Format("ALTER TABLE Repository ADD COLUMN [AllowAnonymousPush] INTEGER DEFAULT({0})", (int)RepositoryPushMode.Global);
            }
        }

        public string Precondition
        {
            get
            {
                return "SELECT Count([AllowAnonymousPush]) = -1 FROM Repository";
            }
        }

        public void CodeAction(BonoboGitServerContext context) { }

    }
}

{'repo_name': 'jakubgarfield/Bonobo-Git-Server', 'stars': '1591', 'repo_language': 'C#', 'file_name': 'UnityFilterAttributeFilterProvider.cs', 'mime_type': 'text/plain', 'hash': -1973560006891712920, 'source_dataset': 'data'}


#!/usr/bin/env bash

#
# dtb_list extracts the list of DTB files from BR2_LINUX_KERNEL_INTREE_DTS_NAME
# in ${BR_CONFIG}, then prints the corresponding list of file names for the
# genimage configuration file
#
dtb_list()
{
	local DTB_LIST="$(sed -n 's/^BR2_LINUX_KERNEL_INTREE_DTS_NAME="\([a-z0-9 \-]*\)"$/\1/p' ${BR2_CONFIG})"

	for dt in $DTB_LIST; do
		echo -n "\"$dt.dtb\", "
	done
}

#
# linux_image extracts the Linux image format from BR2_LINUX_KERNEL_UIMAGE in
# ${BR_CONFIG}, then prints the corresponding file name for the genimage
# configuration file
#
linux_image()
{
	if grep -Eq "^BR2_LINUX_KERNEL_UIMAGE=y$" ${BR2_CONFIG}; then
		echo "\"uImage\""
	else
		echo "\"zImage\""
	fi
}

genimage_type()
{
	if grep -Eq "^BR2_TARGET_UBOOT_SPL=y$" ${BR2_CONFIG}; then
		echo "genimage.cfg.template_spl"
	else
		echo "genimage.cfg.template"
	fi
}

main()
{
	local FILES="$(dtb_list) $(linux_image)"
	local GENIMAGE_CFG="$(mktemp --suffix genimage.cfg)"
	local GENIMAGE_TMP="${BUILD_DIR}/genimage.tmp"

	sed -e "s/%FILES%/${FILES}/" \
		board/freescale/common/imx/$(genimage_type) > ${GENIMAGE_CFG}

	rm -rf "${GENIMAGE_TMP}"

	genimage \
		--rootpath "${TARGET_DIR}" \
		--tmppath "${GENIMAGE_TMP}" \
		--inputpath "${BINARIES_DIR}" \
		--outputpath "${BINARIES_DIR}" \
		--config "${GENIMAGE_CFG}"

	rm -f ${GENIMAGE_CFG}

	exit $?
}

main $@

{'repo_name': 'gamaral/rpi-buildroot', 'stars': '548', 'repo_language': 'Makefile', 'file_name': 'linux-ext-aufs.mk', 'mime_type': 'text/plain', 'hash': -4492930944480812409, 'source_dataset': 'data'}


jsdom

A JavaScript implementation of the DOM and HTML standards

npm run convert-idl && git submodule update --init --recursive

jscs lib/ && jscs test/ && eslint . && eslint test/web-platform-tests/to-upstream --ext .html

git log --format="%aN <%aE>" | sort -f | uniq > AUTHORS.txt

{'repo_name': 'tartanguru/alexa-google-search', 'stars': '207', 'repo_language': 'JavaScript', 'file_name': 'SEARCH.txt', 'mime_type': 'text/plain', 'hash': -3083533490246475652, 'source_dataset': 'data'}


/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2008 University of Washington
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef ENCODE_DECODE_H
#define ENCODE_DECODE_H

#include <string>

namespace ns3 {

std::string BufferToString (uint8_t *buffer, uint32_t len);
bool StringToBuffer (std::string s, uint8_t *buffer, uint32_t *len);

} // namespace ns3

#endif /* ENCODE_DECODE_H */

{'repo_name': 'nyuwireless-unipd/ns3-mmwave', 'stars': '132', 'repo_language': 'C++', 'file_name': '_placeholder_', 'mime_type': 'text/plain', 'hash': 1209053298266738798, 'source_dataset': 'data'}


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Validate
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */

/**
 * @see Zend_Validate_Barcode_AdapterAbstract
 */
require_once 'Zend/Validate/Barcode/AdapterAbstract.php';

/**
 * @category   Zend
 * @package    Zend_Validate
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_Barcode_Ean12 extends Zend_Validate_Barcode_AdapterAbstract
{
    /**
     * Allowed barcode lengths
     * @var integer
     */
    protected $_length = 12;

    /**
     * Allowed barcode characters
     * @var string
     */
    protected $_characters = '0123456789';

    /**
     * Checksum function
     * @var string
     */
    protected $_checksum = '_gtin';
}

{'repo_name': 'omeka/Omeka', 'stars': '320', 'repo_language': 'PHP', 'file_name': 'jquery.nestedSortable.js', 'mime_type': 'text/plain', 'hash': -5590794556536643626, 'source_dataset': 'data'}


# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

import dns.rdtypes.mxbase

class AFSDB(dns.rdtypes.mxbase.UncompressedDowncasingMX):

    """AFSDB record

    @ivar subtype: the subtype value
    @type subtype: int
    @ivar hostname: the hostname name
    @type hostname: dns.name.Name object"""

    # Use the property mechanism to make "subtype" an alias for the
    # "preference" attribute, and "hostname" an alias for the "exchange"
    # attribute.
    #
    # This lets us inherit the UncompressedMX implementation but lets
    # the caller use appropriate attribute names for the rdata type.
    #
    # We probably lose some performance vs. a cut-and-paste
    # implementation, but this way we don't copy code, and that's
    # good.

    def get_subtype(self):
        return self.preference

    def set_subtype(self, subtype):
        self.preference = subtype

    subtype = property(get_subtype, set_subtype)

    def get_hostname(self):
        return self.exchange

    def set_hostname(self, hostname):
        self.exchange = hostname

    hostname = property(get_hostname, set_hostname)

{'repo_name': 'morpheus65535/bazarr', 'stars': '1024', 'repo_language': 'Python', 'file_name': 'movies.html', 'mime_type': 'text/html', 'hash': 6113159143991144603, 'source_dataset': 'data'}


// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("go", function(config) {
  var indentUnit = config.indentUnit;

  var keywords = {
    "break":true, "case":true, "chan":true, "const":true, "continue":true,
    "default":true, "defer":true, "else":true, "fallthrough":true, "for":true,
    "func":true, "go":true, "goto":true, "if":true, "import":true,
    "interface":true, "map":true, "package":true, "range":true, "return":true,
    "select":true, "struct":true, "switch":true, "type":true, "var":true,
    "bool":true, "byte":true, "complex64":true, "complex128":true,
    "float32":true, "float64":true, "int8":true, "int16":true, "int32":true,
    "int64":true, "string":true, "uint8":true, "uint16":true, "uint32":true,
    "uint64":true, "int":true, "uint":true, "uintptr":true, "error": true,
    "rune":true
  };

  var atoms = {
    "true":true, "false":true, "iota":true, "nil":true, "append":true,
    "cap":true, "close":true, "complex":true, "copy":true, "delete":true, "imag":true,
    "len":true, "make":true, "new":true, "panic":true, "print":true,
    "println":true, "real":true, "recover":true
  };

  var isOperatorChar = /[+\-*&^%:=<>!|\/]/;

  var curPunc;

  function tokenBase(stream, state) {
    var ch = stream.next();
    if (ch == '"' || ch == "'" || ch == "`") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    }
    if (/[\d\.]/.test(ch)) {
      if (ch == ".") {
        stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/);
      } else if (ch == "0") {
        stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);
      } else {
        stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/);
      }
      return "number";
    }
    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
      curPunc = ch;
      return null;
    }
    if (ch == "/") {
      if (stream.eat("*")) {
        state.tokenize = tokenComment;
        return tokenComment(stream, state);
      }
      if (stream.eat("/")) {
        stream.skipToEnd();
        return "comment";
      }
    }
    if (isOperatorChar.test(ch)) {
      stream.eatWhile(isOperatorChar);
      return "operator";
    }
    stream.eatWhile(/[\w\$_\xa1-\uffff]/);
    var cur = stream.current();
    if (keywords.propertyIsEnumerable(cur)) {
      if (cur == "case" || cur == "default") curPunc = "case";
      return "keyword";
    }
    if (atoms.propertyIsEnumerable(cur)) return "atom";
    return "variable";
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next, end = false;
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) {end = true; break;}
        escaped = !escaped && quote != "`" && next == "\\";
      }
      if (end || !(escaped || quote == "`"))
        state.tokenize = tokenBase;
      return "string";
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == "/" && maybeEnd) {
        state.tokenize = tokenBase;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return "comment";
  }

  function Context(indented, column, type, align, prev) {
    this.indented = indented;
    this.column = column;
    this.type = type;
    this.align = align;
    this.prev = prev;
  }
  function pushContext(state, col, type) {
    return state.context = new Context(state.indented, col, type, null, state.context);
  }
  function popContext(state) {
    if (!state.context.prev) return;
    var t = state.context.type;
    if (t == ")" || t == "]" || t == "}")
      state.indented = state.context.indented;
    return state.context = state.context.prev;
  }

  // Interface

  return {
    startState: function(basecolumn) {
      return {
        tokenize: null,
        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
        indented: 0,
        startOfLine: true
      };
    },

    token: function(stream, state) {
      var ctx = state.context;
      if (stream.sol()) {
        if (ctx.align == null) ctx.align = false;
        state.indented = stream.indentation();
        state.startOfLine = true;
        if (ctx.type == "case") ctx.type = "}";
      }
      if (stream.eatSpace()) return null;
      curPunc = null;
      var style = (state.tokenize || tokenBase)(stream, state);
      if (style == "comment") return style;
      if (ctx.align == null) ctx.align = true;

      if (curPunc == "{") pushContext(state, stream.column(), "}");
      else if (curPunc == "[") pushContext(state, stream.column(), "]");
      else if (curPunc == "(") pushContext(state, stream.column(), ")");
      else if (curPunc == "case") ctx.type = "case";
      else if (curPunc == "}" && ctx.type == "}") popContext(state);
      else if (curPunc == ctx.type) popContext(state);
      state.startOfLine = false;
      return style;
    },

    indent: function(state, textAfter) {
      if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
      if (ctx.type == "case" && /^(?:case|default)\b/.test(textAfter)) {
        state.context.type = "}";
        return ctx.indented;
      }
      var closing = firstChar == ctx.type;
      if (ctx.align) return ctx.column + (closing ? 0 : 1);
      else return ctx.indented + (closing ? 0 : indentUnit);
    },

    electricChars: "{}):",
    closeBrackets: "()[]{}''\"\"``",
    fold: "brace",
    blockCommentStart: "/*",
    blockCommentEnd: "*/",
    lineComment: "//"
  };
});

CodeMirror.defineMIME("text/x-go", "go");

});

{'repo_name': 'formtools/core', 'stars': '139', 'repo_language': 'PHP', 'file_name': 'nightwatch.json', 'mime_type': 'text/plain', 'hash': 7528481163741818153, 'source_dataset': 'data'}


//
//     Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun  9 2015 22:53:21).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//

#import "IBaseTableViewController.h"

#import "NSOutlineViewDelegate-Protocol.h"

@class NSString, TOutlineViewDataSource;

@interface TOutlineViewController : IBaseTableViewController <NSOutlineViewDelegate>
{
}

- (void)outlineViewItemDidExpand:(id)arg1;
- (void)outlineViewItemDidCollapse:(id)arg1;
- (id)outlineView:(id)arg1 selectionIndexesForProposedSelection:(id)arg2;
- (void)setView:(id)arg1;
- (id)outlineViewNoLoad;
- (id)outlineView;
@property(readonly, retain) TOutlineViewDataSource *dataSource; // @dynamic dataSource;
- (Class)dataSourceClass;
- (void)dealloc;
- (void)viewLoaded;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end

{'repo_name': 'w0lfschild/macOS_headers', 'stars': '304', 'repo_language': 'None', 'file_name': 'NSTextFinderBarContainer-Protocol.h', 'mime_type': 'text/x-objective-c', 'hash': -3028255758836234730, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: 7191a70dcf4959f43961fa78e05484a0
timeCreated: 1455140057
licenseType: Free
MonoImporter:
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'CragonGame/CasinosClient', 'stars': '194', 'repo_language': 'C#', 'file_name': 'org.eclipse.jdt.core.prefs', 'mime_type': 'text/plain', 'hash': 1412170837261726432, 'source_dataset': 'data'}


/*
  ZynAddSubFX - a software synthesizer

  Bank.cpp - Instrument Bank
  Copyright (C) 2002-2005 Nasca Octavian Paul
  Copyright (C) 2010-2010 Mark McCurry
  Author: Nasca Octavian Paul
          Mark McCurry

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.
*/

#include "Bank.h"
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <dirent.h>
#include <sys/stat.h>
#include <algorithm>

#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

#include "Config.h"
#include "Util.h"
#include "Part.h"
#include "BankDb.h"
#ifdef WIN32
#include <windows.h>
#endif

#ifdef __APPLE__
#include <dlfcn.h>

static const char* my_dylib_path () {
    static Dl_info info;
    if (dladdr((const void*) &my_dylib_path, &info)) {
        return info.dli_fname;
    }
    return NULL;
}
#endif

using namespace std;

namespace zyn {

static const char* INSTRUMENT_EXTENSION = ".xiz";

//if this file exists into a directory, this make the directory to be considered as a bank, even if it not contains a instrument file
const char* FORCE_BANK_DIR_FILE = ".bankdir";

Bank::Bank(Config *config)
    :bankpos(0), defaultinsname(" "), config(config),
    db(new BankDb), bank_msb(0), bank_lsb(0)
{
    clearbank();
    bankfiletitle = dirname;
    rescanforbanks();
    loadbank(config->cfg.currentBankDir);

    for(unsigned i=0; i<banks.size(); ++i) {
        if(banks[i].dir == config->cfg.currentBankDir) {
            bankpos = i;
            break;
        }
    }
}

Bank::~Bank()
{
    clearbank();
    delete db;
}

/*
 * Get the name of an instrument from the bank
 */
string Bank::getname(unsigned int ninstrument)
{
    if(emptyslot(ninstrument))
        return defaultinsname;
    return ins[ninstrument].name;
}

/*
 * Get the numbered name of an instrument from the bank
 */
string Bank::getnamenumbered(unsigned int ninstrument)
{
    if(emptyslot(ninstrument))
        return defaultinsname;

    return stringFrom(ninstrument + 1) + ". " + getname(ninstrument);
}

/*
 * Changes the name of an instrument (and the filename)
 */
int Bank::setname(unsigned int ninstrument, const string &newname, int newslot)
{
    if(emptyslot(ninstrument))
        return 0;

    string newfilename;
    char   tmpfilename[100 + 1];
    tmpfilename[100] = 0;

    if(newslot >= 0)
        snprintf(tmpfilename, 100, "%4d-%s", newslot + 1, newname.c_str());
    else
        snprintf(tmpfilename, 100, "%4d-%s", ninstrument + 1, newname.c_str());

    //add the zeroes at the start of filename
    for(int i = 0; i < 4; ++i)
        if(tmpfilename[i] == ' ')
            tmpfilename[i] = '0';

    newfilename = dirname + legalizeFilename(tmpfilename) + ".xiz";

    int err = rename(ins[ninstrument].filename.c_str(), newfilename.c_str());
    if(err)
        return err;

    ins[ninstrument].filename = newfilename;
    ins[ninstrument].name     = newname;
    return err;
}

/*
 * Check if there is no instrument on a slot from the bank
 */
bool Bank::emptyslot(unsigned int ninstrument)
{
    if(ninstrument >= BANK_SIZE)
        return true;
    if(ins[ninstrument].filename.empty())
        return true;

    return false;
}

/*
 * Removes the instrument from the bank
 */
int Bank::clearslot(unsigned int ninstrument)
{
    if(emptyslot(ninstrument))
        return 0;

    //no error when no file
    FILE *f = fopen(ins[ninstrument].filename.c_str(), "r");
    if(!f)
        return 0;
    fclose(f);

    int err = remove(ins[ninstrument].filename.c_str());
    if(!err)
        deletefrombank(ninstrument);
    return err;
}

/*
 * Save the instrument to a slot
 */
int Bank::savetoslot(unsigned int ninstrument, Part *part)
{
    int err = clearslot(ninstrument);
    if(err)
        return err;

    const int maxfilename = 200;
    char      tmpfilename[maxfilename + 20];
    ZERO(tmpfilename, maxfilename + 20);

    snprintf(tmpfilename,
             maxfilename,
             "%04d-%s",
             ninstrument + 1,
             (char *)part->Pname);

    string filename = dirname + '/' + legalizeFilename(tmpfilename) + ".xiz";

    FILE *f = fopen(filename.c_str(), "r");
    if(f) {
        fclose(f);

        err = remove(filename.c_str());
        if(err)
            return err;
    }

    err = part->saveXML(filename.c_str());
    if(err)
        return err;
    addtobank(ninstrument, legalizeFilename(tmpfilename) + ".xiz",
              (char *) part->Pname);
    return 0;
}

/*
 * Loads the instrument from the bank
 */
int Bank::loadfromslot(unsigned int ninstrument, Part *part)
{
    if(emptyslot(ninstrument))
        return 0;

    part->AllNotesOff();
    part->defaultsinstrument();

    part->loadXMLinstrument(ins[ninstrument].filename.c_str());
    return 0;
}

/*
 * Makes current a bank directory
 */
int Bank::loadbank(string bankdirname)
{
    normalizedirsuffix(bankdirname);
    DIR *dir = opendir(bankdirname.c_str());
    clearbank();

    if(dir == NULL)
        return -1;

    //set msb when possible
    bank_msb = 0;
    for(unsigned i=0; i<banks.size(); i++)
        if(banks[i].dir == bankdirname)
            bank_msb = i;

    dirname = bankdirname;

    bankfiletitle = dirname;

    struct dirent *fn;

    while((fn = readdir(dir))) {
        const char *filename = fn->d_name;

        //check for extension
        if(strstr(filename, INSTRUMENT_EXTENSION) == NULL)
            continue;

        //verify if the name is like this NNNN-name (where N is a digit)
        int no = 0;
        unsigned int startname = 0;

        for(unsigned int i = 0; i < 4; ++i) {
            if(strlen(filename) <= i)
                break;

            if((filename[i] >= '0') && (filename[i] <= '9')) {
                no = no * 10 + (filename[i] - '0');
                startname++;
            }
        }

        if((startname + 1) < strlen(filename))
            startname++;  //to take out the "-"

        string name = filename;

        //remove the file extension
        for(int i = name.size() - 1; i >= 2; i--)
            if(name[i] == '.') {
                name = name.substr(0, i);
                break;
            }

        if(no != 0) //the instrument position in the bank is found
            addtobank(no - 1, filename, name.substr(startname));
        else
            addtobank(-1, filename, name);
    }

    closedir(dir);

    if(!dirname.empty())
        config->cfg.currentBankDir = dirname;

    return 0;
}

/*
 * Makes a new bank, put it on a file and makes it current bank
 */
int Bank::newbank(string newbankdirname)
{
    string bankdir;
    bankdir = config->cfg.bankRootDirList[0];

    expanddirname(bankdir);
    normalizedirsuffix(bankdir);

    bankdir += newbankdirname;
#ifdef _WIN32
    if(mkdir(bankdir.c_str()) < 0)
#else
    if(mkdir(bankdir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0)
#endif
        return -1;

    const string tmpfilename = bankdir + '/' + FORCE_BANK_DIR_FILE;

    FILE *tmpfile = fopen(tmpfilename.c_str(), "w+");
    fclose(tmpfile);

    return loadbank(bankdir);
}

/*
 * Check if the bank is locked (i.e. the file opened was readonly)
 */
int Bank::locked()
{
    //XXX Fixme
    return dirname.empty();
}

/*
 * Swaps a slot with another
 */
int Bank::swapslot(unsigned int n1, unsigned int n2)
{
    int err = 0;
    if((n1 == n2) || (locked()))
        return 0;
    if(emptyslot(n1) && (emptyslot(n2)))
        return 0;
    if(emptyslot(n1)) //change n1 to n2 in order to make
        swap(n1, n2);

    if(emptyslot(n2)) { //this is just a movement from slot1 to slot2
        err |= setname(n1, getname(n1), n2);
        if(err)
            return err;
        ins[n2] = ins[n1];
        ins[n1] = ins_t();
    }
    else {  //if both slots are used
        if(ins[n1].name == ins[n2].name) //change the name of the second instrument if the name are equal
            ins[n2].name += "2";

        err |= setname(n1, getname(n1), n2);
        err |= setname(n2, getname(n2), n1);
        if(err)
            return err;
        swap(ins[n2], ins[n1]);
    }
    return err;
}

bool Bank::bankstruct::operator<(const bankstruct &b) const
{
    return name < b.name;
}

/*
 * Re-scan for directories containing instrument banks
 */

void Bank::rescanforbanks()
{
    db->clear();
    //remove old banks
    banks.clear();

    for(int i = 0; i < MAX_BANK_ROOT_DIRS; ++i)
        if(!config->cfg.bankRootDirList[i].empty())
            scanrootdir(config->cfg.bankRootDirList[i]);
#ifdef WIN32
    {
        //Search the VST Directory for banks/preset/etc
        char path[1024];
        GetModuleFileName(GetModuleHandle("ZynAddSubFX.dll"), path, sizeof(path));
        if(strstr(path, "ZynAddSubFX.dll")) {
            strstr(path, "ZynAddSubFX.dll")[0] = 0;
            strcat(path, "banks");
            scanrootdir(path);
        }
    }
#endif
#ifdef __APPLE__
   {
        const char* path = my_dylib_path ();
        if (path && strstr(path, "ZynAddSubFX.dylib") && strlen (path) < 1000) {
            char tmp[1024];
            strcpy (tmp, path);
            strstr (tmp, "ZynAddSubFX.dylib")[0] = 0; // LV2
            strcat (tmp, "banks");
            scanrootdir(tmp);
            strcpy (tmp, path);
            strstr (tmp, "ZynAddSubFX.dylib")[0] = 0;
            strcat (tmp, "../Resources/banks"); // VST
            scanrootdir(tmp);
        }
   }
#endif

    //sort the banks
    sort(banks.begin(), banks.end());

    for(int i = 0; i < (int) banks.size(); ++i)
        db->addBankDir(banks[i].dir);

    //remove duplicate bank names
    for(int j = 0; j < (int) banks.size() - 1; ++j) {
        int dupl = 0;
        for(int i = j + 1; i < (int) banks.size(); ++i) {
            if(banks[i].name == banks[j].name) {
                //add a [1] to the first bankname and [n] to others
                banks[i].name = banks[i].name + '['
                                + stringFrom(dupl + 2) + ']';
                dupl++;
            }
        }
        if(dupl != 0)
            banks[j].name += "[1]";
        if(dupl)
            j += dupl;
    }
    db->scanBanks();
}

void Bank::setMsb(uint8_t msb)
{
    if(msb < banks.size() && banks[msb].dir != bankfiletitle)
        loadbank(banks[msb].dir);
}

void Bank::setLsb(uint8_t lsb)
{
    //should only involve values of 0/1 for the time being...
    bank_lsb = limit<uint8_t>(lsb,0,1);
}

// private stuff

void Bank::scanrootdir(string rootdir)
{
    expanddirname(rootdir);

    DIR *dir = opendir(rootdir.c_str());
    if(dir == NULL)
        return;

    bankstruct bank;

    const char *separator = "/";
    if(rootdir.size()) {
        char tmp = rootdir[rootdir.size() - 1];
        if((tmp == '/') || (tmp == '\\'))
            separator = "";
    }

    struct dirent *fn;
    while((fn = readdir(dir))) {
        const char *dirname = fn->d_name;
        if(dirname[0] == '.')
            continue;

        bank.dir  = rootdir + separator + dirname + '/';
        bank.name = dirname;
        //find out if the directory contains at least 1 instrument
        bool isbank = false;

        DIR *d = opendir(bank.dir.c_str());
        if(d == NULL)
            continue;

        struct dirent *fname;

        while((fname = readdir(d))) {
            if((strstr(fname->d_name, INSTRUMENT_EXTENSION) != NULL)
               || (strstr(fname->d_name, FORCE_BANK_DIR_FILE) != NULL)) {
                isbank = true;
                break; //could put a #instrument counter here instead
            }
        }

        if(isbank)
            banks.push_back(bank);

        closedir(d);
    }

    closedir(dir);
}

void Bank::clearbank()
{
    for(int i = 0; i < BANK_SIZE; ++i)
        ins[i] = ins_t();

    bankfiletitle.clear();
    dirname.clear();
}

std::vector<std::string> Bank::search(std::string s) const
{
    std::vector<std::string> out;
    auto vec = db->search(s);
    for(auto e:vec) {
        out.push_back(e.name);
        out.push_back(e.bank+e.file);
    }
    return out;
}

std::vector<std::string> Bank::blist(std::string s)
{
    std::vector<std::string> out;
    loadbank(s);
    for(int i=0; i<128; ++i) {
        if(ins[i].filename.empty())
            out.push_back("Empty Preset");
        else
            out.push_back(ins[i].name);
        out.push_back(to_s(i));
    }
    return out;
}

int Bank::addtobank(int pos, string filename, string name)
{
    if((pos >= 0) && (pos < BANK_SIZE)) {
        if(!ins[pos].filename.empty())
            pos = -1;  //force it to find a new free position
    }
    else
    if(pos >= BANK_SIZE)
        pos = -1;

    if(pos < 0)   //find a free position
        for(int i = BANK_SIZE - 1; i >= 0; i--)
            if(ins[i].filename.empty()) {
                pos = i;
                break;
            }

    if(pos < 0)
        return -1;  //the bank is full

    deletefrombank(pos);

    ins[pos].name     = name;
    ins[pos].filename = dirname + filename;
    return 0;
}

void Bank::deletefrombank(int pos)
{
    if((pos < 0) || (pos >= BANK_SIZE))
        return;
    ins[pos] = ins_t();
}

Bank::ins_t::ins_t()
    :name(""), filename("")
{}

void Bank::expanddirname(std::string &dirname) {
    if (dirname.empty())
        return;

    // if the directory name starts with a ~ and the $HOME variable is
    // defined in the environment, replace ~ by the content of $HOME
    if (dirname.at(0) == '~') {
        char *home_dirname = getenv("HOME");
        if (home_dirname != NULL) {
            dirname = std::string(home_dirname) + dirname.substr(1);
        }
    }
}

void Bank::normalizedirsuffix(string &dirname) const {
    if(((dirname[dirname.size() - 1]) != '/')
       && ((dirname[dirname.size() - 1]) != '\\'))
        dirname += "/";
}

}

{'repo_name': 'zynaddsubfx/zynaddsubfx', 'stars': '448', 'repo_language': 'C++', 'file_name': 'FindLIBLO.cmake', 'mime_type': 'text/plain', 'hash': 1152308579041617439, 'source_dataset': 'data'}


### Timer的使用

`Timer`继承自`NSObject`，用以提供延迟（周期性）触发动作的方法。通常，定时器会在指定间隔后自动触发，向指定对象发送消息。如果 timer 是非重复定时器，则触发一次后自动失效，从而防止定时器再次触发；如果是重复定时器，则会在指定间隔后重复触发，需手动调用`invaliate()`方法使计时器无效。

这篇文章将介绍计时器（Timer）如何使用，与 run loop 的关系，对性能、电量的影响，以及如何使用`CADisplayLink`处理动画。

详细介绍查看下面文章：

<https://github.com/pro648/tips/wiki/Timer的使用>

{'repo_name': 'pro648/BasicDemos-iOS', 'stars': '267', 'repo_language': 'Objective-C', 'file_name': 'LaunchScreen.storyboard', 'mime_type': 'text/xml', 'hash': -553474927016843493, 'source_dataset': 'data'}


#ifndef BOOST_MPL_VECTOR_AUX_CLEAR_HPP_INCLUDED
#define BOOST_MPL_VECTOR_AUX_CLEAR_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Id: clear.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $
// $Revision: 49267 $

#include <boost/mpl/clear_fwd.hpp>
#include <boost/mpl/vector/aux_/vector0.hpp>
#include <boost/mpl/vector/aux_/tag.hpp>
#include <boost/mpl/aux_/config/typeof.hpp>
#include <boost/mpl/aux_/config/ctps.hpp>

namespace boost { namespace mpl {

#if defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES)

template<>
struct clear_impl< aux::vector_tag >
{
    template< typename Vector > struct apply
    {
        typedef vector0<> type;
    };
};

#else

#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)

template< long N >
struct clear_impl< aux::vector_tag<N> >
{
    template< typename Vector > struct apply
    {
        typedef vector0<> type;
    };
};

#endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION

#endif // BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES

}}

#endif // BOOST_MPL_VECTOR_AUX_CLEAR_HPP_INCLUDED

{'repo_name': 'idaholab/raven', 'stars': '106', 'repo_language': 'Python', 'file_name': 'RBDmodel.tex', 'mime_type': 'text/x-tex', 'hash': -5704834942099706939, 'source_dataset': 'data'}


using System;
using System.Windows.Input;

namespace Adaptive.ReactiveTrader.Shared.UI
{
    public class DelegateCommand : ICommand
    {
        private readonly Func<bool> _canExecute;
        private readonly Action _execute;

        public DelegateCommand(Action execute)
            : this(execute, null)
        {}

        public DelegateCommand(Action execute, Func<bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }
            return _canExecute();
        }

        public void Execute(object parameter)
        {
            _execute();
        }

        public event EventHandler CanExecuteChanged;

        public void RaiseCanExecuteChanged()
        {
            var canExecuteChanged = CanExecuteChanged;
            if (canExecuteChanged != null)
            {
                canExecuteChanged(this, EventArgs.Empty);
            }
        }
    }
}

{'repo_name': 'AdaptiveConsulting/ReactiveTrader', 'stars': '953', 'repo_language': 'C#', 'file_name': 'Resources.Designer.cs', 'mime_type': 'text/plain', 'hash': 3898029264913736983, 'source_dataset': 'data'}


namespace android.content
{
	[global::MonoJavaBridge.JavaInterface(typeof(global::android.content.DialogInterface_OnCancelListener_))]
	public interface DialogInterface_OnCancelListener  : global::MonoJavaBridge.IJavaObject
	{
		void onCancel(android.content.DialogInterface arg0);
	}

	[global::MonoJavaBridge.JavaProxy(typeof(global::android.content.DialogInterface_OnCancelListener))]
	public sealed partial class DialogInterface_OnCancelListener_ : java.lang.Object, DialogInterface_OnCancelListener
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		static DialogInterface_OnCancelListener_()
		{
			InitJNI();
		}
		internal DialogInterface_OnCancelListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		internal static global::MonoJavaBridge.MethodId _onCancel1509;
		 void android.content.DialogInterface_OnCancelListener.onCancel(android.content.DialogInterface arg0)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.content.DialogInterface_OnCancelListener_._onCancel1509, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.DialogInterface_OnCancelListener_.staticClass, global::android.content.DialogInterface_OnCancelListener_._onCancel1509, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static void InitJNI()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.content.DialogInterface_OnCancelListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/DialogInterface_OnCancelListener"));
			global::android.content.DialogInterface_OnCancelListener_._onCancel1509 = @__env.GetMethodIDNoThrow(global::android.content.DialogInterface_OnCancelListener_.staticClass, "onCancel", "(Landroid/content/DialogInterface;)V");
		}
	}
}

{'repo_name': 'koush/androidmono', 'stars': '147', 'repo_language': 'C#', 'file_name': 'missing.c', 'mime_type': 'text/x-c', 'hash': 5815697684492317956, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<Product xmlns='https://github.com/OpenZWave/open-zwave' Revision="3">
	<!-- Configuration Parameters -->
	<CommandClass id="112">
		<Value type="list" index="1" genre="config" label="Set Ignore Start Level Bit When Transmitting Dim Commands" size="1" value="1">
			<Help>
The ZDW232 can send Dim commands to Z-Wave enabled dimmers. The Dim command has a start level embedded
in it. A dimmer receiving this command will start dimming from that start level. However, the command also has a
bit that indicates whether the dimmer should ignore the start level. If the bit is set to 1, the dimmer will ignore the
start level and instead start dimming from its current level. If this bit is set to 0, the dimmer will not ignore the start
level.
			</Help>
			<Item label="No" value="0" />
			<Item label="Yes" value="1" />
		</Value>
		<Value type="list" index="2" genre="config" label="Suspend Group 4" size="1" value="0">
			<Help>You may wish to disable transmitting commands to Z-Wave devices that are in Group 4 without "un-associating"
those devices from the group. Setting parameter 2 to the value of 1 will stop the ZDW232 from transmitting to devices
that are "associated" into Group 4.
It is possible that you may only want the units in Group 4 to track when the dimmer is being turned ON and OFF
and not when dimming.</Help>
			<Item label="No" value="0" />
			<Item label="Yes" value="1" />
		</Value>
		<Value type="list" index="3" genre="config" label="Night Light" size="1" value="0">
			<Help>In night-light mode the LED on the switch will turn ON when the switch is turned OFF.</Help>
			<Item label="No" value="0" />
			<Item label="Yes" value="1" />
		</Value>
		<Value type="list" index="4" genre="config" label="Invert Switch" size="1" value="0">
			<Help>To change the top of the switch to OFF and the bottom of the switch to ON, set parameter 4 to 1.</Help>
			<Item label="No" value="0" />
			<Item label="Yes" value="1" />
		</Value>
		<Value type="list" index="5" genre="config" label="Ignore Start Level When Receiving Dim Commands" size="1" value="1">
			<Help>The ZDW232 can be set to ignore the start level that is part of the dim command, regardless of whether the command
is telling the dimmer to ignore the start level or not ignore the start level embedded in the command (see Parameter
1). Setting parameter 5 to a value of 1 (factory default) will cause the ZDW232 to ignore the start level and to dim
or brighten from its current level. Setting the value to 0 will cause the ZDW232 to dim or brighten from the level in
the command.</Help>
			<Item label="No" value="0" />
			<Item label="Yes" value="1" />
		</Value>
		<Value type="list" index="6" genre="config" label="Don't Send Level Command After Transmitting Dim Commands" size="1" value="1">
			<Help>When you press and hold the bottom of the ZDW232 switch once, the Z-Wave devices that are associated into Group
1 are sent the Dim command. If parameter 6 is set to 0, after you release the switch, the ZDW232 will command
devices in that group to go to the same level of the ZDW232. If parameter 6 is set to a value of 1 (factory default)
the devices in Group 1 will not go to the same level of the ZDW232.</Help>
			<Item label="No" value="0" />
			<Item label="Yes" value="1" />
		</Value>
		<Value type="byte" index="7" genre="config" label="On/Off Command Dim Step" units="" min="1" max="99" value="1">
			<Help>Indicates how many levels the dimmer will change for each dimming step.</Help>
		</Value>
		<Value type="byte" index="8" genre="config" label="On/Off Command Dim Rate" units="x 10 milliseconds" min="1" max="255" value="3">
			<Help>This value indicates in 10 millisecond resolution, how often the dim level will change. For example, if you set this parameter to 1, then every 10ms the dim level will change. If you set it to 255, then every 2.55 seconds the dim level will change.</Help>
		</Value>
		<Value type="byte" index="9" genre="config" label="Local Control Dim Step" units="" min="1" max="99" value="1">
			<Help>Indicates how many levels the dimmer will change for each dimming step.</Help>
		</Value>
		<Value type="byte" index="10" genre="config" label="Local Control Dim Rate" units="x 10 milliseconds" min="1" max="255" value="3">
			<Help>This value indicates in 10 millisecond resolution, how often the dim level will change. For example, if you set this parameter to 1, then every 10ms the dim level will change. If you set it to 255, then every 2.55 seconds the dim level will change.</Help>
		</Value>
		<Value type="byte" index="11" genre="config" label="ALL ON/ALL OFF Dim Step" units="" min="1" max="99" value="1">
			<Help>Indicates how many levels the dimmer will change for each dimming step.</Help>
		</Value>
		<Value type="byte" index="12" genre="config" label="ALL ON/ALL OFF Dim Rate" units="x 10 milliseconds" min="1" max="255" value="3">
			<Help>This value indicates in 10 millisecond resolution, how often the dim level will change. For example, if you set this parameter to 1, then every 10ms the dim level will change. If you set it to 255, then every 2.55 seconds the dim level will change.</Help>
		</Value>
		<Value type="list" index="13" genre="config" label="Disable Group 4 During Dim" size="1">
			<Help>After the ZDW232 is commanded to stop dimming, it will then command the Z-Wave devices in Group 4 to the
ZDW232's new level. To prevent the ZDW232 from commanding the Z-Wave devices in Group 4 during this particular
occurrence, set Parameter 13 to the value of 1.</Help>
			<Item label="No" value="0" />
			<Item label="Yes" value="1" />
		</Value>
		<Value type="list" index="14" genre="config" label="Enable Shade Control Group 2" size="1" value="0">
			<Help>The ZDW232 can operate shade control devices via its group 2 if this configuration parameter is set to 1.</Help>
			<Item label="No" value="0" />
			<Item label="Yes" value="1" />
		</Value>
		<Value type="list" index="15" genre="config" label="Enable Shade Control Group 3" size="1" value="0">
			<Help>The ZDW232 can operate shade control devices via its group 3 if this configuration parameter is set to 1.</Help>
			<Item label="No" value="0" />
			<Item label="Yes" value="1" />
		</Value>
		<Value type="list" index="19" genre="config" label="LED Transmission Indication" size="1" value="2">
			<Help>The ZDW232 will flicker its LED when it is transmitting to any of its 4 groups. This flickering can be set to not flicker at all, to flicker the entire time it is transmitting, or to flicker for only 1 second when it begins transmitting.</Help>
			<Item label="None" value="0" />
			<Item label="While Transmitting" value="1" />
			<Item label="One Second Maximum" value="2" />
		</Value>
		<Value type="byte" index="20" genre="config" label="Poll Group 2 Interval" units="minutes" min="1" max="255" value="2">
			<Help>Poll Group 2 Interval</Help>
		</Value>
		<Value type="list" index="22" genre="config" label="Enable Group 2 Polling" size="1">
			<Help>Poll Group 2</Help>
			<Item label="No" value="0" />
			<Item label="Yes" value="1" />
		</Value>
	</CommandClass>

	<!-- Association Groups -->
	<CommandClass id="133">
		<Associations num_groups="4">
			<Group index="1" max_associations="5" label="One tap / Local load control" />
			<Group index="2" max_associations="5" label="Two taps (Dimmers: One tap, then hold to dim)" />
			<Group index="3" max_associations="5" label="Three taps (Dimmers: Two taps, then hold to dim)" />
			<Group index="4" max_associations="5" label="Update Controller" auto="true" />
		</Associations>
	</CommandClass>
</Product>

{'repo_name': 'domoticz/domoticz', 'stars': '2710', 'repo_language': 'C++', 'file_name': 'pySmartPlugSmpB16.py', 'mime_type': 'text/x-python', 'hash': -8955053439379629442, 'source_dataset': 'data'}


<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Serializer\Normalizer;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Oro\Bundle\ActionBundle\Model\AttributeManager;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;
use Oro\Bundle\WorkflowBundle\Acl\AclManager;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowDefinition;
use Oro\Bundle\WorkflowBundle\Exception\SerializerException;
use Oro\Bundle\WorkflowBundle\Model\Variable;
use Oro\Bundle\WorkflowBundle\Model\VariableManager;
use Oro\Bundle\WorkflowBundle\Model\Workflow;
use Oro\Bundle\WorkflowBundle\Model\WorkflowData;
use Oro\Bundle\WorkflowBundle\Restriction\RestrictionManager;
use Oro\Bundle\WorkflowBundle\Serializer\Normalizer\AttributeNormalizer;
use Oro\Bundle\WorkflowBundle\Serializer\Normalizer\WorkflowVariableNormalizer;
use Oro\Bundle\WorkflowBundle\Serializer\WorkflowAwareSerializer;

class WorkflowVariableNormalizerTest extends \PHPUnit\Framework\TestCase
{
    /** @var \PHPUnit\Framework\MockObject\MockObject */
    private $attributeNormalizer;

    /** @var \PHPUnit\Framework\MockObject\MockObject */
    private $serializer;

    /** @var \PHPUnit\Framework\MockObject\MockObject */
    private $workflow;

    /** @var \PHPUnit\Framework\MockObject\MockObject */
    private $attributeManager;

    /** @var WorkflowVariableNormalizer */
    private $normalizer;

    /**
     * Tests setup
     */
    protected function setUp(): void
    {
        $this->attributeNormalizer = $this->createMock(AttributeNormalizer::class);
        $this->serializer = $this->createMock(WorkflowAwareSerializer::class);
        $this->attributeManager = $this->createMock(AttributeManager::class);
        $doctrineHelper = $this->createMock(DoctrineHelper::class);
        $aclManager = $this->createMock(AclManager::class);
        $restrictionManager = $this->createMock(RestrictionManager::class);
        $variableManager = $this->createMock(VariableManager::class);
        $this->workflow = $this->getMockBuilder(Workflow::class)
            ->setMethods(['getName', 'getVariables', 'getDefinition'])
            ->setConstructorArgs([
                $doctrineHelper,
                $aclManager,
                $restrictionManager,
                null,
                $this->attributeManager,
                null,
                $variableManager
            ])->getMock();

        $workflowDefinition = $this->createMock(WorkflowDefinition::class);
        $workflowDefinition->expects($this->any())
            ->method('getConfiguration')
            ->willReturn([]);

        $this->workflow->expects($this->any())
            ->method('getVariables')
            ->will($this->returnValue(new ArrayCollection()));
        $this->workflow->expects($this->any())
            ->method('getDefinition')
            ->will($this->returnValue($workflowDefinition));

        $this->normalizer = $this->getMockNormalizer();
    }

    /**
     * Test variable normalization
     */
    public function testNormalize()
    {
        $variableName = 'test_variable';
        $denormalizedValue = 'denormalized_value';
        $normalizedValue = ['normalized_value'];
        $variable = $this->createVariable($variableName, 'string');

        $data = new WorkflowData();
        $data->set($variableName, $denormalizedValue);

        $this->normalizer->setSerializer($this->serializer);

        $this->serializer->expects($this->any())->method('getWorkflow')
            ->will($this->returnValue($this->workflow));

        $this->attributeNormalizer->expects($this->once())->method('supportsNormalization')
            ->with($this->workflow, $variable, $data->get($variableName))
            ->will($this->returnValue(true));

        $this->attributeNormalizer->expects($this->once())->method('normalize')
            ->with($this->workflow, $variable, $data->get($variableName))
            ->will($this->returnValue($normalizedValue));

        $this->assertEquals(
            $normalizedValue,
            $this->normalizer->normalizeVariable($this->workflow, $variable, ['value' => $denormalizedValue])
        );
    }

    /**
     * Test variable denormalization
     *
     * @dataProvider testDenormalizeProvider
     *
     * @param Variable $variable
     * @param string $variableName
     * @param mixed $expected
     * @param array $normalized
     * @param array $options
     */
    public function testDenormalize($variable, $variableName, $expected, $normalized, array $options = [])
    {
        $expectedData = new WorkflowData();
        $expectedData->set($variableName, $expected);

        $normalizer = $this->getMockNormalizer($variable, $options);
        $normalizer->setSerializer($this->serializer);

        $this->serializer->expects($this->any())->method('getWorkflow')
            ->will($this->returnValue($this->workflow));

        $this->attributeNormalizer->expects($this->any())->method('supportsDenormalization')
            ->with($this->workflow, $variable, $normalized[$variableName])
            ->will($this->returnValue(true));

        $this->attributeNormalizer->expects($this->any())->method('denormalize')
            ->with($this->workflow, $variable, $normalized[$variableName])
            ->will($this->returnValue($expectedData->get($variableName)));

        $denormalized = $normalizer->denormalizeVariable($this->workflow, $variable, [
            'value' => $variable->getValue(),
            'options' => $variable->getOptions(),
            'property_path' => $variable->getPropertyPath()
        ]);
        $this->assertEquals($expected, $denormalized);
    }

    /**
     * @return array
     */
    public function testDenormalizeProvider()
    {
        return [
            'string_value' => [
                'variable' => $this->createVariable('test_variable', 'string', 'normalized_value'),
                'variable_name' => 'test_variable',
                'expected' => 'denormalized_value',
                'normalized' => ['test_variable' => 'normalized_value']
            ],
            'array_value' => [
                'variable' => $this->createVariable('test_variable', 'array', ['item' => 'value']),
                'variable_name' => 'test_variable',
                'expected' => ['item' => 'value'],
                'normalized' => ['test_variable' => ['item' => 'value']]
            ],
            'object_value' => [
                'variable' => $this->createVariable(
                    'test_variable',
                    'object',
                    'en',
                    ['class' => 'stdClass'],
                    'code'
                ),
                'variable_name' => 'test_variable',
                'expected' => (object) ['code' => 'en'],
                'normalized' => ['test_variable' => (object) ['code' => 'en']]
            ],
            'entity_without_id_field' => [
                'variable' => $this->createVariable(
                    'test_variable',
                    'entity',
                    (object) ['id' => 1],
                    ['class' => 'stdClass', 'identifier' => 'id']
                ),
                'variable_name' => 'test_variable',
                'expected' => (object) ['id' => 1],
                'normalized' => ['test_variable' => ''],
                [
                    'isIdentifierComposite' => false,
                    'identifier' => ['id'],
                    'isUniqueField' => true
                ]
            ],
            'entity_id_field' => [
                'variable' => $this->createVariable(
                    'test_variable',
                    'entity',
                    (object) ['code' => 'en'],
                    ['class' => 'stdClass', 'identifier' => 'code']
                ),
                'variable_name' => 'test_variable',
                'expected' => (object) ['code' => 'en'],
                'normalized' => ['test_variable' => ''],
                [
                    'isIdentifierComposite' => false,
                    'identifier' => ['id'],
                    'isUniqueField' => true
                ]
            ],
        ];
    }

    /**
     * Test variable denormalization
     *
     * @dataProvider denormalizeExceptionsProvider
     *
     * @param string $exception
     * @param string $message
     * @param Variable $variable
     * @param string $variableName
     * @param mixed $expected
     * @param array $options
     *
     */
    public function testDenormalizeExceptions(
        $exception,
        $message,
        $variable,
        $variableName,
        $expected,
        array $options = []
    ) {
        $this->expectException($exception);
        $this->expectExceptionMessage($message);

        $expectedData = new WorkflowData();
        $expectedData->set($variableName, $expected);

        $normalizer = $this->getMockNormalizer($variable, $options);
        $normalizer->setSerializer($this->serializer);

        $this->serializer->expects($this->any())->method('getWorkflow')
            ->will($this->returnValue($this->workflow));

        $this->attributeNormalizer->expects($this->any())->method('supportsDenormalization')
            ->will($this->returnValue(true));

        $this->attributeNormalizer->expects($this->any())->method('denormalize')
            ->will($this->returnValue($expectedData->get($variableName)));

        $normalizer->denormalizeVariable($this->workflow, $variable, [
            'value' => $variable->getValue(),
            'options' => $variable->getOptions(),
            'property_path' => $variable->getPropertyPath()
        ]);
    }

    /**
     * @return array
     */
    public function denormalizeExceptionsProvider()
    {
        return [
            'entity_no_manager' => [
                SerializerException::class,
                'Can\'t get entity manager for class stdClass',
                'variable' => $this->createVariable(
                    'test_variable',
                    'entity',
                    (object) ['id' => 1],
                    ['class' => 'stdClass', 'identifier' => 'id']
                ),
                'variable_name' => 'test_variable',
                'expected' => (object) ['id' => 1],
                [
                    'getManagerForClass' => false,
                    'isIdentifierComposite' => false,
                    'identifier' => ['id'],
                    'isUniqueField' => true
                ]
            ],
            'entity_composite_id' => [
                SerializerException::class,
                'Entity with class stdClass has a composite identifier',
                'variable' => $this->createVariable(
                    'test_variable',
                    'entity',
                    (object) ['code' => 'en'],
                    ['class' => 'stdClass', 'identifier' => 'code']
                ),
                'variable_name' => 'test_variable',
                'expected' => (object) ['code' => 'en'],
                [
                    'isIdentifierComposite' => true,
                    'identifier' => ['id'],
                    'isUniqueField' => true
                ]
            ],
            'entity_not_unique_id' => [
                SerializerException::class,
                'Field code is not unique in entity with class stdClass',
                'variable' => $this->createVariable(
                    'test_variable',
                    'entity',
                    (object) ['code' => 'en'],
                    ['class' => 'stdClass', 'identifier' => 'code']
                ),
                'variable_name' => 'test_variable',
                'expected' => (object) ['code' => 'en'],
                [
                    'isIdentifierComposite' => false,
                    'identifier' => ['id'],
                    'isUniqueField' => false
                ]
            ],
        ];
    }

    /**
     * @dataProvider supportsNormalizationDataProvider
     */
    public function testSupportsNormalization($data, $expected)
    {
        $this->assertEquals($expected, $this->normalizer->supportsNormalization($data, 'any_value'));
    }

    /**
     * @return array
     */
    public function supportsNormalizationDataProvider()
    {
        return [
            [null, false],
            ['scalar', false],
            [new \DateTime(), false],
            [new WorkflowData(), true],
            [$this->createMock(WorkflowData::class), true],
        ];
    }

    /**
     * @dataProvider supportsDenormalizationDataProvider
     */
    public function testSupportsDenormalization($type, $expected)
    {
        $this->assertEquals($expected, $this->normalizer->supportsDenormalization('any_value', $type));
    }

    /**
     * @return array
     */
    public function supportsDenormalizationDataProvider()
    {
        return [
            [null, false],
            ['string', false],
            ['DateTime', false],
            [WorkflowData::class, true],
            [$this->getMockClass(WorkflowData::class), true],
        ];
    }

    /**
     * @return array
     */
    public function normalizeDirectionDataProvider()
    {
        return [
            ['normalization'],
            ['denormalization'],
        ];
    }

    /**
     * @param string $name
     * @param string $type
     * @param string $value
     * @param array  $options
     * @param null   $propertyPath
     *
     * @return Variable
     */
    private function createVariable($name, $type, $value = null, array $options = [], $propertyPath = null)
    {
        $variable = new Variable();
        $variable
            ->setName($name)
            ->setType($type)
            ->setOptions($options)
            ->setPropertyPath($propertyPath)
            ->setValue($value)
            ->setLabel($name);

        return $variable;
    }

    /**
     * @param Variable|null $expected
     * @param array $options
     *
     * @return WorkflowVariableNormalizer|\PHPUnit\Framework\MockObject\MockObject
     */
    private function getMockNormalizer(Variable $expected = null, array $options = [])
    {
        if (!$expected instanceof Variable || 'entity' !== $expected->getType()) {
            $doctrine = $this->createMock(ManagerRegistry::class);
            $doctrine->expects($this->any())
                ->method('getManagerForClass')
                ->willReturn($this->createMock(ObjectManager::class));

            return new WorkflowVariableNormalizer([$this->attributeNormalizer], $doctrine);
        }

        $classMetadata = $this->createMock(ClassMetadataInfo::class);
        $classMetadata->isIdentifierComposite = $options['isIdentifierComposite'];
        $classMetadata->expects($this->any())
            ->method('getIdentifier')
            ->willReturn($options['identifier']);
        $classMetadata->expects($this->any())
            ->method('isUniqueField')
            ->willReturn($options['isUniqueField']);

        $fakeRepository = $this->getMockBuilder(EntityRepository::class)
            ->disableOriginalConstructor()
            ->setMethods(['findOneBy'])
            ->getMock();
        $fakeRepository->expects($this->any())
            ->method('findOneBy')
            ->willReturn($expected->getValue());

        $entityManager = $this->createMock(EntityManager::class);
        $entityManager->expects($this->any())
            ->method('getClassMetadata')
            ->willReturn($classMetadata);
        $entityManager->expects($this->any())
            ->method('getRepository')
            ->willReturn($fakeRepository);

        $getManagerForClass = $options['getManagerForClass'] ?? true;
        $managerForClass = $getManagerForClass ? $entityManager : null;

        $doctrine = $this->createMock(ManagerRegistry::class);
        $doctrine->expects($this->any())
            ->method('getManagerForClass')
            ->willReturn($managerForClass);

        return new WorkflowVariableNormalizer([$this->attributeNormalizer], $doctrine);
    }
}

{'repo_name': 'oroinc/platform', 'stars': '584', 'repo_language': 'PHP', 'file_name': 'user_email_activity.feature', 'mime_type': 'text/plain', 'hash': 1383766118147835342, 'source_dataset': 'data'}


/* (c) 2014 Open Source Geospatial Foundation - all rights reserved
 * (c) 2001 - 2013 OpenPlans
 * This code is licensed under the GPL 2.0 license, available at the root
 * application directory.
 */
package org.geoserver.security.web.jdbc.role;

import org.geoserver.security.jdbc.H2RoleServiceTest;
import org.geoserver.security.jdbc.H2UserGroupServiceTest;
import org.geoserver.security.web.role.RoleListPageTest;
import org.junit.Test;

public class JDBCRoleListPageTest extends RoleListPageTest {

    @Test
    public void testRemove() throws Exception {
        // insertValues();
        addAdditonalData();
        doRemove(getTabbedPanelPath() + ":panel:header:removeSelected");
    }

    @Override
    protected void doInitialize() throws Exception {
        initializeForJDBC();
    }

    void initializeForJDBC() throws Exception {
        initialize(new H2UserGroupServiceTest(), new H2RoleServiceTest());
    }

    @Override
    public String getRoleServiceName() {
        return "h2";
    }

    @Override
    public String getUserGroupServiceName() {
        return "h2";
    }
}

{'repo_name': 'geoserver/geoserver', 'stars': '1985', 'repo_language': 'Java', 'file_name': 'featuretype.xml', 'mime_type': 'text/html', 'hash': -1140541890403598798, 'source_dataset': 'data'}


kernel vec4 filterKernel(sampler inputImage, sampler inputLUT, float intensity) {
    vec4 textureColor = sample(inputImage,samplerCoord(inputImage));
    textureColor = clamp(textureColor, vec4(0.0), vec4(1.0));

    float blueColor = textureColor.b * 63.0;

    vec2 quad1;
    quad1.y = floor(floor(blueColor) / 8.0);
    quad1.x = floor(blueColor) - (quad1.y * 8.0);

    vec2 quad2;
    quad2.y = floor(ceil(blueColor) / 8.0);
    quad2.x = ceil(blueColor) - (quad2.y * 8.0);

    vec2 texPos1;
    texPos1.x = (quad1.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);
    texPos1.y = (quad1.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g);

    vec2 texPos2;
    texPos2.x = (quad2.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);
    texPos2.y = (quad2.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g);

    texPos1.y = 1.0 - texPos1.y;
    texPos2.y = 1.0 - texPos2.y;

    vec4 inputLUTExtent = samplerExtent(inputLUT);

    vec4 newColor1 = sample(inputLUT, samplerTransform(inputLUT, texPos1 * vec2(512.0) + inputLUTExtent.xy));
    vec4 newColor2 = sample(inputLUT, samplerTransform(inputLUT, texPos2 * vec2(512.0) + inputLUTExtent.xy));

    vec4 newColor = mix(newColor1, newColor2, fract(blueColor));
    return mix(textureColor, vec4(newColor.rgb, textureColor.a), intensity);
}

{'repo_name': 'YuAo/YUCIHighPassSkinSmoothing', 'stars': '1082', 'repo_language': 'Objective-C', 'file_name': 'LaunchScreen.storyboard', 'mime_type': 'text/xml', 'hash': 2672529503312692438, 'source_dataset': 'data'}


/*
Copyright (C) 2006 - 2015 Evan Teran
                          evan.teran@gmail.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "DialogAbout.h"
#include "version.h"

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)

//------------------------------------------------------------------------------
// Name: DialogAbout
// Desc: constructor
//------------------------------------------------------------------------------
DialogAbout::DialogAbout(QWidget *parent, Qt::WindowFlags f)
	: QDialog(parent, f) {
	ui.setupUi(this);
	ui.labelVersion->setText(tr("Version: %1
\n"
								"Compiled: %2
\n"
								"Git Commit: %3")
								 .arg(edb::version, __DATE__, TOSTRING(GIT_BRANCH)));
}

{'repo_name': 'eteran/edb-debugger', 'stars': '1605', 'repo_language': 'C++', 'file_name': 'DialogFunctions.cpp', 'mime_type': 'text/x-c++', 'hash': -8786885198350662162, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<ldml>
	<identity>
		<version number="$Revision: 4123 $"/>
		<generation date="$Date: 2009-05-06 08:06:42 +0900 (Wed, 06 May 2009) $"/>
		<language type="ve"/>
		<territory type="ZA"/>
	</identity>
</ldml>

{'repo_name': 'JetBrains/jdk8u_jdk', 'stars': '147', 'repo_language': 'Java', 'file_name': 'MacOSXNativeDispatcher.java', 'mime_type': 'text/x-java', 'hash': 7760380122727378305, 'source_dataset': 'data'}


package io.github.benas.unixstream.components;

import io.github.benas.unixstream.Stage;

import java.util.stream.Stream;

/**
 * Keep the first X elements from a stream.
 * This is an alias for {@link Stream#limit(long)}.
 *
 * @param <T> the type of elements in the stream
 * @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
 */
public class Head<T> implements Stage<T, T> {

    public static long DEFAULT_SIZE = 10;

    private long size;

    /**
     * Create a new {@link Head} instance.
     */
    public Head() {
        this(DEFAULT_SIZE);
    }

    /**
     * Create a new {@link Head} instance.
     *
     * @param size the number of elements to keep
     */
    public Head(final long size) {
        if (size < 1) {
            throw new IllegalArgumentException("Size must be >= 1");
        }
        this.size = size;
    }

    /**
     * Create a new {@link Head} instance.
     *
     * @param <T> the type of elements in the stream
     * @return a new {@link Head} instance.
     */
    public static <T> Head<T> head() {
        return new Head<>();
    }

    /**
     * Create a new {@link Head} instance.
     *
     * @param size the number of elements to keep
     * @param <T>  the type of elements in the stream
     * @return a new {@link Head} instance.
     */
    public static <T> Head<T> head(final long size) {
        return new Head<>(size);
    }

    @Override
    public Stream<T> apply(Stream<T> input) {
        return input.limit(size);
    }

}

{'repo_name': 'benas/unix-stream', 'stars': '116', 'repo_language': 'Java', 'file_name': 'TrimTest.java', 'mime_type': 'text/x-java', 'hash': 6385301524921941213, 'source_dataset': 'data'}


.. algorithm::

.. summary::

.. relatedalgorithms::

.. properties::

Description
-----------

Filters out events using the entries in the Sample Logs.

Sample logs consist of a series of pairs. The first step in filtering is
to generate a list of start-stop time intervals that will be kept, using
those logs.

-  Each log value is compared to the min/max value filters to determine
   whether it is "good" or not.

   -  For a single log value that satisfies the criteria at time T, all
      events between T+-Tolerance (LogBoundary=Centre), or T and
      T+Tolerance (LogBoundary=Left) are kept.
   -  If there are several consecutive log values matching the filter,
      events between T1-Tolerance and T2+Tolerance, where T2 is the last
      "good" value (LogBoundary=Centre), or T1 and T2, where T2 is the
      first "bad" value (LogBoundary=Left) are kept.

-  The filter is then applied to all events in all spectra. Any events
   with pulse times outside of any "good" time ranges are removed.

There is no interpolation of log values between the discrete sample log
times at this time. However, the log value is assumed to be constant at
times before its first point and after its last. For example, if the
first temperature measurement was at time=10 seconds and a temperature
within the acceptable range, then all events between 0 and 10 seconds
will be included also. If a log has a single point in time, then that
log value is assumed to be constant for all time and if it falls within
the range, then all events will be kept.

.. warning::

   :ref:`FilterByLogValue <algm-FilterByLogValue>` is not suitable for
   fast log filtering.

PulseFilter (e.g. for Veto Pulses)
##################################

If you select PulseFilter, then events will be filtered OUT in notches
around each time in the selected sample log, and the MinValue/MaxValue
parameters are ignored. For example:

-  If you have 3 entries at times:

   -  10, 20, 30 seconds.
   -  A TimeTolerance of 1 second.

-  Then the events at the following times will be EXCLUDED from the
   output:

   -  9-11; 19-21; 29-30 seconds.

The typical use for this is to filter out "veto" pulses from a SNS event
nexus file. Some of these files have a sample log called
"veto\_pulse\_time" that only contains times of the pulses to be
rejected. For example, this call will filter out veto pulses:

.. testsetup:: VetoPulseTime

   ws=CreateSampleWorkspace("Event")
   AddTimeSeriesLog(ws, Name="veto_pulse_time", Time="2010-01-01T00:00:00", Value=1)
   AddTimeSeriesLog(ws, Name="veto_pulse_time", Time="2010-01-01T00:10:00", Value=0)
   AddTimeSeriesLog(ws, Name="veto_pulse_time", Time="2010-01-01T00:20:00", Value=1)
   AddTimeSeriesLog(ws, Name="veto_pulse_time", Time="2010-01-01T00:30:00", Value=0)
   AddTimeSeriesLog(ws, Name="veto_pulse_time", Time="2010-01-01T00:40:00", Value=1)
   AddTimeSeriesLog(ws, Name="veto_pulse_time", Time="2010-01-01T00:50:00", Value=0)

.. testcode:: VetoPulseTime

   ws = FilterByLogValue(ws, LogName="veto_pulse_time", PulseFilter="1")

Comparing with other event filtering algorithms
###############################################

The :ref:`EventFiltering` page has a detailed introduction on event
filtering in mantid.

Usage
-----

**Example - Filtering by a simple time series Log**

.. testcode:: FilterByLogValue

   ws = CreateSampleWorkspace("Event",BankPixelWidth=1)

   AddTimeSeriesLog(ws, Name="proton_charge", Time="2010-01-01T00:00:00", Value=100)
   AddTimeSeriesLog(ws, Name="proton_charge", Time="2010-01-01T00:10:00", Value=100)
   AddTimeSeriesLog(ws, Name="proton_charge", Time="2010-01-01T00:20:00", Value=100)
   AddTimeSeriesLog(ws, Name="proton_charge", Time="2010-01-01T00:30:00", Value=100)
   AddTimeSeriesLog(ws, Name="proton_charge", Time="2010-01-01T00:40:00", Value=15)
   AddTimeSeriesLog(ws, Name="proton_charge", Time="2010-01-01T00:50:00", Value=100)

   print("The unfiltered workspace {} has {} events and a peak value of {:.2f}".format(ws, ws.getNumberEvents(),ws.readY(0)[50]))

   wsOut = FilterByLogValue(ws,"proton_charge",MinimumValue=75, MaximumValue=150)

   print("The filtered workspace {} has {} events and a peak value of {:.2f}".format(wsOut, wsOut.getNumberEvents(),wsOut.readY(0)[50]))

Output:

.. testoutput:: FilterByLogValue

   The unfiltered workspace ws has 1900 events and a peak value of 2...
   The filtered workspace wsOut has 950 events and a peak value of 1...

.. categories::

.. sourcelink::

{'repo_name': 'mantidproject/mantid', 'stars': '140', 'repo_language': 'C++', 'file_name': 'launcher-template.desktop.in', 'mime_type': 'text/plain', 'hash': 2591134285189712374, 'source_dataset': 'data'}