text:
package modules

import (
	"regexp"

	"github.com/etcinit/phabulous/app/interfaces"
)

const (
	// RegularMatcherType is used for all regular messages (on channels
	// usually) that do not mention the bot.
	RegularMatcherType MatcherType = iota

	// IMMatcherType is used for all messages sent directly to the bot
	// (private messages).
	IMMatcherType

	// MentionMatcherType is used for messages in channels but that directly
	// mention the bot's username.
	MentionMatcherType
)

// MatcherType is the type of a matcher.
type MatcherType int

// HandlerTuple is a simple pairing of a regular expressions and a handler
// function to be called if it is matched with the input message.
type HandlerTuple struct {
	Pattern *regexp.Regexp
	Handler interfaces.Handler
}

// GetPattern returns the regular expression pattern in this tuple.
func (t HandlerTuple) GetPattern() *regexp.Regexp {
	return t.Pattern
}

// GetHandler returns the Handler in this tuple.
func (t HandlerTuple) GetHandler() interfaces.Handler {
	return t.Handler
}

// RegexBuilder is a function to be provided by Connector implementations while
// using CompileHeaders. It allows the Connector to modify any regular
// expressions before they are added to the matcher lists.
type RegexBuilder func(matcherType MatcherType, pattern string) *regexp.Regexp

// CompileHandlers is a utility function for Connector implementations to
// process all the modules/commands provided into a mapping of HandlerTuples.
// The first list returned is expressions to be matched on regular chats, and
// the second list has expressions to be matched on private/direct
// conversations with a bot.
func CompileHandlers(
	modules []interfaces.Module,
	builder RegexBuilder,
) ([]interfaces.HandlerTuple, []interfaces.HandlerTuple) {
	handlers := []interfaces.HandlerTuple{}
	imHandlers := []interfaces.HandlerTuple{}

	for _, module := range modules {
		for _, command := range module.GetCommands() {
			for _, rgx := range command.GetMatchers() {
				handlers = append(handlers, HandlerTuple{
					Pattern: builder(RegularMatcherType, rgx),
					Handler: command.GetHandler(),
				})
			}

			for _, rgx := range command.GetIMMatchers() {
				imHandlers = append(imHandlers, HandlerTuple{
					Pattern: builder(IMMatcherType, rgx),
					Handler: command.GetHandler(),
				})
			}

			for _, rgx := range command.GetMentionMatchers() {
				handlers = append(handlers, HandlerTuple{
					Pattern: builder(MentionMatcherType, rgx),
					Handler: command.GetHandler(),
				})
			}
		}
	}

	return handlers, imHandlers
}


text:
package bboss.org.jgroups.stack;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

import bboss.org.jgroups.Address;
import bboss.org.jgroups.util.Range;
import bboss.org.jgroups.util.Seqno;
import bboss.org.jgroups.util.SeqnoComparator;
import bboss.org.jgroups.util.SeqnoRange;
import bboss.org.jgroups.util.TimeScheduler;

/**
 * This retransmitter is specialized in maintaining ranges of seqnos, e.g. [3-20, [89-89], [100-120].
 * The ranges are stored in a sorted hashmap and the {@link Comparable#compareTo(Object)} method compares both ranges
 * again ranges, and ranges against seqnos. The latter helps to find a range given a seqno, e.g. seqno 105 will find
 * range [100-120].

 * Each range is implemented by {@link bboss.org.jgroups.util.SeqnoRange}, which has a bitset of all missing seqnos. When
 * a seqno is received, that bit set is updated; the bit corresponding to the seqno is set to 1. A task linked to
 * the range periodically retransmits missing messages.

 * When all bits are 1 (= all messages have been received), the range is removed from the hashmap and the retransmission
 * task is cancelled.
 *
 * @author Bela Ban
 * @version $Id: RangeBasedRetransmitter.java,v 1.6 2009/11/30 12:36:52 belaban Exp $
 */
public class RangeBasedRetransmitter extends Retransmitter {

    // todo: when JDK 6 is the baseline, convert the TreeMap to a TreeSet or ConcurrentSkipListSet and use ceiling()
    /** Sorted hashmap storing the ranges */
    private final Map<Seqno,Seqno> ranges=Collections.synchronizedSortedMap(new TreeMap<Seqno,Seqno>(new SeqnoComparator()));

    /** Association between ranges and retransmission tasks */
    private final Map<Seqno,Task> tasks=new ConcurrentHashMap<Seqno,Task>();

    private final AtomicLong num_missing_seqnos=new AtomicLong(0);
    private final AtomicLong num_ranges=new AtomicLong(0);
    private final AtomicLong num_single_msgs=new AtomicLong(0);

    /**
     * Create a new Retransmitter associated with the given sender address
     * @param sender the address from which retransmissions are expected or to which retransmissions are sent
     * @param cmd    the retransmission callback reference
     * @param sched  retransmissions scheduler
     */
    public RangeBasedRetransmitter(Address sender, RetransmitCommand cmd, TimeScheduler sched) {
        super(sender, cmd, sched);
    }

    /**
     * Add the given range [first_seqno, last_seqno] in the list of
     * entries eligible for retransmission. If first_seqno > last_seqno,
     * then the range [last_seqno, first_seqno] is added instead
     */
    public void add(long first_seqno, long last_seqno) {
        if(first_seqno > last_seqno) {
            long tmp=first_seqno;
            first_seqno=last_seqno;
            last_seqno=tmp;
        }

        num_missing_seqnos.addAndGet(last_seqno - first_seqno +1);

        // create a single seqno if we have no range or else a SeqnoRange
        Seqno range=first_seqno == last_seqno? new Seqno(first_seqno) : new SeqnoRange(first_seqno, last_seqno);
        if(range instanceof SeqnoRange)
            num_ranges.incrementAndGet();
        else
            num_single_msgs.incrementAndGet();

        // each task needs its own retransmission interval, as they are stateful *and* mutable, so we *need* to copy !
        RangeTask new_task=new RangeTask(range, RETRANSMIT_TIMEOUTS.copy(), cmd, sender);

        Seqno old_range=ranges.put(range, range);
        if(old_range != null)
            log.error("new range " + range + " overlaps with old range " + old_range);

        tasks.put(range, new_task);
        new_task.doSchedule(); // Entry adds itself to the timer

        if(log.isTraceEnabled())
            log.trace("added range " + sender + " [" + range + "]");
    }

    /**
     * Remove the given sequence number from the list of seqnos eligible
     * for retransmission. If there are no more seqno intervals in the
     * respective entry, cancel the entry from the retransmission
     * scheduler and remove it from the pending entries
     */
    public int remove(long seqno) {
        int retval=0;
        Seqno range=ranges.get(new Seqno(seqno, true));
        if(range == null)
            return 0;

        range.set(seqno);
        if(log.isTraceEnabled())
            log.trace("removed " + sender + " #" + seqno + " from retransmitter");

        // if the range has no missing messages, get the associated task and cancel it
        if(range.getNumberOfMissingMessages() == 0) {
            Task task=tasks.remove(range);
            if(task != null) {
                task.cancel();
                retval=task.getNumRetransmits();
            }
            else
                log.error("task for range " + range + " not found");
            ranges.remove(range);
            if(log.isTraceEnabled())
                log.trace("all messages for " + sender + " [" + range + "] have been received; removing range");
        }

        return retval;
    }

    /**
     * Reset the retransmitter: clear all msgs and cancel all the
     * respective tasks
     */
    public void reset() {
        synchronized(ranges) {
            for(Seqno range: ranges.keySet()) {
                // get task associated with range and cancel it
                Task task=tasks.get(range);
                if(task != null) {
                    task.cancel();
                    tasks.remove(range);
                }
            }

            ranges.clear();
        }

        for(Task task: tasks.values())
            task.cancel();

        num_missing_seqnos.set(0);
        num_ranges.set(0);
        num_single_msgs.set(0);
    }

    public String toString() {
        int missing_msgs=0;

        synchronized(ranges) {
            for(Seqno range: ranges.keySet()) {
                missing_msgs+=range.getNumberOfMissingMessages();
            }
        }

        StringBuilder sb=new StringBuilder();
        sb.append(missing_msgs).append(" messages to retransmit");
        if(missing_msgs < 50) {
            Collection<Range> all_missing_msgs=new LinkedList<Range>();
            for(Seqno range: ranges.keySet()) {
                all_missing_msgs.addAll(range.getMessagesToRetransmit());
            }
            sb.append(": ").append(all_missing_msgs);
        }
        return sb.toString();
    }

    public int size() {
        int retval=0;

        synchronized(ranges) {
            for(Seqno range: ranges.keySet()) {
                retval+=range.getNumberOfMissingMessages();
            }
        }
        return retval;
    }

    public String printStats() {
        StringBuilder sb=new StringBuilder();
        sb.append("total seqnos=" + num_missing_seqnos);
        sb.append(", single seqnos=" + num_single_msgs);
        sb.append(", ranges=" + num_ranges);
        double avg_seqnos_per_range=(double)(num_missing_seqnos.get() - num_single_msgs.get()) / num_ranges.get();
        sb.append(", seqnos / range: " + avg_seqnos_per_range);
        return sb.toString();
    }

    protected class RangeTask extends Task {
        protected final Seqno range;

        protected RangeTask(Seqno range, Interval intervals, RetransmitCommand cmd, Address msg_sender) {
            super(intervals, cmd, msg_sender);
            this.range=range;
        }

        public String toString() {
            return range.toString();
        }

        protected void callRetransmissionCommand() {
            Collection<Range> missing=range.getMessagesToRetransmit();
            if(missing.isEmpty()) {
                cancel();
            }
            else {
                for(Range range: missing) {
                    command.retransmit(range.low, range.high, msg_sender);
                }
            }
        }
    }

    /* ------------------------------- Private Methods -------------------------------------- */

    /* ---------------------------- End of Private Methods ------------------------------------ */

}

redpajama_set_name: RedPajamaGithub


text:
package ca.etsmtl.applets.etsmobile.model;

//----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 2.0.0.4
//
// Created by Quasar Development at 15-01-2014
//
//---------------------------------------------------

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import org.ksoap2.serialization.AttributeContainer;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;

import java.util.Hashtable;

import ca.etsmtl.applets.etsmobile.http.soap.ExtendedSoapSerializationEnvelope;

@DatabaseTable(tableName = "programme")
public class Programme extends AttributeContainer implements KvmSerializable {

	@DatabaseField(id = true)
	public String code;
	@DatabaseField
	public String libelle;
	@DatabaseField
	public String profil;
	@DatabaseField
	public String statut;
	@DatabaseField
	public String sessionDebut;
	@DatabaseField
	public String sessionFin;
	@DatabaseField
	public String moyenne;
	@DatabaseField
	public String nbEquivalences;
	@DatabaseField
	public String nbCrsReussis;
	@DatabaseField
	public String nbCrsEchoues;
	@DatabaseField
	public String nbCreditsInscrits;
	@DatabaseField
	public String nbCreditsCompletes;
	@DatabaseField
	public String nbCreditsPotentiels;
	@DatabaseField
	public String nbCreditsRecherche;

	public Programme() {
	}

	public Programme(AttributeContainer inObj, ExtendedSoapSerializationEnvelope envelope) {

		if (inObj == null)
			return;

		SoapObject soapObject = (SoapObject) inObj;

		if (soapObject.hasProperty("code")) {
			Object obj = soapObject.getProperty("code");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					code = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				code = (String) obj;
			}
		}
		if (soapObject.hasProperty("libelle")) {
			Object obj = soapObject.getProperty("libelle");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					libelle = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				libelle = (String) obj;
			}
		}
		if (soapObject.hasProperty("profil")) {
			Object obj = soapObject.getProperty("profil");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					profil = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				profil = (String) obj;
			}
		}
		if (soapObject.hasProperty("statut")) {
			Object obj = soapObject.getProperty("statut");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					statut = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				statut = (String) obj;
			}
		}
		if (soapObject.hasProperty("sessionDebut")) {
			Object obj = soapObject.getProperty("sessionDebut");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					sessionDebut = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				sessionDebut = (String) obj;
			}
		}
		if (soapObject.hasProperty("sessionFin")) {
			Object obj = soapObject.getProperty("sessionFin");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					sessionFin = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				sessionFin = (String) obj;
			}
		}
		if (soapObject.hasProperty("moyenne")) {
			Object obj = soapObject.getProperty("moyenne");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					moyenne = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				moyenne = (String) obj;
			}
		}
		if (soapObject.hasProperty("nbEquivalences")) {
			Object obj = soapObject.getProperty("nbEquivalences");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					nbEquivalences = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				nbEquivalences = (String) obj;
			}
		}
		if (soapObject.hasProperty("nbCrsReussis")) {
			Object obj = soapObject.getProperty("nbCrsReussis");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					nbCrsReussis = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				nbCrsReussis = (String) obj;
			}
		}
		if (soapObject.hasProperty("nbCrsEchoues")) {
			Object obj = soapObject.getProperty("nbCrsEchoues");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					nbCrsEchoues = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				nbCrsEchoues = (String) obj;
			}
		}
		if (soapObject.hasProperty("nbCreditsInscrits")) {
			Object obj = soapObject.getProperty("nbCreditsInscrits");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					nbCreditsInscrits = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				nbCreditsInscrits = (String) obj;
			}
		}
		if (soapObject.hasProperty("nbCreditsCompletes")) {
			Object obj = soapObject.getProperty("nbCreditsCompletes");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					nbCreditsCompletes = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				nbCreditsCompletes = (String) obj;
			}
		}
		if (soapObject.hasProperty("nbCreditsPotentiels")) {
			Object obj = soapObject.getProperty("nbCreditsPotentiels");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					nbCreditsPotentiels = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				nbCreditsPotentiels = (String) obj;
			}
		}
		if (soapObject.hasProperty("nbCreditsRecherche")) {
			Object obj = soapObject.getProperty("nbCreditsRecherche");
			if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
				SoapPrimitive j = (SoapPrimitive) obj;
				if (j.toString() != null) {
					nbCreditsRecherche = j.toString();
				}
			} else if (obj != null && obj instanceof String) {
				nbCreditsRecherche = (String) obj;
			}
		}

	}

	@Override
	public Object getProperty(int propertyIndex) {
		if (propertyIndex == 0) {
			return code;
		}
		if (propertyIndex == 1) {
			return libelle;
		}
		if (propertyIndex == 2) {
			return profil;
		}
		if (propertyIndex == 3) {
			return statut;
		}
		if (propertyIndex == 4) {
			return sessionDebut;
		}
		if (propertyIndex == 5) {
			return sessionFin;
		}
		if (propertyIndex == 6) {
			return moyenne;
		}
		if (propertyIndex == 7) {
			return nbEquivalences;
		}
		if (propertyIndex == 8) {
			return nbCrsReussis;
		}
		if (propertyIndex == 9) {
			return nbCrsEchoues;
		}
		if (propertyIndex == 10) {
			return nbCreditsInscrits;
		}
		if (propertyIndex == 11) {
			return nbCreditsCompletes;
		}
		if (propertyIndex == 12) {
			return nbCreditsPotentiels;
		}
		if (propertyIndex == 13) {
			return nbCreditsRecherche;
		}
		return null;
	}

	@Override
	public int getPropertyCount() {
		return 14;
	}

	@Override
	public void getPropertyInfo(int propertyIndex, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo info) {
		if (propertyIndex == +0) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "code";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +1) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "libelle";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +2) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "profil";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +3) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "statut";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +4) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "sessionDebut";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +5) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "sessionFin";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +6) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "moyenne";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +7) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "nbEquivalences";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +8) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "nbCrsReussis";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +9) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "nbCrsEchoues";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +10) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "nbCreditsInscrits";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +11) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "nbCreditsCompletes";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +12) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "nbCreditsPotentiels";
			info.namespace = "http://etsmtl.ca/";
		}
		if (propertyIndex == +13) {
			info.type = PropertyInfo.STRING_CLASS;
			info.name = "nbCreditsRecherche";
			info.namespace = "http://etsmtl.ca/";
		}
	}

	@Override
	public void setProperty(int arg0, Object arg1) {
	}

}


text:
package org.telegram.telegrambots.meta.api.methods.invoices;

import org.junit.jupiter.api.Test;
import org.telegram.telegrambots.meta.api.objects.payments.LabeledPrice;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

/**
 * @author Ruben Bermudez
 * @version 5.2
 */
public class SendInvoiceTest {
    @Test
    public void validObjectMustNotThrow() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        assertDoesNotThrow(sendInvoice::validate);
        sendInvoice.setSuggestedTipAmounts(new ArrayList<>());
        assertDoesNotThrow(sendInvoice::validate);
    }

    @Test
    public void chatIdCantBeEmpty() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setChatId("");
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("ChatId parameter can't be empty", thrown.getMessage());
    }

    @Test
    public void titleCantBeEmpty() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setTitle("");
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("Title parameter can't be empty or longer than 32 chars", thrown.getMessage());
    }

    @Test
    public void titleCantBeOver32Chars() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setTitle("1234567890123456789012345678901234");
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("Title parameter can't be empty or longer than 32 chars", thrown.getMessage());
    }

    @Test
    public void descriptionCantBeEmpty() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setDescription("");
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("Description parameter can't be empty or longer than 255 chars", thrown.getMessage());
    }

    @Test
    public void descriptionCantBeOver255() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setDescription("1234567890123456789012345678901234567890123456789012345678901234567890" +
                "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" +
                "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345" +
                "1234567890123456789012345678901234567890123456789012345678901234567890");
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("Description parameter can't be empty or longer than 255 chars", thrown.getMessage());
    }

    @Test
    public void payloadCantBeEmpty() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setPayload("");
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("Payload parameter can't be empty", thrown.getMessage());
    }

    @Test
    public void providerTokenCantBeEmpty() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setProviderToken("");
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("ProviderToken parameter can't be empty", thrown.getMessage());
    }

    @Test
    public void currencyCantBeEmpty() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setCurrency("");
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("Currency parameter can't be empty", thrown.getMessage());
    }

    @Test
    public void pricesMustBeValidated() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setPrices(Collections.singletonList(LabeledPrice.builder().label("").amount(1).build()));
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("Label parameter can't be empty", thrown.getMessage());
    }

    @Test
    public void pricesCantBeEmpty() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setPrices(new ArrayList<>());
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("Prices parameter can't be empty", thrown.getMessage());
        sendInvoice.setPrices(Collections.singletonList(LabeledPrice.builder().label("").amount(1).build()));
        thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("Label parameter can't be empty", thrown.getMessage());
    }

    @Test
    public void suggestedTipAmountsMustNotHaveMoreThan4Elements() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setSuggestedTipAmounts(Arrays.asList(1,2,3,4,5));
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("No more that 4 suggested tips allowed", thrown.getMessage());
    }

    @Test
    public void replyMarkupMustBeValidated() {
        SendInvoice sendInvoice = createSendInvoiceObject();
        sendInvoice.setReplyMarkup(InlineKeyboardMarkup.builder().keyboardRow(Collections.singletonList(InlineKeyboardButton.builder().text("").build())).build());
        Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
        assertEquals("Text parameter can't be empty", thrown.getMessage());
    }

    private SendInvoice createSendInvoiceObject() {
        return SendInvoice.builder()
                .chatId(123456L)
                .title("Title")
                .description("Description")
                .payload("Payload")
                .providerToken("ProviderToken")
                .startParameter("StartParameter")
                .currency("Currency")
                .price(LabeledPrice.builder().label("Label").amount(1).build())
                .suggestedTipAmount(1)
                .suggestedTipAmount(2)
                .suggestedTipAmount(3)
                .suggestedTipAmount(4)
                .replyMarkup(InlineKeyboardMarkup.builder().keyboardRow(Collections.singletonList(InlineKeyboardButton.builder().text("Hello").build())).build())
                .build();
    }
}


text:
using System.IO;

namespace Coevery.Data.Bags.Serialization {
    public interface IBagSerializer : IDependency {
        void Serialize(TextWriter tw, Bag o);
        Bag Deserialize(TextReader tr);
    }
}


text:
<?php
namespace Oka\PaginationBundle\Tests\Pagination\FilterExpression\ORM;

use Oka\PaginationBundle\Pagination\FilterExpression\ORM\RangeORMFilterExpression;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 *
 * @author Cedrick Oka Baidai <okacedrick@gmail.com>
 *
 */
class RangeORMFilterExpressionTest extends KernelTestCase
{
	/**
	 * @var \Doctrine\ORM\EntityManager
	 */
	protected $entityManager;

	public function setUp() :void
	{
		static::bootKernel();

		$this->entityManager = static::$container->get('doctrine.orm.entity_manager');
	}

	/**
	 * @covers
	 */
	public function testThatFilterCanSupportEvaluation()
	{
		$filterExpression = new RangeORMFilterExpression();

		$this->assertEquals(true, $filterExpression->supports($this->entityManager->createQueryBuilder(), 'range[1,2]'));
	}

	/**
	 * @covers
	 */
	public function testThatFilterCanEvaluateExpression()
	{
		$filterExpression = new RangeORMFilterExpression();
		$queryBuilder = $this->entityManager->createQueryBuilder();

		$result = $filterExpression->evaluate($queryBuilder, 'p.field', 'range[1,2]', 'int');
		/** @var \Doctrine\ORM\Query\Expr $expr */
		$expr = $result->getExpr();

		$this->assertEquals('p.field >= ?1 AND p.field <= ?2', $expr->__toString());
		$this->assertEquals([1 => 1, 2 => 2], $result->getParameters());

		$result = $filterExpression->evaluate($queryBuilder, 'p.field', 'range]1,2]', 'int');
		/** @var \Doctrine\ORM\Query\Expr $expr */
		$expr = $result->getExpr();

		$this->assertEquals('p.field > ?1 AND p.field <= ?2', $expr->__toString());
		$this->assertEquals([1 => 1, 2 => 2], $result->getParameters());

		$result = $filterExpression->evaluate($queryBuilder, 'p.field', 'range[1,3[', 'int');
		/** @var \Doctrine\ORM\Query\Expr $expr */
		$expr = $result->getExpr();

		$this->assertEquals('p.field >= ?1 AND p.field < ?2', $expr->__toString());
		$this->assertEquals([1 => 1, 2 => 3], $result->getParameters());

		$result = $filterExpression->evaluate($queryBuilder, 'p.field', 'range]1,2[', 'int');
		/** @var \Doctrine\ORM\Query\Expr $expr */
		$expr = $result->getExpr();

		$this->assertEquals('p.field > ?1 AND p.field < ?2', $expr->__toString());
		$this->assertEquals([1 => 1, 2 => 2], $result->getParameters());

		$result = $filterExpression->evaluate($queryBuilder, 'p.field', 'range]1,[', 'int');
		/** @var \Doctrine\ORM\Query\Expr $expr */
		$expr = $result->getExpr();

		$this->assertEquals('p.field > ?1', $expr->__toString());
		$this->assertEquals([1 => 1], $result->getParameters());

		$result = $filterExpression->evaluate($queryBuilder, 'p.field', 'range],2[', 'int');
		/** @var \Doctrine\ORM\Query\Expr $expr */
		$expr = $result->getExpr();

		$this->assertEquals('p.field < ?1', $expr->__toString());
		$this->assertEquals([1 => 2], $result->getParameters());
	}
}


text:
package com.animals.app.repository.Impl;

import com.animals.app.domain.Animal;
import com.animals.app.domain.Pagenator;
import com.animals.app.repository.AnimalRepository;
import com.animals.app.repository.MyBatisConnectionFactory;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * Created by Rostyslav.Viner on 24.07.2015.
 */
public class AnimalRepositoryImpl {
    private SqlSessionFactory sqlSessionFactory;

    public AnimalRepositoryImpl() {
        sqlSessionFactory = new MyBatisConnectionFactory().getSqlSessionFactory();
    }

    /**
     * Insert an instance of Animal into the database.
     * @param animal the instance to be persisted.
     */
    public void insert(Animal animal) {

        SqlSession session = sqlSessionFactory.openSession();

        try {
            AnimalRepository mapper = session.getMapper(AnimalRepository.class);
            mapper.insert(animal);

            session.commit();
        } finally {
            session.close();
        }

    }

    /**
     * Update an instance of Animal in the database.
     * @param animal the instance to be updated.
     */
    public void update(Animal animal) {

        SqlSession session = sqlSessionFactory.openSession();

        try {
            AnimalRepository mapper = session.getMapper(AnimalRepository.class);
            mapper.update(animal);

            session.commit();
        } finally {
            session.close();
        }

    }

    /**
     * Delete an instance of Animal from the database.
     * @param id primary key value of the instance to be deleted.
     */
    public void delete(long id) {

        SqlSession session = sqlSessionFactory.openSession();

        try {
            AnimalRepository mapper = session.getMapper(AnimalRepository.class);
            mapper.delete(id);

            session.commit();
        } finally {
            session.close();
        }

    }

    /**
     * Returns an Animal instance from the database.
     * @param id primary key value used for lookup.
     * @return An Animal instance with a primary key value equals to pk. null if there is no matching row.
     */
    public Animal getById(long id){

        SqlSession session = sqlSessionFactory.openSession();

        try {
            AnimalRepository mapper = session.getMapper(AnimalRepository.class);
            return mapper.getById(id);
        } finally {
            session.close();
        }
    }

    /**
     * Returns the list of all Animal instances from the database.
     * @return the list of all Animal instances from the database.
     */
    public List<Animal> getAllForAdminAnimalsListByPage(Pagenator page) {

        SqlSession session = sqlSessionFactory.openSession();

        try {
            AnimalRepository mapper = session.getMapper(AnimalRepository.class);
            return mapper.getAllForAdminAnimalsListByPage(page);
        } finally {
            session.close();
        }
    }

    /**
     * Created by 41X 08.08.2015
     * Returns count of rows selected from DB by method getAdminAnimalsListByPage
     * @return count of rows selected by getAdminAnimalsListByPage
     */
    public Pagenator getAdminAnimalsListByPageCount() {

        SqlSession session = sqlSessionFactory.openSession();

        try {
            AnimalRepository mapper = session.getMapper(AnimalRepository.class);
            return mapper.getAdminAnimalsListByPageCount();
        } finally {
            session.close();
        }
    }

    /*
     * This method return short information about animals for showing on adopting page.
     * @param pagenator Separating records for a parts.
     * @return the list of all Animal instances from the database.
     */
    public List<Animal> getAllForAdopting(Pagenator pagenator){

        SqlSession session = sqlSessionFactory.openSession();

        try {
            AnimalRepository mapper = session.getMapper(AnimalRepository.class);
            return mapper.getAllForAdopting(pagenator);
        } finally {
            session.close();
        }
    }

    /**
     * Returns count of rows selected from DB by method getAllForAdopting
     * @return count of rows selected by getAllForAdopting
     */
    public Pagenator getAmountListForAdopting() {

        SqlSession session = sqlSessionFactory.openSession();

        try {
            AnimalRepository mapper = session.getMapper(AnimalRepository.class);
            return mapper.getAmountListForAdopting();
        } finally {
            session.close();
        }
    }

    /*
     * This method return short information about animals by UserId for showing on UserCabinet.
     * @return the list of Animal instances from the database with UserId.
     */
    public List<Animal> getAnimalByUserId(int parseId) {

    	SqlSession session = sqlSessionFactory.openSession();

        try {
            AnimalRepository mapper = session.getMapper(AnimalRepository.class);
            return mapper.getAnimalByUserId(parseId);
        } finally {
            session.close();
        }
	}

    /**
     * Returns short information about animal by id.
     * @param id primary key value used for lookup.
     * @return An Animal instance with a primary key value equals to pk. null if there is no matching row.
     */
    public Animal getShortInfoById(long id){
        SqlSession session = sqlSessionFactory.openSession();

        try {
            AnimalRepository mapper = session.getMapper(AnimalRepository.class);
            return mapper.getShortInfoById(id);
        } finally {
            session.close();
        }
    }
}


text:
namespace extensions {

namespace {

constexpr char kIdA[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
constexpr char kIdB[] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
constexpr char kIdC[] = "cccccccccccccccccccccccccccccccc";
constexpr char kIdD[] = "dddddddddddddddddddddddddddddddd";
constexpr char kIdE[] = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
constexpr char kIdF[] = "ffffffffffffffffffffffffffffffff";
constexpr char kIdG[] = "gggggggggggggggggggggggggggggggg";
constexpr char kIdX[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

// A vector based implementation of WorkerIdSet.
// GetAllForExtension()/Contains() are O(n).
class VectorWorkerIdListImpl {
 public:
  explicit VectorWorkerIdListImpl(const std::vector<WorkerId> worker_ids)
      : workers_(worker_ids) {}
  ~VectorWorkerIdListImpl() = default;

  std::vector<WorkerId> GetAllForExtension(const ExtensionId& extension_id,
                                           int render_process_id) const {
    std::vector<WorkerId> matching_workers;
    for (const WorkerId& worker_id : workers_) {
      if (worker_id.extension_id == extension_id &&
          worker_id.render_process_id == render_process_id) {
        matching_workers.push_back(worker_id);
      }
    }
    return matching_workers;
  }

  bool Contains(const WorkerId& worker_id) const {
    return std::find(workers_.begin(), workers_.end(), worker_id) !=
           workers_.end();
  }

 private:
  std::vector<WorkerId> workers_;

  DISALLOW_COPY_AND_ASSIGN(VectorWorkerIdListImpl);
};

std::vector<WorkerId> GenerateWorkerIds(
    const std::vector<ExtensionId>& extension_ids,
    const std::vector<int>& render_process_ids,
    const std::vector<int64_t>& worker_version_ids,
    const std::vector<int>& worker_thread_ids) {
  std::vector<WorkerId> worker_ids;
  for (const ExtensionId& extension_id : extension_ids) {
    for (int render_process_id : render_process_ids) {
      for (int64_t worker_version_id : worker_version_ids) {
        for (int worker_thread_id : worker_thread_ids) {
          worker_ids.push_back(WorkerId({extension_id, render_process_id,
                                         worker_version_id, worker_thread_id}));
        }
      }
    }
  }
  return worker_ids;
}

std::unique_ptr<WorkerIdSet> CreateWorkerIdSet(
    const std::vector<WorkerId>& worker_ids) {
  auto worker_id_set = std::make_unique<WorkerIdSet>();
  for (const WorkerId& worker_id : worker_ids)
    worker_id_set->Add(worker_id);
  return worker_id_set;
}

}  // namespace

class WorkerIdSetTest : public testing::Test {
 public:
  WorkerIdSetTest() = default;

  bool AreWorkerIdsEqual(const std::vector<WorkerId>& expected,
                         const std::vector<WorkerId>& actual) {
    if (expected.size() != actual.size())
      return false;

    std::vector<WorkerId> expected_copy = expected;
    std::vector<WorkerId> actual_copy = actual;
    std::sort(expected_copy.begin(), expected_copy.end());
    std::sort(actual_copy.begin(), actual_copy.end());
    return expected_copy == actual_copy;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(WorkerIdSetTest);
};

TEST_F(WorkerIdSetTest, GetAllForExtension) {
  std::unique_ptr<WorkerIdSet> workers = CreateWorkerIdSet({{kIdA, 1, 100, 1},
                                                            {kIdA, 1, 101, 2},
                                                            {kIdA, 1, 102, 1},
                                                            {kIdA, 1, 103, 3},
                                                            {kIdB, 2, 100, 3},
                                                            {kIdB, 2, 100, 4},
                                                            {kIdC, 2, 110, 5},
                                                            {kIdA, 9, 100, 4}});

  EXPECT_TRUE(AreWorkerIdsEqual({{kIdA, 1, 100, 1},
                                 {kIdA, 1, 101, 2},
                                 {kIdA, 1, 102, 1},
                                 {kIdA, 1, 103, 3}},
                                workers->GetAllForExtension(kIdA, 1)));
  EXPECT_TRUE(AreWorkerIdsEqual({{kIdB, 2, 100, 4}, {kIdB, 2, 100, 3}},
                                workers->GetAllForExtension(kIdB, 2)));
  EXPECT_TRUE(AreWorkerIdsEqual({{kIdC, 2, 110, 5}},
                                workers->GetAllForExtension(kIdC, 2)));
  EXPECT_TRUE(AreWorkerIdsEqual({{kIdA, 9, 100, 4}},
                                workers->GetAllForExtension(kIdA, 9)));

  // No matches.
  EXPECT_TRUE(workers->GetAllForExtension(kIdX, 1).empty());
  EXPECT_TRUE(workers->GetAllForExtension(kIdB, 1).empty());
  EXPECT_TRUE(workers->GetAllForExtension(kIdA, 2).empty());
  EXPECT_TRUE(workers->GetAllForExtension(kIdX, 2).empty());
  EXPECT_TRUE(workers->GetAllForExtension(kIdB, 9).empty());
  EXPECT_TRUE(workers->GetAllForExtension(kIdC, 9).empty());
  EXPECT_TRUE(workers->GetAllForExtension(kIdX, 9).empty());
  EXPECT_TRUE(workers->GetAllForExtension(kIdA, 10).empty());
  EXPECT_TRUE(workers->GetAllForExtension(kIdB, 10).empty());
  EXPECT_TRUE(workers->GetAllForExtension(kIdC, 10).empty());
  EXPECT_TRUE(workers->GetAllForExtension(kIdX, 10).empty());
}

TEST_F(WorkerIdSetTest, RemoveAllForExtension) {
  // Some worker ids with multiple workers pointing to same extension(s).
  std::vector<WorkerId> workers_vector = {
      {kIdA, 10, 1, 2}, {kIdA, 10, 3, 4}, {kIdA, 11, 1, 2}, {kIdA, 12, 1, 2},
      {kIdB, 10, 1, 2}, {kIdB, 14, 1, 2}, {kIdB, 15, 1, 2}, {kIdB, 16, 1, 2},
      {kIdC, 20, 7, 3}, {kIdD, 20, 7, 3}, {kIdD, 20, 8, 2}, {kIdD, 21, 7, 1},
      {kIdD, 22, 9, 9}};
  std::unique_ptr<WorkerIdSet> worker_id_set =
      CreateWorkerIdSet(workers_vector);
  EXPECT_EQ(workers_vector.size(), worker_id_set->count_for_testing());

  size_t expected_entries_removed = 0u;
  auto test_removal = [&](const std::string& extension_id_to_remove,
                          size_t expected_removal_count) {
    std::vector<WorkerId> worker_ids_to_remove =
        worker_id_set->GetAllForExtension(extension_id_to_remove);
    for (const auto& worker_id : worker_ids_to_remove) {
      if (!worker_id_set->Remove(worker_id)) {
        return ::testing::AssertionFailure()
               << "WorkerId not found to Remove: "
               << "{" << worker_id.extension_id
               << ", rph = " << worker_id.render_process_id
               << ", version_id = " << worker_id.version_id
               << ", thread = " << worker_id.thread_id << "}";
      }
    }
    expected_entries_removed += expected_removal_count;

    const size_t num_expected_entries =
        workers_vector.size() - expected_entries_removed;
    const size_t num_actual_entries = worker_id_set->count_for_testing();
    if (num_expected_entries != num_actual_entries) {
      return ::testing::AssertionFailure()
             << "Expected number of workers: " << num_expected_entries
             << ". Actual number of workers: " << num_actual_entries;
    }

    // No entry with |extension_id_to_remove| should be present.
    for (const WorkerId& worker_id : workers_vector) {
      if (worker_id.extension_id == extension_id_to_remove) {
        if (worker_id_set->Contains(worker_id)) {
          return ::testing::AssertionFailure()
                 << "Worker with extension_id: " << extension_id_to_remove
                 << " was not removed.";
        }
      }
    }
    return ::testing::AssertionSuccess();
  };

  // Removes 4 entries.
  EXPECT_TRUE(test_removal(kIdB, 4u));

  // The next attempt to remove the same extension wouldn't remove anything.
  EXPECT_TRUE(test_removal(kIdB, 0u));

  // Removes 1 entry.
  EXPECT_TRUE(test_removal(kIdC, 1u));

  // Removes 4 entries.
  EXPECT_TRUE(test_removal(kIdA, 4u));

  // Removes last entries.
  EXPECT_TRUE(test_removal(kIdD, 4u));

  EXPECT_EQ(0u, worker_id_set->count_for_testing());
}

// Tests parity of WorkerIdSet methods with a std::vector implementation.
TEST_F(WorkerIdSetTest, ExtensiveCases) {
  std::vector<WorkerId> worker_ids_vector =
      GenerateWorkerIds({kIdA, kIdC, kIdE, kIdG}, {1, 3, 5, 7, 9},
                        {10, 30, 50, 70}, {100, 300, 500, 700});
  VectorWorkerIdListImpl test_impl(worker_ids_vector);
  std::unique_ptr<WorkerIdSet> impl = CreateWorkerIdSet(worker_ids_vector);

  // Worker ids that we're going to use to test |worker_ids_vector|.
  std::vector<WorkerId> test_case_worker_ids_vector = GenerateWorkerIds(
      {kIdA, kIdB, kIdC, kIdD, kIdE, kIdF, kIdG}, {1, 2, 3, 4, 5, 6, 7, 8, 9},
      {10, 20, 30, 40, 50, 60, 70, 80, 90},
      {100, 200, 300, 400, 500, 600, 700, 800, 900});

  // Test that GetAllForExtension/Contains return the same value as vector based
  // implementation.
  for (const WorkerId& w : test_case_worker_ids_vector) {
    EXPECT_TRUE(AreWorkerIdsEqual(
        test_impl.GetAllForExtension(w.extension_id, w.render_process_id),
        impl->GetAllForExtension(w.extension_id, w.render_process_id)));
    EXPECT_EQ(test_impl.Contains(w), impl->Contains(w));
  }
}

}  // namespace extensions


text:
/*!
 *  Copyright (c) 2018 by Contributors
 * \file type_solver.h
 * \brief Solver logic for type inference.
 */
#ifndef TVM_RELAY_PASS_TYPE_SOLVER_H_
#define TVM_RELAY_PASS_TYPE_SOLVER_H_

#include <tvm/relay/expr.h>
#include <tvm/relay/type.h>
#include <tvm/relay/analysis.h>
#include <tvm/relay/error.h>
#include <vector>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include "../../common/arena.h"

namespace tvm {
namespace relay {

using common::LinkNode;
using common::LinkedList;

/*!
 * \brief Interface of type solver used in type inference.
 *
 * TypeSolver works on a list of constraints among incomplete types.
 * The user will populate the constraints by AddConstraint and Assign.
 * Then we can call Solve to trying to resolve the unknown.
 *
 * This can be viewed as "type program(computational graph)" of types, where
 * the type constraint are operators of the graph and the incomplete
 * types are intermediate value of the graph.
 * If all the input types are concretely known, we should be able to
 * just run a forward pass on the "type program" to get all the types.
 *
 * The list of constraints representation means we are storing it as a bipartite
 * graph instead of a DAG. This is because some constraints might go both direction.
 * TypeSolver could take advantage of bidirectional constraints to deduce input
 * value given output ones. Never-the-less, we should keep in mind that
 * there is a "forward direction" that the TypeSolver should take advantage of.
 */
class TypeSolver {
 public:
  TypeSolver(const GlobalVar& current_func, ErrorReporter* err_reporter);
  ~TypeSolver();
  /*!
   * \brief Add a type constraint to the solver.
   * \param constraint The constraint to be added.
   * \param location The location at which the constraint was incurred.
   */
  void AddConstraint(const TypeConstraint& constraint, const NodeRef& lcoation);
  /*!
   * \brief Resolve type to the solution type in the solver.
   * \param type The type to be resolved.
   * \return The resolved type.
   */
  Type Resolve(const Type& type);
  /*!
   * \brief Start to solve the types using the current known information.
   * \return Whether all the incomplete types has been fully resolved.
   */
  bool Solve();
  /*!
   * \brief Unify lhs and rhs.
   * \param lhs The left operand.
   * \param rhs The right operand
   * \param location The location at which the unification problem arose.
   */
  Type Unify(const Type& lhs, const Type& rhs, const NodeRef& location);
  /*!
   * \brief Report an error at the provided location.
   * \param err The error to report.
   * \param loc The location at which to report the error.
   */
  void ReportError(const Error& err, const NodeRef& location);

 private:
  class OccursChecker;
  class Unifier;
  class Resolver;
  class Propagator;
  class Merger;
  class Reporter;
  struct TypeNode;
  struct RelationNode;
  // Internally the solver maintains a bipartite graph of Relation and Types.
  // All the object in the structure is managed by a arena allocator
  // which releases the memory upon distruction of the type solver.
  /*!
   * \brief type node struct
   *  TypeNode implements a union-find data structure(via parent)
   *  that can unifies the same types to the name resolved_type.
   *
   *  It also contains collection of links to related Relations,
   *  which is stored in rel_set.
   */
  struct TypeNode {
    /*! \brief The final resolved type */
    Type resolved_type;
    /*! \brief type node in the union find algorithm */
    TypeNode* parent{nullptr};
    /*! \brief set of relations that is related to this type node */
    std::unordered_set<RelationNode*> rel_set;

    /*!
     * \brief Find the root type node, perform path compression
     * \return The root type node.
     */
    TypeNode* FindRoot() {
      // fast path
      if (this->parent == nullptr) return this;
      // slow path with path compression.
      TypeNode* root = this;
      while (root->parent != nullptr) {
        root = root->parent;
      }
      for (TypeNode* p = this; p != root;) {
        TypeNode* parent = p->parent;
        p->parent = root;
        p = parent;
      }
      return root;
    }
  };

  /*! \brief relation node */
  struct RelationNode {
    /*! \brief Whether the relation is in the queue to be solved */
    bool inqueue{false};
    /*! \brief Whether the relation is resolved */
    bool resolved{false};
    /*! \brief The corresponding type relation */
    TypeRelation rel;
    /*! \brief list types to this relation */
    LinkedList<TypeNode*> type_list;
    /*! \brief The location this type relation originated from. */
    NodeRef location;
  };

  /*! \brief A simple union find between shapes. */
  tvm::Map<IndexExpr, IndexExpr> shape_uf_;
  /*! \brief List of all allocated type nodes */
  std::vector<TypeNode*> type_nodes_;
  /*! \brief List of all allocated relation nodes */
  std::vector<RelationNode*> rel_nodes_;
  /*! \brief Number of resolved relations */
  size_t num_resolved_rels_{0};
  /*! \brief map from types to type nodes. */
  std::unordered_map<Type, TypeNode*, NodeHash, NodeEqual> tmap_;
  /*! \brief Internal queue to update the relation */
  std::queue<RelationNode*> update_queue_;
  /*! \brief allocator of all the internal node obhect*/
  common::Arena arena_;
  /*! \brief Reporter that reports back to self */
  TypeReporter reporter_;
  /*! \brief The global representing the current function. */
  GlobalVar current_func;
  /*! \brief Error reporting. */
  ErrorReporter* err_reporter_;

  /*!
   * \brief GetTypeNode that is corresponds to t.
   * if it do not exist, create a new one.
   * \return The type node.
   */
  TypeNode* GetTypeNode(const Type& t) {
    auto it = tmap_.find(t);
    if (it != tmap_.end()) {
      return it->second->FindRoot();
    } else {
      TypeNode* n = arena_.make<TypeNode>();
      type_nodes_.push_back(n);
      n->resolved_type = t;
      tmap_[t] = n;
      return n;
    }
  }
  /*!
   * \brief Add relation node rel to the update queue
   * \param rel The relation node
   */
  void AddToQueue(RelationNode* rel) {
    if (rel->inqueue) return;
    CHECK(!rel->resolved);
    rel->inqueue = true;
    update_queue_.push(rel);
  }

  /*!
   * \brief Merge rhs type node to lhs
   * \param src The source operand
   * \param dst The dst operand.
   */
  void MergeFromTo(TypeNode* src, TypeNode* dst);
};

}  // namespace relay
}  // namespace tvm
#endif  // TVM_RELAY_PASS_TYPE_SOLVER_H_


text:
#import "MWorksCocoa/MWCocoaEvent.h"
#import "MWorksCocoa/MWClientServerBase.h"
#import "MWorksCocoa/NSString+MWorksCocoaAdditions.h"
#import "MWorksCore/GenericData.h"
#import "MWorksCore/VariableProperties.h"
#import "MWMATLABWindowController.h"
#import "MWVarEntry.h"

#include <MWorksCore/ScarabServices.h>

@interface MWMATLABWindowController(Private)
- (void)codecArrived:(MWCocoaEvent *)codec;
- (void)updateClientCallbacks:(NSArray *)names_of_variables_to_register;
- (void)MATLABExecutionLoop:(id)obj;
- (void)serviceEvent:(MWCocoaEvent *)event;
- (void)reset;
- (void)updateCurrentSelectedVariables:(id)arg;
@end

#define MATLAB_WINDOW_CALLBACK_KEY @"MWorksMATLABWindow callback key"

#define MATLAB_EXECUTABLE_PATH @"MATLAB client window - MATLAB executable path"
#define MATLAB_M_FILE @"MATLAB client window - MATLAB .m file"
#define SYNC_EVENT_NAME @"MATLAB client window - sync event name"
#define SELECTED_VAR_NAMES @"MATLAB client window - selected variables"
#define COLLECTING_DATA @"MATLAB client window - running"
#define PROCESSING_DATA @"MATLAB client window - processing"
#define MW_SCROLL_TO_BOTTOM @"MATLAB client window - scroll to bottom on output"

@implementation MWMATLABWindowController

-  (id) init {
	self = [super init];
	if (self != nil) {
		matlabLock = [[NSRecursiveLock alloc] init];
		eventList = [[NSMutableArray alloc] init];
		executionList = [[NSMutableArray alloc] init];
		default_selected_variables = [[NSArray alloc] init];
		collectingEvents = NO;
		savedCodec = new Datum();
	}
	return self;
}

- (void)dealloc {
	delete savedCodec;

}

- (NSString *)matlabFileName {return [matlab_file_name lastPathComponent]; }
- (void)setMatlabFileName:(NSString *)new_matlab_file {
	matlab_file_name = [new_matlab_file copy];
	[mi setMatlabFile:matlab_file_name];

}

- (void) setLogTextContent:(NSString *)new_content {
	logTextContent = [new_content copy];

	// set it in the UI
    [[logTextView textStorage] setAttributedString:[[NSAttributedString alloc] initWithString:logTextContent
                                                                                attributes:@{ NSForegroundColorAttributeName: [NSColor textColor] }]];

};
@synthesize logTextContent;

@synthesize delegate;

- (void)setDelegate:(id)new_delegate {
	if(![new_delegate respondsToSelector:@selector(unregisterCallbacksWithKey:)] ||
	   ![new_delegate respondsToSelector:@selector(variableNames)] ||
	   ![new_delegate respondsToSelector:@selector(registerEventCallbackWithReceiver:
												   selector:
												   callbackKey:
                                                   onMainThread:)] ||
	   ![new_delegate respondsToSelector:@selector(registerEventCallbackWithReceiver:
												   selector:
												   callbackKey:
												   forVariableCode:
                                                   onMainThread:)] ||
	   ![new_delegate respondsToSelector:@selector(codeForTag:)] ||
	   ![new_delegate respondsToSelector:@selector(updateVariableWithTag:
												   withData:)]) {
		[NSException raise:NSInternalInconsistencyException
					format:@"Delegate doesn't respond to required methods for MWMATLABWindowController"];
	}

	delegate = new_delegate;
	[delegate registerEventCallbackWithReceiver:self
                                       selector:@selector(codecArrived:)
                                    callbackKey:[MATLAB_WINDOW_CALLBACK_KEY UTF8String]
								forVariableCode:RESERVED_CODEC_CODE
                                   onMainThread:YES];
}

- (void)awakeFromNib {
    if (!initializeScarab()) {
        NSLog(@"Scarab initialization failed");
    }

	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

	[self setProcessing:[defaults boolForKey:PROCESSING_DATA]];
	[self setRunning:[defaults boolForKey:COLLECTING_DATA]];

	NSString *matlabFile = [defaults objectForKey:MATLAB_M_FILE];
	if(matlabFile != nil) {
		[self setMatlabFileName:matlabFile];
	}

	if([defaults stringForKey:SYNC_EVENT_NAME]) {
		self.syncEventName = [defaults stringForKey:SYNC_EVENT_NAME];
	} else {
		self.syncEventName = @"";
	}

	[NSThread detachNewThreadSelector:@selector(MATLABExecutionLoop:)
							 toTarget:self
						   withObject:nil];

	[self setLogTextContent:@"Matlab output:\n"];
	if ([defaults boolForKey:MW_SCROLL_TO_BOTTOM]) {
		scrollToBottom = [defaults boolForKey:MW_SCROLL_TO_BOTTOM];
	} else {
		scrollToBottom = TRUE;
	}
	if (scrollToBottom == TRUE) {
		[scrollToBottomButton setState:NSControlStateValueOn];
	} else {
		[scrollToBottomButton setState:NSControlStateValueOff];
	}

}

// *******************************************************************
// *                 Interface builder methods
// *******************************************************************
- (IBAction)chooseMATLABFile:(id)sender {
	[matlabLock lock];

	NSOpenPanel * op = [NSOpenPanel openPanel];
	[op setTitle:@"Select MATLAB .m file to open"];
	[op setCanChooseDirectories:NO];
	[op setCanChooseFiles:YES];
	[op setAllowsMultipleSelection:NO];
    [op setAllowedFileTypes:[NSArray arrayWithObject:@"m"]];

	int bp = [op runModal];

	if(bp == NSModalResponseOK) {

		NSArray * fn = [op URLs];
		NSEnumerator * fileEnum = [fn objectEnumerator];
		NSURL * filename;
		NSString *matlabFile;

		while((filename = [fileEnum nextObject])) {
			matlabFile = [filename path];
		}

		NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
		[defaults setObject:matlabFile forKey:MATLAB_M_FILE];

		[self setMatlabFileName:matlabFile];
	}

	[matlabLock unlock];
	[self reset];
}

- (IBAction)primeMATLABEngine:(id)sender {
	[matlabLock lock];
	[mi startMATLABEngine];
	[matlabLock unlock];
}

- (IBAction)resetAction:(id)sender {
	[self reset];
}

/**********************************
 * Accessors
 **********************************/
- (NSString *)syncEventName { return sync_event_name; }
- (void)setSyncEventName:(NSString *)new_sync_event_name {
	@synchronized(vl) {
		sync_event_name = [new_sync_event_name copy];
		[vl setSyncEventName:sync_event_name];
		[[NSUserDefaults standardUserDefaults] setObject:sync_event_name forKey:SYNC_EVENT_NAME];

		[self updateVariableFilter];
		[vl reloadData];
	}

	[self reset];
}

- (int)processing { return processing; }
- (void)setProcessing:(int)new_processing {
	[[NSUserDefaults standardUserDefaults] setBool:new_processing forKey:PROCESSING_DATA];
	processing = new_processing;
}

- (int)running { return running; }
- (void)setRunning:(int)new_running {
	[[NSUserDefaults standardUserDefaults] setBool:new_running forKey:COLLECTING_DATA];
	running = new_running;
}

@synthesize numberToProcessString = number_to_process_string;

/*******************************************************************
 *                 MWDataEventListenerProtocol Methods
 *******************************************************************/
- (void)serviceEvent:(MWCocoaEvent *)event {
	[matlabLock lock];
	if(running == NSControlStateValueOn) {
		if([event code] == [[delegate codeForTag:sync_event_name] intValue]) {
			Datum *syncData = [event data];
			if(syncData->getInteger() > 0 && !collectingEvents) {
				collectingEvents = YES;
				[eventList removeAllObjects];
			} else if(syncData->getInteger() == 0) {
				if(collectingEvents) {
					collectingEvents = NO;
					[eventList addObject:event];
					[executionList addObject:[NSArray arrayWithArray:eventList]];
					[eventList removeAllObjects];
				}
			}
		}

		if(collectingEvents) {
			[eventList addObject:event];
		}
	}
	[matlabLock unlock];
}

#define MATLAB_DEBUG_OUTPUT_MAX_LENGTH 10000

- (IBAction)changeScrollToBottom:(id)sender {
	if ([sender state] == NSControlStateValueOn) {
		[self doScrollToBottom];
		scrollToBottom = TRUE;
	} else {
		scrollToBottom = FALSE;
	}
	[[NSUserDefaults standardUserDefaults] setBool:scrollToBottom forKey:MW_SCROLL_TO_BOTTOM];

	//if ([sender state] == NSControlStateValueOff) {
	// do nothing
}

// *******************************************************************
// *                           Private Methods
// *******************************************************************

- (void) doScrollToBottomMain {

	[logTextView scrollRangeToVisible:NSMakeRange([[logTextView textStorage] length], 0) ];

}

- (void) appendLogTextMain:(NSString *)logText {
    NSTextStorage *textStorage = logTextView.textStorage;
    [textStorage appendAttributedString:[[NSAttributedString alloc] initWithString:logText
                                                                        attributes:@{ NSForegroundColorAttributeName: [NSColor textColor] }]];

    NSMutableString* tStr = textStorage.mutableString;
	if ([tStr characterAtIndex:[tStr length]-1] != '\n') {
		// append newline
		[tStr appendString:@"\n"];
	}

	// Trim the beginning of the string if it is too long
	if ([tStr length] > MATLAB_DEBUG_OUTPUT_MAX_LENGTH) {
		NSRange deleteRange = NSMakeRange(0, ([tStr length] - MATLAB_DEBUG_OUTPUT_MAX_LENGTH));
			[tStr deleteCharactersInRange:deleteRange];
		}

		[self->logTextView setNeedsDisplay:YES];
		if (self->scrollToBottom) {
			[self doScrollToBottom];
		}
}

- (void)codecArrived:(MWCocoaEvent *)event {
	[matlabLock lock];

    Datum *new_codec = [event data];

    if (*new_codec == *savedCodec) {
        // Codec is unchanged.  No need to reset anything.
        [matlabLock unlock];
        return;
    }

	// need to force it by capturing the pointer so it makes it a dictionary
	delete savedCodec;
	savedCodec = new Datum(*new_codec);

	NSArray *current_selected_variables = [NSArray array];

	[self performSelectorOnMainThread:@selector(updateDefaultSelectedVariables:)
						   withObject:nil
						waitUntilDone:YES];

	@synchronized(vl) {

		[vl clear];

		// determine max code number of codec
		int max_key = -1;
        for (auto &item : new_codec->getDict()) {
            max_key = std::max(max_key, int(item.first));
        }

		for(int i=0;i<=max_key;++i) {
			Datum codec_entry(new_codec->getElement(Datum(M_INTEGER, i)));

			if(!codec_entry.isUndefined()) {
				NSString *variableName = [NSString stringWithCString:codec_entry.getElement("tagname").getString().c_str()
															encoding:NSASCIIStringEncoding];
				MWVarEntry *var = [[MWVarEntry alloc] initWithName:variableName];

				// select previous variables
				if(default_selected_variables != nil) {
					NSEnumerator *enumerator = [default_selected_variables objectEnumerator];
					NSString *selectedVariableName;

					while(selectedVariableName = [enumerator nextObject]) {
						if([selectedVariableName isEqualToString:variableName]) {
							[var setSelected:YES];
						}
					}
				}
				[vl addVariable:var];
			}
		}

		[vl setSyncEventName:[self syncEventName]];
		current_selected_variables = [vl currentSelectedVariables];
		[vl reloadData];
	}
	[matlabLock unlock];

	[self updateClientCallbacks:current_selected_variables];

	[self reset];
}

// must be run on main thread
- (void)updateDefaultSelectedVariables:(id)arg {
	default_selected_variables = [[NSArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:SELECTED_VAR_NAMES]];
}

- (void)updateClientCallbacks:(NSArray *)codes_to_register {
	[delegate unregisterCallbacksWithKey:[MATLAB_WINDOW_CALLBACK_KEY UTF8String]];

	// register for codecs
	[delegate registerEventCallbackWithReceiver:self
                                       selector:@selector(codecArrived:)
                                    callbackKey:[MATLAB_WINDOW_CALLBACK_KEY UTF8String]
								forVariableCode:RESERVED_CODEC_CODE
                                   onMainThread:YES];

	NSString *name;
	NSEnumerator *enumerator = [codes_to_register objectEnumerator];

	while(name = [enumerator nextObject]) {
		NSNumber *event_code = [delegate codeForTag:name];
		[delegate registerEventCallbackWithReceiver:self
                                           selector:@selector(serviceEvent:)
                                        callbackKey:[MATLAB_WINDOW_CALLBACK_KEY UTF8String]
									forVariableCode:[event_code intValue]
                                       onMainThread:YES];
	}
}

- (void)MATLABExecutionLoop:(id)obj {
	@autoreleasepool {
		do {
			@autoreleasepool {
				[matlabLock lock];
				self.numberToProcessString = [NSString stringWithFormat:@"Process %lu events", (unsigned long)[executionList count]];
				[matlabLock unlock];

				if(processing == NSControlStateValueOn) {
					NSArray *eventsToExecute = nil;
					[matlabLock lock];
					Datum codec(*savedCodec);
					if([executionList count] > 0 && codec.isDictionary()) {
						eventsToExecute = [executionList objectAtIndex:0];
						[executionList removeObjectAtIndex:0];
					}
					[matlabLock unlock];

					if(eventsToExecute != nil && codec.isDictionary()) {
						mxArray *dataStruct = [mi createDataStruct:eventsToExecute
														 withCodec:&codec];
						[mi runMatlabFile:dataStruct];
						mxDestroyArray(dataStruct);
					}
				}
				usleep(5000); // sleep to surrender the processor
			}
		} while (1);
	}
}

// this must be locked before being called
- (void)reset {
	[matlabLock lock];
	collectingEvents = NO;
	//	[delegate set:[[delegate codeForTag:[self syncEventName]] intValue] to:&sync_zero];
	//	[delegate setValue:[NSNumber numberWithInt:0] forKey:[@"variables." stringByAppendingString:self.syncEventName]];

	NSArray *variable_names = [delegate variableNames];
	NSEnumerator *var_name_enumerator = [variable_names objectEnumerator];
	NSString *var_name = nil;

	while(var_name = [var_name_enumerator nextObject]) {
		if([var_name isEqualToString:self.syncEventName]) {
			Datum data(0L);
			[delegate updateVariableWithTag:self.syncEventName
								   withData:&data];
		}
	}

	[mi resetRetval];
	[executionList removeAllObjects];
	[matlabLock unlock];
}

///////////////////////////////////////////////////////////////////////
// Delegate functions
///////////////////////////////////////////////////////////////////////

// this only gets called from the main thread
- (void)updateVariableFilter {
	[matlabLock lock];

	NSArray *selected_variables;

	@synchronized(vl) {
        selected_variables = [vl currentSelectedVariables];
	}

	if([selected_variables count] > 1) {
		// don't update the defaults until there is some variables to update
		[[NSUserDefaults standardUserDefaults] setObject:selected_variables forKey:SELECTED_VAR_NAMES];
	}

	[matlabLock unlock];
	[self updateClientCallbacks:selected_variables];
}

- (void) appendLogText:(NSString *)logText {

	[self performSelectorOnMainThread: @selector(appendLogTextMain:)
						   withObject: logText
						waitUntilDone: NO];
}

-(void) doScrollToBottom {

	[self performSelectorOnMainThread:@selector(doScrollToBottomMain)
						   withObject:nil
						waitUntilDone:YES];
}

- (NSDictionary *)workspaceState {
    NSMutableDictionary *workspaceState = [NSMutableDictionary dictionary];

    if (running == NSControlStateValueOn) {
        if (matlab_file_name) {
            [workspaceState setObject:matlab_file_name forKey:@"filePath"];
        }
        if (sync_event_name) {
            [workspaceState setObject:sync_event_name forKey:@"syncEventName"];
        }
        @synchronized(vl) {
            [workspaceState setObject:[vl currentSelectedVariables] forKey:@"selectedVariables"];
        }
    }

    return workspaceState;
}

- (void)setWorkspaceState:(NSDictionary *)workspaceState {
    NSString *newFilePath = [workspaceState objectForKey:@"filePath"];
    if (newFilePath && [newFilePath isKindOfClass:[NSString class]]) {
        newFilePath = [newFilePath mwk_absolutePath];
        [[NSUserDefaults standardUserDefaults] setObject:newFilePath forKey:MATLAB_M_FILE];
        [self setMatlabFileName:newFilePath];
    }

    NSString *newSyncEventName = [workspaceState objectForKey:@"syncEventName"];
    if (newSyncEventName && [newSyncEventName isKindOfClass:[NSString class]]) {
        [self setSyncEventName:newSyncEventName];
    }

    NSArray *newSelectedVariables = [workspaceState objectForKey:@"selectedVariables"];
    if (newSelectedVariables &&
        [newSelectedVariables isKindOfClass:[NSArray class]] &&
        [newSelectedVariables count] > 0)
    {
        [[NSUserDefaults standardUserDefaults] setObject:newSelectedVariables forKey:SELECTED_VAR_NAMES];
    }
}

@end


text:
package com.ztw.admin.basic.security;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

/**
 * ${DESCRIPTION}
 *
 * @author 马旭
 * @created 2017-07-09 10:06.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class JwtUser implements UserDetails {

    private final String id;
    private final String username;
    private final String nickname;
    private final String password;
    private final boolean status;
    private final Collection<? extends GrantedAuthority> authorities;

    public JwtUser(String id, String username, String nickname, String password, boolean status, Collection<? extends GrantedAuthority> authorities) {
        this.id = id;
        this.username = username;
        this.nickname = nickname;
        this.password = password;
        this.status = status;
        this.authorities = authorities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    public String getId() {
        return id;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public String getPassword() {
        return password;
    }

    public String getNickname() {
        return nickname;
    }

    public boolean isStatus() {
        return status;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return status;
    }
}


text:
<?php
/**
 * @package Techotronic
 * @subpackage All in one Favicon
 *
 * @since 4.0
 * @author Arne Franken
 *
 * Helper class for debugging variables in PHP.
 * see http://www.php.net/manual/en/function.var-dump.php
 *
 * In class:
 * var $debugger;
 *
 * In constructor:
 * global $debugger;
 * require_once('debugger.php');
 * $debugger = new AioFaviconDebugger();
 *
 * In method:
 * global $debugger;
 * $debugger->dieWithVariable($variable);
 */
class AioFaviconDebugger {

  /**
   * Calls wp_die with the given variable.
   *
   * @author Arne Franken
   * @access public
   *
   * @return void
   */
  //public function dieWithAllVariables() {
  function dieWithAllVariables() {
    wp_die(var_dump(get_defined_vars()));
  }

  // dieWithAllVariables()

  /**
   * Calls wp_die with the given variable.
   *
   * @author Arne Franken
   * @access public
   *
   * @param $variable the variable
   * @param $title
   *
   * @return void
   */
  //public function dieWithVariable($variable, $title = null) {
  function dieWithVariable($variable, $title = null) {
    wp_die($this->dumpVariable($variable), $title);
  }

  // dieWithVariable()

  //=====================================================================================================

  /**
   * Dumps the given variable into an HTML container
   *
   * @access private
   *
   * @param $var the variable
   * @param String $info display as a title
   *
   * @return void
   */
  //private function dumpVariable(&$var, $info = FALSE) {
  function dumpVariable(&$var, $info = FALSE) {
    $scope = false;
    $prefix = 'unique';
    $suffix = 'value';

    if ($scope) $vals = $scope;
    else $vals = $GLOBALS;

    $old = $var;
    $var = $new = $prefix . rand() . $suffix;
    $vname = FALSE;
    foreach ($vals as $key => $val) if ($val === $new) $vname = $key;
    $var = $old;

    echo "
";
    if ($info != FALSE) echo "$info:
";
    $this->doDumpVariable($var, '$' . $vname);
    echo "
";
  }

  // dumpVariable()

  /**
   * Dumps and formats variables
   *
   * @access private
   *
   * @param  $var
   * @param null $var_name
   * @param null $indent
   * @param null $reference
   *
   * @return void
   */
  //private function doDumpVariable(&$var, $var_name = NULL, $indent = NULL, $reference = NULL) {
  function doDumpVariable(&$var, $var_name = NULL, $indent = NULL, $reference = NULL) {
    $do_dump_indent = "|    ";
    $reference = $reference . $var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme';
    $keyname = 'referenced_object_name';

    if (is_array($var) && isset($var[$keyvar])) {
      $real_var = &$var[$keyvar];
      $real_name = &$var[$keyname];
      $type = ucfirst(gettype($real_var));
      echo "$indent$var_name $type = &$real_name
";
    }
    else {
      $var = array($keyvar => $var, $keyname => $reference);
      $avar = &$var[$keyvar];

      $type = ucfirst(gettype($avar));
      if ($type == "String") $type_color = "";
      elseif ($type == "Integer") $type_color = "";
      elseif ($type == "Double") {
        $type_color = "";
        $type = "Float";
      }
      elseif ($type == "Boolean") $type_color = "";
      elseif ($type == "NULL") $type_color = "";

      if (is_array($avar)) {
        $count = count($avar);
        echo "$indent" . ($var_name ? "$var_name => " : "") . "$type ($count)
$indent(
";
        $keys = array_keys($avar);
        foreach ($keys as $name) {
          $value = &$avar[$name];
          $this->doDumpVariable($value, "['$name']", $indent . $do_dump_indent, $reference);
        }
        echo "$indent)
";
      }
      elseif (is_object($avar)) {
        echo "$indent$var_name $type
$indent(
";
        foreach ($avar as $name => $value) $this->doDumpVariable($value, "$name", $indent . $do_dump_indent, $reference);
        echo "$indent)
";
      }
      elseif (is_int($avar)) echo "$indent$var_name = $type(" . strlen($avar) . ") $type_color$avar
";
      elseif (is_string($avar)) echo "$indent$var_name = $type(" . strlen($avar) . ") $type_color\"$avar\"
";
      elseif (is_float($avar)) echo "$indent$var_name = $type(" . strlen($avar) . ") $type_color$avar
";
      elseif (is_bool($avar)) echo "$indent$var_name = $type(" . strlen($avar) . ") $type_color" . ($avar == 1
              ? "TRUE" : "FALSE") . "
";
      elseif (is_null($avar)) echo "$indent$var_name = $type(" . strlen($avar) . ") {$type_color}NULL
";
      else echo "$indent$var_name = $type(" . strlen($avar) . ") $avar
";

      $var = $var[$keyvar];
    }
  }

  // doDumpVariable()

}

// Debugger()
?>


text:
var x = require('casper').selectXPath;
casper.on('page.error', function(msg, trace) {
   this.echo('Error: ' + msg, 'ERROR');
   for(var i=0; i<trace.length; i++) {
       var step = trace[i];
       this.echo('   ' + step.file + ' (line ' + step.line + ')', 'ERROR');
   }
});

captureScreen = function() {
   var file_name = casper.cli.get("output")+'test_click_search_for_1999_175_screen_error.png';
   this.capture(file_name);
   this.echo('Captured "'+file_name+'"');
}

casper.test.begin('Test search for 1999:175', function(test) {
   casper.start(casper.cli.get("url")+'/ui/');

   casper.then(function() {
        this.test.assertTitle('RInfo Service UI');
        this.test.assertTextDoesntExist('Sökresultat');
        this.sendKeys("#queryForm input[name='q']", "1999:175");
        this.click('#queryForm button[type="submit"]');
   });

   casper.waitForSelector("#resultsView h2", function(){}, captureScreen, 5000);

   casper.then(function() {
        this.test.assertTextExists("Sökresultat");
        this.test.assertExists("a[href='#/publ/sfs/1999:175/data.json']");
        this.click("a[href='#/publ/sfs/1999:175/data.json']");
   });

   casper.waitForSelector("#documentView h2", function(){}, captureScreen, 20000);

   casper.then(function() {
        this.test.assertSelectorHasText('#documentView h2', 'SFS 1999:175');
   })

   casper.run(function() {test.done();});
});


text:
layout: page
title: Pratt Motors Executive Retreat
date: 2016-05-24
author: Madison Mercado
tags: weekly links, java
status: published
summary: Donec feugiat nisi neque. Fusce imperdiet.
banner: images/banner/office-01.jpg
booking:
  startDate: 08/26/2019
  endDate: 08/28/2019
  ctyhocn: SAEVAHX
  groupCode: PMER
published: true
---
Donec euismod diam a elit ultrices, et scelerisque libero varius. Ut at sem sed ante pellentesque bibendum. Nunc pellentesque placerat nibh eu fringilla. Morbi dictum nisl vitae eros commodo, eget dictum turpis dignissim. Nullam sagittis massa et augue tempus, dictum tempor arcu ullamcorper. Vestibulum ut felis ut augue euismod porttitor in quis tortor. Nulla ac aliquam ex.

* Curabitur condimentum lacus nec lorem efficitur blandit
* Phasellus eu justo a ex accumsan tempor.

Fusce a mauris et metus sollicitudin ullamcorper. Maecenas ante ligula, dictum ac bibendum molestie, consequat eget lectus. Suspendisse viverra egestas ex eget feugiat. Mauris iaculis ornare dolor ac tincidunt. Suspendisse nec molestie libero, id malesuada lacus. Nulla id arcu fringilla, tincidunt enim a, interdum felis. Etiam venenatis sem at urna mattis auctor. Praesent turpis diam, vehicula ac viverra ultrices, elementum nec purus. Sed at vulputate odio. Sed malesuada id ante vel interdum. Vestibulum at tortor diam. Sed molestie nunc ac lectus vulputate sollicitudin. Nullam iaculis, enim eu hendrerit fermentum, sapien diam euismod tortor, eget pulvinar enim augue eget est. Vestibulum pellentesque pharetra ex sit amet elementum. Ut sit amet pellentesque sapien.


text:
class ControllerError(Exception):
    pass

class PhysicalDriveError(Exception):
    pass

class LogicalDriveError(Exception):
    pass


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Pilosocereus supthutianus P.J.Braun

### Remarks
null


text:
A simple template for starting on a Wpf MVVM project

# Requirements
Visual Studio 2012 or 2013 and with update 5 or greater


text:
package org.apache.camel.component.kafka;

/**
 * A fatal exception such as the kafka consumer is not able to be created and/or subscribed to the kafka brokers within
 * a given backoff period, leading to camel-kafka giving up and terminating the kafka consumer thread, meaning that the
 * kafka consumer will not try to recover. To recover requires either to restart the Camel route, or the application.
 */
public class KafkaConsumerFatalException extends RuntimeException {

    public KafkaConsumerFatalException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
<?php namespace Pingpong\Admin\Entities;

use Pingpong\Presenters\Model;

class Article extends Model {

    /**
     * @var string
     */
    protected $presenter = 'Pingpong\Admin\Presenters\Article';

    /**
     * @var array
     */
    protected $fillable = [
        'type',
        'user_id',
        'category_id',
        'title',
        'slug',
        'body',
        'image',
        'published_at'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(__NAMESPACE__ . '\\User');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(__NAMESPACE__ . '\\Category');
    }

    /**
     * Coming soon.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function comments()
    {
        return $this->morphMany('Comment', 'commentable');
    }

    /**
     * @param $query
     * @return mixed
     */
    public function scopeNewest($query)
    {
        return $query->orderBy('created_at', 'desc');
    }

    /**
     * @param $query
     * @return mixed
     */
    public function scopeOnlyPage($query)
    {
        return $query->whereType('page');
    }

    /**
     * @param $query
     * @return mixed
     */
    public function scopeOnlyPost($query)
    {
        return $query->whereType('post');
    }

    /**
     * @param $query
     * @return mixed
     */
    public function scopePublished($query)
    {
        return $query->whereNull('published_at');
    }

    /**
     * @param $query
     * @return mixed
     */
    public function scopeDrafted($query)
    {
        return $query->whereNotNull('published_at');
    }

    /**
     * @param $query
     * @param $id
     * @return mixed
     */
    public function scopeBySlugOrId($query, $id)
    {
        return $query->whereId($id)->orWhere('slug', '=', $id);
    }

    /**
     * Boot the eloquent.
     *
     * @return void
     */
    public static function boot()
    {
        parent::boot();

        static::deleting(function ($data)
        {
            $data->deleteImage();
        });
    }

    /**
     * @return bool
     */
    public function deleteImage()
    {
        $file = $this->present()->image_path;

        if (file_exists($file))
        {
            @unlink($file);

            return true;
        }

        return false;
    }
}


text:
package ee.telekom.workflow.graph;

import ee.telekom.workflow.graph.core.GraphInstanceImpl;

/**
 * A {@link GraphEngineFacade} is the interface that external systems should use
 * to communicated with a graph engine.
 *
 *

 *
 * An graph engine executes a workflow. A {@link Graph} specifies how it should
 * be executed and a {@link GraphInstance} tracks the current state of
 * execution. It is an graph engine which creates instances of
 * {@link GraphInstance} and {@link Token}.
 *
 * Engines must be thread-safe. Thus implementations of interface may be safely
 * shared among threads.
 */
public interface GraphEngineFacade{

    /**
     * A shorthand for {@link #start(String, Integer, Environment, String)} using
     * the latest graph with the given name and an empty initial environment and
     * a null external id.
     */
    GraphInstance start( String graphName );

    /**
     * A shorthand for {@link #start(String, Integer, Environment, String)} using
     * an empty initial environment and a null external id.
     */
    GraphInstance start( String graphName, Integer version );

    /**
     * A shorthand for {@link #start(String, Integer, Environment, String)} using a
     * null external id.
     */
    GraphInstance start( String graphName, Integer version, Environment initialEnvironment );

    /**
     * Starts a {@link GraphInstance} of the {@link Graph} with the given name
     * and version and using the given {@link Environment} and associates the created
     * {@link GraphInstance} with the given external. Is the equivalent of doing
     *
     *

     * Graph graph = engine.getRepository().getLatestGraph(graphName);
     * GraphInstance graphInstance = engine.start(graph, initialEnvironment,
     * 		externalId);
     *

     *
     * If no graph is found for the given graphName, a {@link WorkflowException}
     * will be thrown.
     *
     * @param graphName
     *            the name of the graph to execute
     * @param version
     *            the version of the graph to execute of null for
     *            the latest graph with the given name.
     * @param initialEnvironment
     *            A starting environment for the {@link GraphInstance}. All
     *            attributes from this environment will be copied into the new
     *            graph instance's environment before execution starts.
     * @param externalId
     *            the external id that the graph instance is associated with
     * @throws WorkflowException
     *             If no graph is found with the given graphName
     *
     * @return a {@link GraphInstance} of the latest {@link Graph} with the
     *         given name and using the given {@link Environment} which has
     *         already been started (and, given that no wait states were
     *         entered, is already completed).
     */
    GraphInstance start( String graphName, Integer version, Environment initialEnvironment, Long externalId );

    /**
     * A shorthand for {@link #start(Graph, Environment, String)} using an empty
     * initial environment and a null external id.
     */
    GraphInstance start( Graph graph );

    GraphInstance start( Graph graph, Environment initialEnvironment );

    /**
     * Starts a {@link GraphInstance} of the given {@link Graph} using the given
     * {@link Environment}. A {@link Token} will be generated for the start node
     * (determined by {@link Graph#getStartNode()}), and this token will be
     * executed. If the graph does not contain nodes which go into a wait state,
     * the {@link GraphInstance} returned will be completed.
     *

     * Before the graph instance is started, the given initial environment will
     * be copied into the one of the new graph instance.
     *
     * @param graph
     *            the graph to create a graph instance of
     * @param initialEnvironment
     *            an initial environment for the graph instance
     * @param externalId
     *            the external id that the graph instance is associated with
     */
    GraphInstanceImpl start( Graph graph, Environment initialEnvironment, Long externalId );

    /**
     * Aborts the given {@link GraphInstance}'s execution and cancels all
     * associated tokens and work items.
     *
     * @param instance
     *            the graph instance to abort
     */
    void abort( GraphInstance instance );

    /**
     * Completes the executed work item and continues execution until another
     * wait state is reached or until the graph instance is completed.
     *
     * @param workItem
     *            the work item to complete
     */
    void complete( GraphWorkItem workItem );

    /**
     * Returns the engine's {@link GraphRepository}.
     *
     * @return the engine's {@link GraphRepository}
     */
    GraphRepository getRepository();

    /**
     * Returns the engine's {@link BeanResolver}, or null
     * if the engine does not support to resolve beans.
     *
     * @return the engine's {@link BeanResolver}, or null
     * if the engine does not support to resolve beans.
     */
    BeanResolver getBeanResolver();

    /**
     * Returns the engine's {@link NewGraphInstanceCreator}, or null
     * if the engine does not support to create sub graph instances.
     *
     * @return the engine's {@link NewGraphInstanceCreator}, or null
     * if the engine does not support to create sub graph instances.
     */
    NewGraphInstanceCreator getNewGraphInstanceCreator();

    /**
     * Adds a {@link GraphInstanceEventListener} to the engine.
     *
     * @param listener
     *            listener to be added
     */
    void registerInstanceEventListener( GraphInstanceEventListener listener );

    /**
     * Adds a {@link GraphWorkItemEventListener} to the engine.
     *
     * @param listener
     *            listener to be added
     */
    void registerWorkItemEventListener( GraphWorkItemEventListener listener );

    /**
     * Adds a {@link NodeEventListener} to the engine.
     *
     * @param listener
     *            listener to be added
     */
    void registerNodeEventListener( NodeEventListener listener );

}


text:
require 'spec_helper'
require Rails.root.join("lib/migrations/gws/20200203000000_use_portal_permissions.rb")

RSpec.describe SS::Migration20200203000000, dbscope: :example do
  let(:site) { gws_site }
  let!(:role1) { create :gws_role }
  let!(:role2) { create :gws_role_admin }

  before do
    described_class.new.change
  end

  it do
    role1.reload
    expect(role1.permissions).to include("use_gws_portal_user_settings", "use_gws_portal_group_settings",
      "use_gws_portal_organization_settings")

    role2.reload
    expect(role2.permissions).to include("use_gws_portal_user_settings", "use_gws_portal_group_settings",
      "use_gws_portal_organization_settings")
  end
end


text:
//
//  DZProgressController.h
//  DZProgressController
//
//  (c) 2012 Zachary Waldowski.
//  (c) 2009-2011 Matej Bukovinski and contributors.
//  This code is licensed under MIT. See LICENSE for more information.
//

#import <UIKit/UIKit.h>

/** When set as the HUD's custom view, the HUD will show a check image. **/
extern const id DZProgressControllerSuccessView;

/** When set as the HUD's custom view, the HUD will show an error image. **/
extern const id DZProgressControllerErrorView;

typedef enum {
    /** Progress is shown using an UIActivityIndicatorView. This is the default. */
    DZProgressControllerModeIndeterminate,
    /** Progress is shown using a DZRoundProgressView. */
	DZProgressControllerModeDeterminate,
	/** Shows a custom view */
	DZProgressControllerModeCustomView
} DZProgressControllerMode;

@interface DZProgressController : UIViewController <UIAppearanceContainer>

/**
 * Creates a new HUD and shows it on the current window.
 *
 * @returns A reference to the created HUD.
 *
 * @see showOnView:
 * @see hide
 */
+ (DZProgressController *)show;

/**
 * Shows a HUD on the current window using while executing a block in the background.
 *
 * The block is executed from a separate queue unrelated to the UI main thread. The HUD is passed
 * as an argument to the block for progress updates, changes, and so on. The HUD should not be
 * dismissed from within the block; instead, bail out using a return statement.
 *
 * @param block A code block to be executed. Should not be NULL.
 *
 * @see showWithText:whileExecuting:
 */
+ (void)showWhileExecuting:(void(^)(DZProgressController *))block;

/**
 * Shows a HUD on the current window using while executing a block in the background.
 *
 * The block is executed from a separate queue unrelated to the UI main thread. The HUD is passed
 * as an argument to the block for progress updates, changes, and so on. The HUD should not be
 * dismissed from within the block; instead, bail out using a return statement.
 *
 * @param statusText The text for the main label. Send an empty string to not show the label at all.
 * @param block A code block to be executed. Should not be NULL.
 *
 * @see label
 * @see showWhileExecuting:
 */
+ (void)showWithText:(NSString *)statusText whileExecuting:(void(^)(DZProgressController *))block;

/**
 * The view to be shown when the HUD is set to DZProgressControllerModeCustomView.
 * For best results, use a 37x37 pt view (so the bounds match the default indicator bounds).
 *
 * Pass `DZProgressControllerSuccessView` for an image view with a check.
 * Pass `DZProgressControllerErrorView`, for an image view with an error symbol.
 **/
@property (nonatomic, strong) UIView *customView;

/**
 * HUD operation mode. The default is DZProgressControllerModeModeIndeterminate.
 *
 * @see DZProgressControllerMode
 */
@property (nonatomic) DZProgressControllerMode mode;

/**
 * Returns the label used for the main textual content of the HUD.
 */
@property (nonatomic, strong, readonly) UILabel *label;

/**
 * The progress of the progress indicator, from 0.0 to 1.0. Always animated.
 */
@property (nonatomic) CGFloat progress;

/** A callback fired when the HUD is tapped. */
@property (nonatomic, copy) void(^wasTappedBlock)(DZProgressController *);

/** A callback fired when the HUD is hidden. */
@property (nonatomic, copy) void(^wasHiddenBlock)(DZProgressController *);

/*
 * The show delay is the time (in seconds) that your method may run without the HUD
 * being shown. If the task finishes before the grace time runs out, the HUD will
 * not appear at all.
 *
 * Defaults to 0. If you don't set one and still might have a short task,
 * it is recommended to set a minimum show time instead.
 *
 * @see minimumShowTime
 */
@property (nonatomic) NSTimeInterval showDelayTime;

/**
 * The minimum time (in seconds) that the HUD is shown.
 * This avoids the problem of the HUD being shown and than instantly hidden.
 *
 * Defaults to 1.5. If you don't set one and your task might run short,
 * it is recommended to instead set a show delay time.
 *
 * @see showDelayTime
 */
@property (nonatomic) NSTimeInterval minimumShowTime;

/**
 * Returns whether or not the HUD is currently visible.
 */
@property (nonatomic, readonly, getter = isVisible) BOOL visible;

/**
 * Display the HUD. All user interaction with the app is disabled while the HUD is shown.
 */
- (void)show;

/**
 * Hide the HUD when your task completes.
 */
- (void)hide;

/**
 * Shows the HUD while a task is executing in a background queue, then hides it.
 *
 * This method also takes care of an autorelease pool so your method does not have
 * to be concerned with setting one up.
 *
 * @param block A code block to be executed while the HUD is shown.
 */
- (void)showWhileExecuting:(void(^)(void))block;

/**
 * Coalesces changes to the HUD (mode, view, text, fonts) into a single animation.
 *
 * This method is non-blocking, but the HUD cannot be hidden while animations are ongoing.
 *
 * @param A code block of changes to the HUD. Will be executed from within a transition method.
 */
- (void)performChanges:(void(^)(void))animations;

@end


text: from api.settings.default import *


text:
package com.microsoft.example;

import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisDataException;

/**
 * A very simplified FIFO queue structure, implemented with Jedis.
 *
 * @author Christopher Kilding
 * @date 29/11/2012
 */

public class JedisQueue {
	private transient Jedis jedis;

	  private String pattern;

	  /**
	   * @param jedis
	   * @param pattern
	   */
	  public JedisQueue(Jedis jedis, String pattern) {
	    this.jedis = jedis;
	    this.pattern = pattern;
	  }

	  /**
	   * Clear out the values for this.pattern
	   */
	  public void clear() {
	    this.jedis.del(this.pattern);

	  }

	  /**
	   * @return whether this.pattern maps to no values
	   *
	   */
	  public boolean isEmpty() {
	    return (this.size() == 0);
	  }

	  /**
	   * @return the number of values for this.pattern
	   */
	  public int size() {
	    return new Integer(this.jedis.llen(this.pattern).toString());
	  }

	  /**
	   * @return
	   *  serialized form of the Jedis queue
	   */
	  public List<String> toArray() {
	    return this.jedis.lrange(this.pattern, 0, -1);
	  }

	  /**
	   * @param elems the element(s) to add
	   */
	  public void enqueue(String... elems) {
	    this.jedis.rpush(this.pattern, elems);
	  }

	  /**
	   * @return the next item in the queue, popped
	   *
	   */
	  public List<String> dequeue() {
	    List<String> out = null;
	    try {
	      out = this.jedis.blpop(0, this.pattern);
	    }
	    catch (JedisDataException e) {
	      // It wasn't a list of strings
	    }

	    return out;
	  }
}


text:
require 'dnc/dn'

#
# Extend the core String class to include `.to_dn` && `.to_dn!`
#
class String
  # Parses the string to return a DN object
  # Returns nil if a DN instance cannot be created
  def to_dn
    begin
      new_dn = DN.new(dn_string: to_s)
    rescue StandardError
      new_dn = nil
    end

    new_dn
  end

  # Similar to {#to_dn}, but raises an error unless the string can be
  # explicitly parsed to a DN instance
  def to_dn!
    begin
      new_dn = DN.new(dn_string: to_s)
    rescue StandardError
      raise DnStringUnparsableError,
            "Could not force conversion to DN:\n#{inspect}"
    end

    new_dn
  end
end


text:
'''Unit test package for module "tws._TagValue".'''

__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__   = "$Id$"

import unittest
from tws import TagValue

class test_TagValue(unittest.TestCase):
    '''Test type "tws.TagValue"'''

    def test_init(self):
        test1 = TagValue()
        test2 = TagValue("AB","CD")
        self.assertEqual(test1.m_tag, "")
        self.assertEqual(test1.m_value, "")
        self.assertEqual(test2.m_tag, "AB")
        self.assertEqual(test2.m_value, "CD")

    def test_fields(self):
        test = TagValue()
        test.m_tag = "ab"
        test.m_value = "cd"
        self.assertEqual(test.m_tag, "ab")
        self.assertEqual(test.m_value, "cd")

    def test_equals(self):
        test1 = TagValue()
        test2 = TagValue()
        test3 = TagValue("AB","CD")

        self.assertEqual(test1, test1)
        self.assertEqual(test1, test2)
        self.assertNotEqual(test1, None)
        self.assertNotEqual(test1, "")
        self.assertEqual(test3, test3)
        self.assertNotEqual(test1, test3)